From b42aae41eba3831a1c154113bcc1325fa98ce953 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:16:31 +0100 Subject: [PATCH 01/11] Chore: Use .NET 7 syntax --- .../BaudValidator.cs | 37 +++--- .../ContainsTextValidator.cs | 11 +- ...ryPathWithEnvironmentVariablesValidator.cs | 25 ++-- .../DomainValidator.cs | 11 +- .../EmptyOrAWSRegionExistsValidator.cs | 24 ++-- .../EmptyOrFileExistsValidator.cs | 15 ++- .../EmptyOrIPv4AddressValidator.cs | 15 ++- .../EmptyOrPortRangeValidator.cs | 61 +++++---- .../EmptyValidator.cs | 11 +- .../FileExistsValidator.cs | 11 +- .../FileNameValidator.cs | 29 +++-- .../FilePathValidator.cs | 23 ++-- .../FolderInPathExistsValidator.cs | 33 +++-- .../GroupNameValidator.cs | 17 ++- .../HttpAndHttpsUriValidator.cs | 11 +- .../IPAddressOrHostnameAsRangeValidator.cs | 39 +++--- .../IPAddressOrHostnameValidator.cs | 35 +++--- .../IPv4AddressValidator.cs | 17 ++- .../IPv4IPv6SubnetValidator.cs | 36 +++--- .../IPv4IPv6SubnetmaskOrCIDRValidator.cs | 39 +++--- .../IPv4SubnetValidator.cs | 25 ++-- .../IPv4SubnetmaskOrCIDRValidator.cs | 31 +++-- .../IPv6AddressValidator.cs | 19 ++- .../Int32Validator.cs | 11 +- .../NETworkManager.Validators/IsNameUnique.cs | 17 ++- .../IsNameUniqueDependencyObjectWrapper.cs | 21 ++-- .../MACAddressValidator.cs | 11 +- .../MultipleHostsRangeValidator.cs | 117 +++++++++--------- .../MultipleIPAddressesValidator.cs | 27 ++-- .../NoSpacesValidator.cs | 15 ++- .../NotEndWithSemicolonValidator.cs | 11 +- .../NumberValidator.cs | 11 +- .../NETworkManager.Validators/OIDValidator.cs | 27 ++-- .../PortRangeValidator.cs | 57 +++++---- .../PortValidator.cs | 19 ++- .../PowerShellPathValidator.cs | 15 ++- .../ProfileFileUniqueValidator.cs | 11 +- .../PuTTYPathValidator.cs | 15 ++- .../RemoteDesktopHostnameAndPortValidator.cs | 33 +++-- .../ServerDependencyObjectWrapper.cs | 21 ++-- .../ServerValidator.cs | 43 ++++--- .../SubnetmaskValidator.cs | 11 +- .../TigerVNCPathValidator.cs | 21 ++-- 43 files changed, 524 insertions(+), 565 deletions(-) diff --git a/Source/NETworkManager.Validators/BaudValidator.cs b/Source/NETworkManager.Validators/BaudValidator.cs index ae83515ca0..46b400b444 100644 --- a/Source/NETworkManager.Validators/BaudValidator.cs +++ b/Source/NETworkManager.Validators/BaudValidator.cs @@ -2,27 +2,26 @@ using System.Linq; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class BaudValidator : ValidationRule { - public class BaudValidator : ValidationRule - { - /// - /// Possible baud rates. - /// - private readonly int[] _bauds = { 75, 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200 }; + /// + /// Possible baud rates. + /// + private readonly int[] _bauds = { 75, 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200 }; - /// - /// Check if the int is a valid baud rate. - /// - /// Baud like 9600. - /// Culture to use for validation. - /// True if the value is a valid baut rate. - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - if (!int.TryParse(value as string, out var baud)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidBaud); + /// + /// Check if the int is a valid baud rate. + /// + /// Baud like 9600. + /// Culture to use for validation. + /// True if the value is a valid baut rate. + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + if (!int.TryParse(value as string, out var baud)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidBaud); - return _bauds.Contains(baud) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidBaud); - } + return _bauds.Contains(baud) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidBaud); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/ContainsTextValidator.cs b/Source/NETworkManager.Validators/ContainsTextValidator.cs index d9f30bc7f7..8e8f9b381c 100644 --- a/Source/NETworkManager.Validators/ContainsTextValidator.cs +++ b/Source/NETworkManager.Validators/ContainsTextValidator.cs @@ -3,13 +3,12 @@ using System.Windows.Controls; using NETworkManager.Localization.Resources; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class ContainsTextValidator : ValidationRule { - public class ContainsTextValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return ((string)value).All(char.IsWhiteSpace) ? new ValidationResult(false, Strings.InputDoesNotContainAnyText) : ValidationResult.ValidResult; - } + return ((string)value).All(char.IsWhiteSpace) ? new ValidationResult(false, Strings.InputDoesNotContainAnyText) : ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/DirectoryPathWithEnvironmentVariablesValidator.cs b/Source/NETworkManager.Validators/DirectoryPathWithEnvironmentVariablesValidator.cs index b04bc999e7..abc56340a0 100644 --- a/Source/NETworkManager.Validators/DirectoryPathWithEnvironmentVariablesValidator.cs +++ b/Source/NETworkManager.Validators/DirectoryPathWithEnvironmentVariablesValidator.cs @@ -5,24 +5,23 @@ using NETworkManager.Utilities; using System; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +/// +/// Check if the string is a valid directory path (like "C:\Temp\" or "%AppData%\Temp"). The directory path does not have to exist on the local system. +/// +public class DirectoryPathWithEnvironmentVariablesValidator : ValidationRule { /// /// Check if the string is a valid directory path (like "C:\Temp\" or "%AppData%\Temp"). The directory path does not have to exist on the local system. /// - public class DirectoryPathWithEnvironmentVariablesValidator : ValidationRule + /// Directory path like "C:\test" or "%AppData%\test". + /// Culture to use for validation. + /// True if the directory path is valid. + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - /// - /// Check if the string is a valid directory path (like "C:\Temp\" or "%AppData%\Temp"). The directory path does not have to exist on the local system. - /// - /// Directory path like "C:\test" or "%AppData%\test". - /// Culture to use for validation. - /// True if the directory path is valid. - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var path = Environment.ExpandEnvironmentVariables((string)value); + var path = Environment.ExpandEnvironmentVariables((string)value); - return new Regex(RegexHelper.FilePathRegex, RegexOptions.IgnoreCase).IsMatch(path) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidFilePath); - } + return new Regex(RegexHelper.FilePathRegex, RegexOptions.IgnoreCase).IsMatch(path) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidFilePath); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/DomainValidator.cs b/Source/NETworkManager.Validators/DomainValidator.cs index 4bee9747b0..2e8ef5d6e6 100644 --- a/Source/NETworkManager.Validators/DomainValidator.cs +++ b/Source/NETworkManager.Validators/DomainValidator.cs @@ -4,13 +4,12 @@ using NETworkManager.Localization.Resources; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class DomainValidator : ValidationRule { - public class DomainValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return Regex.IsMatch((string) value, RegexHelper.DomainRegex) ? ValidationResult.ValidResult : new ValidationResult(false,Strings.EnterValidDomain); - } + return Regex.IsMatch((string) value, RegexHelper.DomainRegex) ? ValidationResult.ValidResult : new ValidationResult(false,Strings.EnterValidDomain); } } diff --git a/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs b/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs index a0e5c65218..df175bdd4f 100644 --- a/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs +++ b/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs @@ -2,21 +2,21 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; +namespace NETworkManager.Validators; + +public class EmptyOrAWSRegionExistsValidator : ValidationRule { - public class EmptyOrAWSRegionExistsValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var region = value as string; + var region = value as string; - if (string.IsNullOrEmpty(region)) - return ValidationResult.ValidResult; - - if (AWSRegion.GetInstance().RegionExists(region)) - return ValidationResult.ValidResult; + if (string.IsNullOrEmpty(region)) + return ValidationResult.ValidResult; + + if (AWSRegion.GetInstance().RegionExists(region)) + return ValidationResult.ValidResult; - return new ValidationResult(false, string.Format(Localization.Resources.Strings.AnAWSRegionNamedXDoesNotExist, region)); - } + return new ValidationResult(false, string.Format(Localization.Resources.Strings.AnAWSRegionNamedXDoesNotExist, region)); } } diff --git a/Source/NETworkManager.Validators/EmptyOrFileExistsValidator.cs b/Source/NETworkManager.Validators/EmptyOrFileExistsValidator.cs index 1c043ef3b5..71c5900faa 100644 --- a/Source/NETworkManager.Validators/EmptyOrFileExistsValidator.cs +++ b/Source/NETworkManager.Validators/EmptyOrFileExistsValidator.cs @@ -2,16 +2,15 @@ using System.IO; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class EmptyOrFileExistsValidator : ValidationRule { - public class EmptyOrFileExistsValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - if (string.IsNullOrEmpty(value as string)) - return ValidationResult.ValidResult; + if (string.IsNullOrEmpty(value as string)) + return ValidationResult.ValidResult; - return File.Exists((string)value) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.FileDoesNotExist); - } + return File.Exists((string)value) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.FileDoesNotExist); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/EmptyOrIPv4AddressValidator.cs b/Source/NETworkManager.Validators/EmptyOrIPv4AddressValidator.cs index 9a02dbe4e5..434c0819e4 100644 --- a/Source/NETworkManager.Validators/EmptyOrIPv4AddressValidator.cs +++ b/Source/NETworkManager.Validators/EmptyOrIPv4AddressValidator.cs @@ -3,16 +3,15 @@ using System.Text.RegularExpressions; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class EmptyOrIPv4AddressValidator : ValidationRule { - public class EmptyOrIPv4AddressValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - if (string.IsNullOrEmpty(value as string)) - return ValidationResult.ValidResult; + if (string.IsNullOrEmpty(value as string)) + return ValidationResult.ValidResult; - return Regex.IsMatch((string)value, RegexHelper.IPv4AddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv4Address); - } + return Regex.IsMatch((string)value, RegexHelper.IPv4AddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv4Address); } } diff --git a/Source/NETworkManager.Validators/EmptyOrPortRangeValidator.cs b/Source/NETworkManager.Validators/EmptyOrPortRangeValidator.cs index 8b14275a69..a07b786d66 100644 --- a/Source/NETworkManager.Validators/EmptyOrPortRangeValidator.cs +++ b/Source/NETworkManager.Validators/EmptyOrPortRangeValidator.cs @@ -1,51 +1,50 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class EmptyOrPortRangeValidator : ValidationRule { - public class EmptyOrPortRangeValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - if (string.IsNullOrEmpty(value as string)) - return ValidationResult.ValidResult; + if (string.IsNullOrEmpty(value as string)) + return ValidationResult.ValidResult; - var isValid = true; + var isValid = true; - if (value == null) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); + if (value == null) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); - foreach (var portOrRange in ((string)value).Replace(" ", "").Split(';')) + foreach (var portOrRange in ((string)value).Replace(" ", "").Split(';')) + { + if (portOrRange.Contains('-')) { - if (portOrRange.Contains('-')) - { - var portRange = portOrRange.Split('-'); + var portRange = portOrRange.Split('-'); - if (int.TryParse(portRange[0], out var startPort) && int.TryParse(portRange[1], out var endPort)) - { - if (!((startPort > 0) && (startPort < 65536) && (endPort > 0) && (endPort < 65536) && (startPort < endPort))) - isValid = false; - } - else - { + if (int.TryParse(portRange[0], out var startPort) && int.TryParse(portRange[1], out var endPort)) + { + if (!((startPort > 0) && (startPort < 65536) && (endPort > 0) && (endPort < 65536) && (startPort < endPort))) isValid = false; - } } else { - if (int.TryParse(portOrRange, out var portNumber)) - { - if (!((portNumber > 0) && (portNumber < 65536))) - isValid = false; - } - else - { + isValid = false; + } + } + else + { + if (int.TryParse(portOrRange, out var portNumber)) + { + if (!((portNumber > 0) && (portNumber < 65536))) isValid = false; - } + } + else + { + isValid = false; } } - - return isValid ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); } + + return isValid ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/EmptyValidator.cs b/Source/NETworkManager.Validators/EmptyValidator.cs index f3fa89a0db..2ef2591de8 100644 --- a/Source/NETworkManager.Validators/EmptyValidator.cs +++ b/Source/NETworkManager.Validators/EmptyValidator.cs @@ -1,13 +1,12 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class EmptyValidator : ValidationRule { - public class EmptyValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return string.IsNullOrEmpty((string)value) ? new ValidationResult(false, Localization.Resources.Strings.FieldCannotBeEmpty) : ValidationResult.ValidResult; - } + return string.IsNullOrEmpty((string)value) ? new ValidationResult(false, Localization.Resources.Strings.FieldCannotBeEmpty) : ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/FileExistsValidator.cs b/Source/NETworkManager.Validators/FileExistsValidator.cs index 4ae9a14618..f875e1aa80 100644 --- a/Source/NETworkManager.Validators/FileExistsValidator.cs +++ b/Source/NETworkManager.Validators/FileExistsValidator.cs @@ -2,13 +2,12 @@ using System.IO; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class FileExistsValidator : ValidationRule { - public class FileExistsValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return File.Exists((string)value) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.FileDoesNotExist); - } + return File.Exists((string)value) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.FileDoesNotExist); } } diff --git a/Source/NETworkManager.Validators/FileNameValidator.cs b/Source/NETworkManager.Validators/FileNameValidator.cs index 5a5888c66b..683cb4631d 100644 --- a/Source/NETworkManager.Validators/FileNameValidator.cs +++ b/Source/NETworkManager.Validators/FileNameValidator.cs @@ -4,25 +4,24 @@ using System.Windows.Controls; using NETworkManager.Localization.Resources; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +/// +/// Check if the filename is a valid file name (like "text.txt"). The file name does not have to exist on the local system. +/// +public class FileNameValidator : ValidationRule { /// - /// Check if the filename is a valid file name (like "text.txt"). The file name does not have to exist on the local system. + /// Check if the filename is a valid file name (like "text.txt"). The filen ame does not have to exist on the local system. /// - public class FileNameValidator : ValidationRule + /// File name like "test.txt" or "README.md". + /// Culture to use for validation. + /// True if the file name is valid. + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - /// - /// Check if the filename is a valid file name (like "text.txt"). The filen ame does not have to exist on the local system. - /// - /// File name like "test.txt" or "README.md". - /// Culture to use for validation. - /// True if the file name is valid. - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var filename = (string)value; + var filename = (string)value; - // Check if the filename has valid chars and a dot. - return filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && new Regex(@"^.+\..+$").IsMatch(filename) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidFileName); - } + // Check if the filename has valid chars and a dot. + return filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && new Regex(@"^.+\..+$").IsMatch(filename) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidFileName); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/FilePathValidator.cs b/Source/NETworkManager.Validators/FilePathValidator.cs index 8126cc7a1c..cb91bc346d 100644 --- a/Source/NETworkManager.Validators/FilePathValidator.cs +++ b/Source/NETworkManager.Validators/FilePathValidator.cs @@ -4,22 +4,21 @@ using NETworkManager.Localization.Resources; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +/// +/// Check if the string is a valid file path (like "C:\Temp\Test.txt"). The file path does not have to exist on the local system. +/// +public class FilePathValidator : ValidationRule { /// /// Check if the string is a valid file path (like "C:\Temp\Test.txt"). The file path does not have to exist on the local system. /// - public class FilePathValidator : ValidationRule + /// File path like "C:\Temp\Test.txt"". + /// Culture to use for validation. + /// True if the file path is valid. + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - /// - /// Check if the string is a valid file path (like "C:\Temp\Test.txt"). The file path does not have to exist on the local system. - /// - /// File path like "C:\Temp\Test.txt"". - /// Culture to use for validation. - /// True if the file path is valid. - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return new Regex(RegexHelper.FullNameRegex, RegexOptions.IgnoreCase).IsMatch((string)value) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidFilePath); - } + return new Regex(RegexHelper.FullNameRegex, RegexOptions.IgnoreCase).IsMatch((string)value) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidFilePath); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/FolderInPathExistsValidator.cs b/Source/NETworkManager.Validators/FolderInPathExistsValidator.cs index d22c9ed7a0..0cabd43b0b 100644 --- a/Source/NETworkManager.Validators/FolderInPathExistsValidator.cs +++ b/Source/NETworkManager.Validators/FolderInPathExistsValidator.cs @@ -3,27 +3,26 @@ using System.Windows.Controls; using NETworkManager.Localization.Resources; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +/// +/// Check if the folder in the full path exists on the system (like "C:\Temp" from "C:\Temp\export.json"). +/// +public class FolderInPathExistsValidator : ValidationRule { /// - /// Check if the folder in the full path exists on the system (like "C:\Temp" from "C:\Temp\export.json"). + /// Check if the string is a valid file path (like "C:\Temp\Test.txt"). The file path does not have to exist on the local system. /// - public class FolderInPathExistsValidator : ValidationRule + /// File path like "C:\Temp\Test.txt"". + /// Culture to use for validation. + /// True if the folder exists. + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - /// - /// Check if the string is a valid file path (like "C:\Temp\Test.txt"). The file path does not have to exist on the local system. - /// - /// File path like "C:\Temp\Test.txt"". - /// Culture to use for validation. - /// True if the folder exists. - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - string path = Path.GetDirectoryName((string)value); + string path = Path.GetDirectoryName((string)value); - if (Directory.Exists(path)) - return ValidationResult.ValidResult; - else - return new ValidationResult(false, Strings.FolderDoesNotExist); - } + if (Directory.Exists(path)) + return ValidationResult.ValidResult; + else + return new ValidationResult(false, Strings.FolderDoesNotExist); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/GroupNameValidator.cs b/Source/NETworkManager.Validators/GroupNameValidator.cs index 13cfa05736..c8a295d86c 100644 --- a/Source/NETworkManager.Validators/GroupNameValidator.cs +++ b/Source/NETworkManager.Validators/GroupNameValidator.cs @@ -1,18 +1,17 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class GroupNameValidator : ValidationRule { - public class GroupNameValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var groupName = value as string; + var groupName = value as string; - if (groupName.StartsWith("~")) - return new ValidationResult(false, string.Format(Localization.Resources.Strings.GroupNameCannotStartWithX, "~")); + if (groupName.StartsWith("~")) + return new ValidationResult(false, string.Format(Localization.Resources.Strings.GroupNameCannotStartWithX, "~")); - return ValidationResult.ValidResult; - } + return ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/HttpAndHttpsUriValidator.cs b/Source/NETworkManager.Validators/HttpAndHttpsUriValidator.cs index bd8d4821b5..27cbf99cb2 100644 --- a/Source/NETworkManager.Validators/HttpAndHttpsUriValidator.cs +++ b/Source/NETworkManager.Validators/HttpAndHttpsUriValidator.cs @@ -2,13 +2,12 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class HttpAndHttpsUriValidator : ValidationRule { - public class HttpAndHttpsUriValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return Uri.TryCreate(value as string, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidWebsiteUri); - } + return Uri.TryCreate(value as string, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidWebsiteUri); } } diff --git a/Source/NETworkManager.Validators/IPAddressOrHostnameAsRangeValidator.cs b/Source/NETworkManager.Validators/IPAddressOrHostnameAsRangeValidator.cs index 0473a1690a..c490880601 100644 --- a/Source/NETworkManager.Validators/IPAddressOrHostnameAsRangeValidator.cs +++ b/Source/NETworkManager.Validators/IPAddressOrHostnameAsRangeValidator.cs @@ -4,31 +4,30 @@ using NETworkManager.Localization.Resources; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IPAddressOrHostnameAsRangeValidator : ValidationRule { - public class IPAddressOrHostnameAsRangeValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var input = (value as string)?.Trim(); - - if (string.IsNullOrEmpty(input)) - return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); + var input = (value as string)?.Trim(); - foreach (var item in input.Split(";")) - { - var localItem = item.Trim(); + if (string.IsNullOrEmpty(input)) + return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); - // Check if it is a valid IPv4 address like 192.168.0.1, a valid IPv6 address like ::1 or a valid hostname like server-01 or server-01.example.com - var isValid = Regex.IsMatch(localItem, RegexHelper.IPv4AddressRegex) || - Regex.IsMatch(localItem, RegexHelper.IPv6AddressRegex) || - Regex.IsMatch(localItem, RegexHelper.HostnameRegex); - - if (!isValid) - return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); - } + foreach (var item in input.Split(";")) + { + var localItem = item.Trim(); - return ValidationResult.ValidResult; + // Check if it is a valid IPv4 address like 192.168.0.1, a valid IPv6 address like ::1 or a valid hostname like server-01 or server-01.example.com + var isValid = Regex.IsMatch(localItem, RegexHelper.IPv4AddressRegex) || + Regex.IsMatch(localItem, RegexHelper.IPv6AddressRegex) || + Regex.IsMatch(localItem, RegexHelper.HostnameRegex); + + if (!isValid) + return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); } + + return ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/IPAddressOrHostnameValidator.cs b/Source/NETworkManager.Validators/IPAddressOrHostnameValidator.cs index 6bc6109649..984f2de21d 100644 --- a/Source/NETworkManager.Validators/IPAddressOrHostnameValidator.cs +++ b/Source/NETworkManager.Validators/IPAddressOrHostnameValidator.cs @@ -4,30 +4,29 @@ using NETworkManager.Localization.Resources; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IPAddressOrHostnameValidator : ValidationRule { - public class IPAddressOrHostnameValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var input = (value as string)?.Trim(); + var input = (value as string)?.Trim(); - if(string.IsNullOrEmpty(input)) - return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); + if(string.IsNullOrEmpty(input)) + return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); - // Check if it is a valid IPv4 address like 192.168.0.1 - if (Regex.IsMatch(input, RegexHelper.IPv4AddressRegex)) - return ValidationResult.ValidResult; + // Check if it is a valid IPv4 address like 192.168.0.1 + if (Regex.IsMatch(input, RegexHelper.IPv4AddressRegex)) + return ValidationResult.ValidResult; - // Check if it is a valid IPv6 address like ::1 - if (Regex.IsMatch(input, RegexHelper.IPv6AddressRegex)) - return ValidationResult.ValidResult; + // Check if it is a valid IPv6 address like ::1 + if (Regex.IsMatch(input, RegexHelper.IPv6AddressRegex)) + return ValidationResult.ValidResult; - // Check if it is a valid hostname like server-01 or server-01.example.com - if (Regex.IsMatch(input, RegexHelper.HostnameRegex)) - return ValidationResult.ValidResult; + // Check if it is a valid hostname like server-01 or server-01.example.com + if (Regex.IsMatch(input, RegexHelper.HostnameRegex)) + return ValidationResult.ValidResult; - return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); - } + return new ValidationResult(false, Strings.EnterValidHostnameOrIPAddress); } } diff --git a/Source/NETworkManager.Validators/IPv4AddressValidator.cs b/Source/NETworkManager.Validators/IPv4AddressValidator.cs index cfe024ff5d..83a7ad59dd 100644 --- a/Source/NETworkManager.Validators/IPv4AddressValidator.cs +++ b/Source/NETworkManager.Validators/IPv4AddressValidator.cs @@ -3,18 +3,17 @@ using System.Text.RegularExpressions; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IPv4AddressValidator : ValidationRule { - public class IPv4AddressValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var ipAddress = (value as string)?.Trim(); + var ipAddress = (value as string)?.Trim(); - if (string.IsNullOrEmpty(ipAddress)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv4Address); + if (string.IsNullOrEmpty(ipAddress)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv4Address); - return Regex.IsMatch(ipAddress, RegexHelper.IPv4AddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv4Address); - } + return Regex.IsMatch(ipAddress, RegexHelper.IPv4AddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv4Address); } } diff --git a/Source/NETworkManager.Validators/IPv4IPv6SubnetValidator.cs b/Source/NETworkManager.Validators/IPv4IPv6SubnetValidator.cs index a4083712ab..2f88a97b9a 100644 --- a/Source/NETworkManager.Validators/IPv4IPv6SubnetValidator.cs +++ b/Source/NETworkManager.Validators/IPv4IPv6SubnetValidator.cs @@ -2,30 +2,30 @@ using System.Text.RegularExpressions; using System.Windows.Controls; using NETworkManager.Utilities; -namespace NETworkManager.Validators + +namespace NETworkManager.Validators; + +public class IPv4IPv6SubnetValidator : ValidationRule { - public class IPv4IPv6SubnetValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var subnet = (value as string)?.Trim(); + var subnet = (value as string)?.Trim(); - if (string.IsNullOrEmpty(subnet)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); + if (string.IsNullOrEmpty(subnet)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); - // Check if it is a IPv4 address with a cidr like 192.168.0.0/24 - if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressCidrRegex)) - return ValidationResult.ValidResult; + // Check if it is a IPv4 address with a cidr like 192.168.0.0/24 + if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressCidrRegex)) + return ValidationResult.ValidResult; - // Check if it is a IPv4 address with a subnetmask like 255.255.255.0 - if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressSubnetmaskRegex)) - return ValidationResult.ValidResult; + // Check if it is a IPv4 address with a subnetmask like 255.255.255.0 + if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressSubnetmaskRegex)) + return ValidationResult.ValidResult; - // check if it is a IPv6 address with a cidr like ::1/64 - if (Regex.IsMatch(subnet, RegexHelper.IPv6AddressCidrRegex)) - return ValidationResult.ValidResult; + // check if it is a IPv6 address with a cidr like ::1/64 + if (Regex.IsMatch(subnet, RegexHelper.IPv6AddressCidrRegex)) + return ValidationResult.ValidResult; - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); - } + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); } } diff --git a/Source/NETworkManager.Validators/IPv4IPv6SubnetmaskOrCIDRValidator.cs b/Source/NETworkManager.Validators/IPv4IPv6SubnetmaskOrCIDRValidator.cs index f4100c6ad8..2223e9ff06 100644 --- a/Source/NETworkManager.Validators/IPv4IPv6SubnetmaskOrCIDRValidator.cs +++ b/Source/NETworkManager.Validators/IPv4IPv6SubnetmaskOrCIDRValidator.cs @@ -3,29 +3,28 @@ using System.Windows.Controls; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IPv4IPv6SubnetmaskOrCIDRValidator : ValidationRule { - public class IPv4IPv6SubnetmaskOrCIDRValidator : ValidationRule - { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var subnetmaskOrCidr = (value as string)?.Trim(); + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + var subnetmaskOrCidr = (value as string)?.Trim(); - if(string.IsNullOrEmpty(subnetmaskOrCidr)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); + if(string.IsNullOrEmpty(subnetmaskOrCidr)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); - // Check if it is a subnetmask like 255.255.255.0 - if (Regex.IsMatch(subnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) - return ValidationResult.ValidResult; + // Check if it is a subnetmask like 255.255.255.0 + if (Regex.IsMatch(subnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) + return ValidationResult.ValidResult; - // Check if it is a CIDR like /24 - if (int.TryParse(subnetmaskOrCidr.TrimStart('/'), out var cidr)) - { - if (cidr >= 0 && cidr < 129) - return ValidationResult.ValidResult; - } - - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); - } + // Check if it is a CIDR like /24 + if (int.TryParse(subnetmaskOrCidr.TrimStart('/'), out var cidr)) + { + if (cidr >= 0 && cidr < 129) + return ValidationResult.ValidResult; + } + + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); } } diff --git a/Source/NETworkManager.Validators/IPv4SubnetValidator.cs b/Source/NETworkManager.Validators/IPv4SubnetValidator.cs index 84782ebf28..1f51d679a4 100644 --- a/Source/NETworkManager.Validators/IPv4SubnetValidator.cs +++ b/Source/NETworkManager.Validators/IPv4SubnetValidator.cs @@ -3,24 +3,23 @@ using System.Windows.Controls; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IPv4SubnetValidator : ValidationRule { - public class IPv4SubnetValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var subnet = (value as string)?.Trim(); + var subnet = (value as string)?.Trim(); - if(string.IsNullOrEmpty(subnet)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); + if(string.IsNullOrEmpty(subnet)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); - if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressCidrRegex)) - return ValidationResult.ValidResult; + if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressCidrRegex)) + return ValidationResult.ValidResult; - if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressSubnetmaskRegex)) - return ValidationResult.ValidResult; + if (Regex.IsMatch(subnet, RegexHelper.IPv4AddressSubnetmaskRegex)) + return ValidationResult.ValidResult; - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); - } + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnet); } } diff --git a/Source/NETworkManager.Validators/IPv4SubnetmaskOrCIDRValidator.cs b/Source/NETworkManager.Validators/IPv4SubnetmaskOrCIDRValidator.cs index 76e69b588c..34568b9fd9 100644 --- a/Source/NETworkManager.Validators/IPv4SubnetmaskOrCIDRValidator.cs +++ b/Source/NETworkManager.Validators/IPv4SubnetmaskOrCIDRValidator.cs @@ -3,28 +3,27 @@ using System.Windows.Controls; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IPv4SubnetmaskOrCIDRValidator : ValidationRule { - public class IPv4SubnetmaskOrCIDRValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var subnetmaskOrCidr = (value as string)?.Trim(); - - if(string.IsNullOrEmpty(subnetmaskOrCidr)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); + var subnetmaskOrCidr = (value as string)?.Trim(); + if(string.IsNullOrEmpty(subnetmaskOrCidr)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); - if (Regex.IsMatch(subnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) - return ValidationResult.ValidResult; - if (int.TryParse(subnetmaskOrCidr.TrimStart('/'), out var cidr)) - { - if (cidr >= 0 && cidr < 33) - return ValidationResult.ValidResult; - } + if (Regex.IsMatch(subnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) + return ValidationResult.ValidResult; - return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); + if (int.TryParse(subnetmaskOrCidr.TrimStart('/'), out var cidr)) + { + if (cidr >= 0 && cidr < 33) + return ValidationResult.ValidResult; } + + return new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmaskOrCIDR); } } diff --git a/Source/NETworkManager.Validators/IPv6AddressValidator.cs b/Source/NETworkManager.Validators/IPv6AddressValidator.cs index a3afdc095c..f5ddc6b13e 100644 --- a/Source/NETworkManager.Validators/IPv6AddressValidator.cs +++ b/Source/NETworkManager.Validators/IPv6AddressValidator.cs @@ -3,18 +3,17 @@ using System.Text.RegularExpressions; using System.Windows.Controls; -namespace NETworkManager.Validators -{ - public class IPv6AddressValidator : ValidationRule +namespace NETworkManager.Validators; + +public class IPv6AddressValidator : ValidationRule +{ + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var ipAddress = (value as string)?.Trim(); + var ipAddress = (value as string)?.Trim(); - if (string.IsNullOrEmpty(ipAddress)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv6Address); + if (string.IsNullOrEmpty(ipAddress)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv6Address); - return Regex.IsMatch(ipAddress, RegexHelper.IPv6AddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv6Address); - } + return Regex.IsMatch(ipAddress, RegexHelper.IPv6AddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPv6Address); } } diff --git a/Source/NETworkManager.Validators/Int32Validator.cs b/Source/NETworkManager.Validators/Int32Validator.cs index 6d720a1994..d2f9c04513 100644 --- a/Source/NETworkManager.Validators/Int32Validator.cs +++ b/Source/NETworkManager.Validators/Int32Validator.cs @@ -1,13 +1,12 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class Int32Validator : ValidationRule { - public class Int32Validator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return int.TryParse(value as string, out var x) && x > 0 ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidNumber); - } + return int.TryParse(value as string, out var x) && x > 0 ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidNumber); } } diff --git a/Source/NETworkManager.Validators/IsNameUnique.cs b/Source/NETworkManager.Validators/IsNameUnique.cs index 15b6042d74..f62a930ee1 100644 --- a/Source/NETworkManager.Validators/IsNameUnique.cs +++ b/Source/NETworkManager.Validators/IsNameUnique.cs @@ -3,16 +3,15 @@ using System.Linq; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IsNameUnique : ValidationRule { - public class IsNameUnique : ValidationRule - { - public IsNameUniqueDependencyObjectWrapper Wrapper { get; set; } + public IsNameUniqueDependencyObjectWrapper Wrapper { get; set; } - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return Wrapper.UsedNames.Any(x => x.Equals(value as string, StringComparison.OrdinalIgnoreCase)) ? - new ValidationResult(false, Localization.Resources.Strings.ErrorMessage_NameIsAlreadyUsed) : ValidationResult.ValidResult; - } + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return Wrapper.UsedNames.Any(x => x.Equals(value as string, StringComparison.OrdinalIgnoreCase)) ? + new ValidationResult(false, Localization.Resources.Strings.ErrorMessage_NameIsAlreadyUsed) : ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/IsNameUniqueDependencyObjectWrapper.cs b/Source/NETworkManager.Validators/IsNameUniqueDependencyObjectWrapper.cs index e06f1a6061..675b8a15be 100644 --- a/Source/NETworkManager.Validators/IsNameUniqueDependencyObjectWrapper.cs +++ b/Source/NETworkManager.Validators/IsNameUniqueDependencyObjectWrapper.cs @@ -1,18 +1,17 @@ using System.Collections.Generic; using System.Windows; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class IsNameUniqueDependencyObjectWrapper : DependencyObject { - public class IsNameUniqueDependencyObjectWrapper : DependencyObject - { - public static readonly DependencyProperty UsedNamesProperty = DependencyProperty.Register("UsedNames", - typeof(List), - typeof(IsNameUniqueDependencyObjectWrapper)); + public static readonly DependencyProperty UsedNamesProperty = DependencyProperty.Register("UsedNames", + typeof(List), + typeof(IsNameUniqueDependencyObjectWrapper)); - public List UsedNames - { - get { return GetValue(UsedNamesProperty) as List; } - set { SetValue(UsedNamesProperty, value); } - } + public List UsedNames + { + get { return GetValue(UsedNamesProperty) as List; } + set { SetValue(UsedNamesProperty, value); } } } diff --git a/Source/NETworkManager.Validators/MACAddressValidator.cs b/Source/NETworkManager.Validators/MACAddressValidator.cs index 2691bc196d..f6e2889037 100644 --- a/Source/NETworkManager.Validators/MACAddressValidator.cs +++ b/Source/NETworkManager.Validators/MACAddressValidator.cs @@ -3,13 +3,12 @@ using System.Text.RegularExpressions; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class MACAddressValidator : ValidationRule { - public class MACAddressValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return value != null && Regex.IsMatch((string) value, RegexHelper.MACAddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidMACAddress); - } + return value != null && Regex.IsMatch((string) value, RegexHelper.MACAddressRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidMACAddress); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/MultipleHostsRangeValidator.cs b/Source/NETworkManager.Validators/MultipleHostsRangeValidator.cs index df01589f35..ee7e09b86d 100644 --- a/Source/NETworkManager.Validators/MultipleHostsRangeValidator.cs +++ b/Source/NETworkManager.Validators/MultipleHostsRangeValidator.cs @@ -5,89 +5,88 @@ using System.Net; using NETworkManager.Models.Network; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class MultipleHostsRangeValidator : ValidationRule { - public class MultipleHostsRangeValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var isValid = true; + var isValid = true; - if (value == null) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidIPScanRange); + if (value == null) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidIPScanRange); - foreach (var ipHostOrRange in ((string)value).Replace(" ", "").Split(';')) - { - // 192.168.0.1 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRegex)) - continue; + foreach (var ipHostOrRange in ((string)value).Replace(" ", "").Split(';')) + { + // 192.168.0.1 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRegex)) + continue; - // 192.168.0.0/24 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressCidrRegex)) - continue; + // 192.168.0.0/24 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressCidrRegex)) + continue; - // 192.168.0.0/255.255.255.0 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSubnetmaskRegex)) - continue; + // 192.168.0.0/255.255.255.0 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSubnetmaskRegex)) + continue; - // 192.168.0.0 - 192.168.0.100 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRangeRegex)) - { - var range = ipHostOrRange.Split('-'); + // 192.168.0.0 - 192.168.0.100 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRangeRegex)) + { + var range = ipHostOrRange.Split('-'); - if (IPv4Address.ToInt32(IPAddress.Parse(range[0])) > IPv4Address.ToInt32(IPAddress.Parse(range[1]))) - isValid = false; + if (IPv4Address.ToInt32(IPAddress.Parse(range[0])) > IPv4Address.ToInt32(IPAddress.Parse(range[1]))) + isValid = false; - continue; - } + continue; + } - // 192.168.[50-100].1 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSpecialRangeRegex)) + // 192.168.[50-100].1 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSpecialRangeRegex)) + { + var octets = ipHostOrRange.Split('.'); + + foreach (var octet in octets) { - var octets = ipHostOrRange.Split('.'); + // Match [50-100] + if (!Regex.IsMatch(octet, RegexHelper.SpecialRangeRegex)) + continue; - foreach (var octet in octets) + foreach (var numberOrRange in octet.Substring(1, octet.Length - 2).Split(',')) { - // Match [50-100] - if (!Regex.IsMatch(octet, RegexHelper.SpecialRangeRegex)) + if (!numberOrRange.Contains("-")) continue; - foreach (var numberOrRange in octet.Substring(1, octet.Length - 2).Split(',')) - { - if (!numberOrRange.Contains("-")) - continue; + // 50-100 --> {50, 100} + var rangeNumber = numberOrRange.Split('-'); - // 50-100 --> {50, 100} - var rangeNumber = numberOrRange.Split('-'); - - if (int.Parse(rangeNumber[0]) > int.Parse(rangeNumber[1])) - isValid = false; - } + if (int.Parse(rangeNumber[0]) > int.Parse(rangeNumber[1])) + isValid = false; } - - continue; } - // 2001:db8:85a3::8a2e:370:7334 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv6AddressRegex)) - continue; + continue; + } - // server-01.example.com - if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameRegex)) - continue; + // 2001:db8:85a3::8a2e:370:7334 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv6AddressRegex)) + continue; - // server-01.example.com/24 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameCidrRegex)) - continue; + // server-01.example.com + if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameRegex)) + continue; - // server-01.example.com/255.255.255.0 - if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameSubnetmaskRegex)) - continue; + // server-01.example.com/24 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameCidrRegex)) + continue; - isValid = false; - } + // server-01.example.com/255.255.255.0 + if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameSubnetmaskRegex)) + continue; - return isValid ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPScanRange); + isValid = false; } + + return isValid ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidIPScanRange); } } diff --git a/Source/NETworkManager.Validators/MultipleIPAddressesValidator.cs b/Source/NETworkManager.Validators/MultipleIPAddressesValidator.cs index a0a93ff50b..be333a77f8 100644 --- a/Source/NETworkManager.Validators/MultipleIPAddressesValidator.cs +++ b/Source/NETworkManager.Validators/MultipleIPAddressesValidator.cs @@ -3,24 +3,23 @@ using System.Text.RegularExpressions; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class MultipleIPAddressesValidator : ValidationRule { - public class MultipleIPAddressesValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - if (value == null) - return ValidationResult.ValidResult; - - for (var index = 0; index < ((string)value).Split(';').Length; index++) - { - var ipAddress = ((string)value).Split(';')[index]; + if (value == null) + return ValidationResult.ValidResult; - if (!Regex.IsMatch(ipAddress.Trim(), RegexHelper.IPv4AddressRegex) && !Regex.IsMatch(ipAddress.Trim(), RegexHelper.IPv6AddressRegex)) - return new ValidationResult(false, Localization.Resources.Strings.EnterOneOrMoreValidIPAddresses); - } + for (var index = 0; index < ((string)value).Split(';').Length; index++) + { + var ipAddress = ((string)value).Split(';')[index]; - return ValidationResult.ValidResult; + if (!Regex.IsMatch(ipAddress.Trim(), RegexHelper.IPv4AddressRegex) && !Regex.IsMatch(ipAddress.Trim(), RegexHelper.IPv6AddressRegex)) + return new ValidationResult(false, Localization.Resources.Strings.EnterOneOrMoreValidIPAddresses); } + + return ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/NoSpacesValidator.cs b/Source/NETworkManager.Validators/NoSpacesValidator.cs index 2c75c4911c..2f29a44c5b 100644 --- a/Source/NETworkManager.Validators/NoSpacesValidator.cs +++ b/Source/NETworkManager.Validators/NoSpacesValidator.cs @@ -2,16 +2,15 @@ using System.Linq; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class NoSpacesValidator : ValidationRule { - public class NoSpacesValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - if (string.IsNullOrEmpty(value as string) || !((string) value).Any(char.IsWhiteSpace)) - return ValidationResult.ValidResult; + if (string.IsNullOrEmpty(value as string) || !((string) value).Any(char.IsWhiteSpace)) + return ValidationResult.ValidResult; - return new ValidationResult(false, Localization.Resources.Strings.SpacesAreNotAllowed); - } + return new ValidationResult(false, Localization.Resources.Strings.SpacesAreNotAllowed); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/NotEndWithSemicolonValidator.cs b/Source/NETworkManager.Validators/NotEndWithSemicolonValidator.cs index c573573361..4d40022def 100644 --- a/Source/NETworkManager.Validators/NotEndWithSemicolonValidator.cs +++ b/Source/NETworkManager.Validators/NotEndWithSemicolonValidator.cs @@ -4,13 +4,12 @@ using NETworkManager.Localization.Resources; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class NotEndWithSemicolonValidator : ValidationRule { - public class NotEndWithSemicolonValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return Regex.IsMatch(((string) value).Trim(), RegexHelper.StringNotEndWithSemicolonRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.InputCannotEndWithSemicolon); - } + return Regex.IsMatch(((string) value).Trim(), RegexHelper.StringNotEndWithSemicolonRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.InputCannotEndWithSemicolon); } } diff --git a/Source/NETworkManager.Validators/NumberValidator.cs b/Source/NETworkManager.Validators/NumberValidator.cs index 6220b680d0..7f6cff1dee 100644 --- a/Source/NETworkManager.Validators/NumberValidator.cs +++ b/Source/NETworkManager.Validators/NumberValidator.cs @@ -4,13 +4,12 @@ using System.Text.RegularExpressions; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class NumberValidator : ValidationRule { - public class NumberValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return Regex.IsMatch(((string)value).Trim(), RegexHelper.NumberRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.OnlyNumbersCanBeEntered); - } + return Regex.IsMatch(((string)value).Trim(), RegexHelper.NumberRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.OnlyNumbersCanBeEntered); } } diff --git a/Source/NETworkManager.Validators/OIDValidator.cs b/Source/NETworkManager.Validators/OIDValidator.cs index 8dd5f0ad74..47b136bda8 100644 --- a/Source/NETworkManager.Validators/OIDValidator.cs +++ b/Source/NETworkManager.Validators/OIDValidator.cs @@ -2,23 +2,22 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class OIDValidator : ValidationRule { - public class OIDValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) + // Use SharpSNMP new ObjectIdentifiert to validate oid + try { - // Use SharpSNMP new ObjectIdentifiert to validate oid - try - { - var oid = new ObjectIdentifier(value as string); - } - catch (System.ArgumentException) - { - return new ValidationResult(false, Localization.Resources.Strings.EnterValidOID); - } - - return ValidationResult.ValidResult; + var oid = new ObjectIdentifier(value as string); } + catch (System.ArgumentException) + { + return new ValidationResult(false, Localization.Resources.Strings.EnterValidOID); + } + + return ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/PortRangeValidator.cs b/Source/NETworkManager.Validators/PortRangeValidator.cs index 25f0ba5252..d2297cb77d 100644 --- a/Source/NETworkManager.Validators/PortRangeValidator.cs +++ b/Source/NETworkManager.Validators/PortRangeValidator.cs @@ -1,48 +1,47 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class PortRangeValidator : ValidationRule { - public class PortRangeValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - var isValid = true; + var isValid = true; - if (value == null) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); + if (value == null) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); - foreach (var portOrRange in ((string)value).Replace(" ", "").Split(';')) + foreach (var portOrRange in ((string)value).Replace(" ", "").Split(';')) + { + if (portOrRange.Contains("-")) { - if (portOrRange.Contains("-")) - { - var portRange = portOrRange.Split('-'); + var portRange = portOrRange.Split('-'); - if (int.TryParse(portRange[0], out var startPort) && int.TryParse(portRange[1], out var endPort)) - { - if (!((startPort > 0) && (startPort < 65536) && (endPort > 0) && (endPort < 65536) && (startPort < endPort))) - isValid = false; - } - else - { + if (int.TryParse(portRange[0], out var startPort) && int.TryParse(portRange[1], out var endPort)) + { + if (!((startPort > 0) && (startPort < 65536) && (endPort > 0) && (endPort < 65536) && (startPort < endPort))) isValid = false; - } } else { - if (int.TryParse(portOrRange, out var portNumber)) - { - if (!((portNumber > 0) && (portNumber < 65536))) - isValid = false; - } - else - { + isValid = false; + } + } + else + { + if (int.TryParse(portOrRange, out var portNumber)) + { + if (!((portNumber > 0) && (portNumber < 65536))) isValid = false; - } + } + else + { + isValid = false; } } - - return isValid ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); } + + return isValid ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidPortOrPortRange); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/PortValidator.cs b/Source/NETworkManager.Validators/PortValidator.cs index 75c4b9c194..de53ae6fd6 100644 --- a/Source/NETworkManager.Validators/PortValidator.cs +++ b/Source/NETworkManager.Validators/PortValidator.cs @@ -1,19 +1,18 @@ using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class PortValidator : ValidationRule { - public class PortValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - if (!int.TryParse(value as string, out var portNumber)) - return new ValidationResult(false, Localization.Resources.Strings.EnterValidPort); + if (!int.TryParse(value as string, out var portNumber)) + return new ValidationResult(false, Localization.Resources.Strings.EnterValidPort); - if (portNumber > 0 && (portNumber < 65536)) - return ValidationResult.ValidResult; + if (portNumber > 0 && (portNumber < 65536)) + return ValidationResult.ValidResult; - return new ValidationResult(false, Localization.Resources.Strings.EnterValidPort); - } + return new ValidationResult(false, Localization.Resources.Strings.EnterValidPort); } } \ No newline at end of file diff --git a/Source/NETworkManager.Validators/PowerShellPathValidator.cs b/Source/NETworkManager.Validators/PowerShellPathValidator.cs index f79fe57f89..fc6fe9af35 100644 --- a/Source/NETworkManager.Validators/PowerShellPathValidator.cs +++ b/Source/NETworkManager.Validators/PowerShellPathValidator.cs @@ -3,15 +3,14 @@ using System.Linq; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class PowerShellPathValidator : ValidationRule { - public class PowerShellPathValidator : ValidationRule - { - private static string[] fileNames = new[] { "powershell.exe", "pwsh.exe" }; + private static string[] fileNames = new[] { "powershell.exe", "pwsh.exe" }; - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return fileNames.Contains(Path.GetFileName((string)value).ToLower()) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.NoValidPowerShellPath); - } + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return fileNames.Contains(Path.GetFileName((string)value).ToLower()) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.NoValidPowerShellPath); } } diff --git a/Source/NETworkManager.Validators/ProfileFileUniqueValidator.cs b/Source/NETworkManager.Validators/ProfileFileUniqueValidator.cs index 0611bfdd4d..d698662861 100644 --- a/Source/NETworkManager.Validators/ProfileFileUniqueValidator.cs +++ b/Source/NETworkManager.Validators/ProfileFileUniqueValidator.cs @@ -3,13 +3,12 @@ using System.Windows.Controls; using System.Linq; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class ProfileFileUniqueValidator : ValidationRule { - public class ProfileFileUniqueValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return ProfileManager.ProfileFiles.Any(x => x.Name == value as string) ? new ValidationResult(false, Localization.Resources.Strings.ProfileNameAlreadyExists) : ValidationResult.ValidResult; - } + return ProfileManager.ProfileFiles.Any(x => x.Name == value as string) ? new ValidationResult(false, Localization.Resources.Strings.ProfileNameAlreadyExists) : ValidationResult.ValidResult; } } diff --git a/Source/NETworkManager.Validators/PuTTYPathValidator.cs b/Source/NETworkManager.Validators/PuTTYPathValidator.cs index f747810b5c..ca810c33a1 100644 --- a/Source/NETworkManager.Validators/PuTTYPathValidator.cs +++ b/Source/NETworkManager.Validators/PuTTYPathValidator.cs @@ -3,15 +3,14 @@ using System.Linq; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class PuTTYPathValidator : ValidationRule { - public class PuTTYPathValidator : ValidationRule - { - private static string[] fileNames = new[] { "putty.exe" }; + private static string[] fileNames = new[] { "putty.exe" }; - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return fileNames.Contains(Path.GetFileName((string)value).ToLower()) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.NoValidPuTTYPath); - } + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + return fileNames.Contains(Path.GetFileName((string)value).ToLower()) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.NoValidPuTTYPath); } } diff --git a/Source/NETworkManager.Validators/RemoteDesktopHostnameAndPortValidator.cs b/Source/NETworkManager.Validators/RemoteDesktopHostnameAndPortValidator.cs index 6acfde7a70..bcac86f26b 100644 --- a/Source/NETworkManager.Validators/RemoteDesktopHostnameAndPortValidator.cs +++ b/Source/NETworkManager.Validators/RemoteDesktopHostnameAndPortValidator.cs @@ -4,27 +4,26 @@ using NETworkManager.Localization.Resources; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class RemoteDesktopHostnameAndPortValidator : ValidationRule { - public class RemoteDesktopHostnameAndPortValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - string hostnameAndPort = (string)value; + string hostnameAndPort = (string)value; - if(hostnameAndPort.Contains(":")) - { - string[] hostnameAndPortValues = hostnameAndPort.Split(':'); + if(hostnameAndPort.Contains(":")) + { + string[] hostnameAndPortValues = hostnameAndPort.Split(':'); - if (Regex.IsMatch(hostnameAndPortValues[0], RegexHelper.HostnameRegex) && !string.IsNullOrEmpty(hostnameAndPortValues[1]) && Regex.IsMatch(hostnameAndPortValues[1], RegexHelper.PortRegex)) - return ValidationResult.ValidResult; - - return new ValidationResult(false, Strings.EnterValidHostnameAndPort); - } - else - { - return Regex.IsMatch((string)value, RegexHelper.HostnameRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidHostname); - } + if (Regex.IsMatch(hostnameAndPortValues[0], RegexHelper.HostnameRegex) && !string.IsNullOrEmpty(hostnameAndPortValues[1]) && Regex.IsMatch(hostnameAndPortValues[1], RegexHelper.PortRegex)) + return ValidationResult.ValidResult; + + return new ValidationResult(false, Strings.EnterValidHostnameAndPort); + } + else + { + return Regex.IsMatch((string)value, RegexHelper.HostnameRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Strings.EnterValidHostname); } } } diff --git a/Source/NETworkManager.Validators/ServerDependencyObjectWrapper.cs b/Source/NETworkManager.Validators/ServerDependencyObjectWrapper.cs index 2cc7a5f92b..a01e339425 100644 --- a/Source/NETworkManager.Validators/ServerDependencyObjectWrapper.cs +++ b/Source/NETworkManager.Validators/ServerDependencyObjectWrapper.cs @@ -1,17 +1,16 @@ using System.Windows; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class ServerDependencyObjectWrapper : DependencyObject { - public class ServerDependencyObjectWrapper : DependencyObject - { - public static readonly DependencyProperty AllowOnlyIPAddressProperty = DependencyProperty.Register("AllowOnlyIPAddress", - typeof(bool), - typeof(ServerDependencyObjectWrapper)); + public static readonly DependencyProperty AllowOnlyIPAddressProperty = DependencyProperty.Register("AllowOnlyIPAddress", + typeof(bool), + typeof(ServerDependencyObjectWrapper)); - public bool AllowOnlyIPAddress - { - get { return (bool)GetValue(AllowOnlyIPAddressProperty); } - set { SetValue(AllowOnlyIPAddressProperty, value); } - } + public bool AllowOnlyIPAddress + { + get { return (bool)GetValue(AllowOnlyIPAddressProperty); } + set { SetValue(AllowOnlyIPAddressProperty, value); } } } diff --git a/Source/NETworkManager.Validators/ServerValidator.cs b/Source/NETworkManager.Validators/ServerValidator.cs index 9fcb9c22ea..facd9ff1be 100644 --- a/Source/NETworkManager.Validators/ServerValidator.cs +++ b/Source/NETworkManager.Validators/ServerValidator.cs @@ -4,35 +4,34 @@ using NETworkManager.Localization.Resources; using NETworkManager.Utilities; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class ServerValidator : ValidationRule { - public class ServerValidator : ValidationRule + public ServerDependencyObjectWrapper Wrapper { get; set; } + + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public ServerDependencyObjectWrapper Wrapper { get; set; } - - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - bool allowOnlyIPAddress = Wrapper.AllowOnlyIPAddress; - var genericErrorResult = allowOnlyIPAddress ? Strings.EnterValidIPAddress : Strings.EnterValidHostnameOrIPAddress; + bool allowOnlyIPAddress = Wrapper.AllowOnlyIPAddress; + var genericErrorResult = allowOnlyIPAddress ? Strings.EnterValidIPAddress : Strings.EnterValidHostnameOrIPAddress; - var input = (value as string)?.Trim(); + var input = (value as string)?.Trim(); - if(string.IsNullOrEmpty(input)) - return new ValidationResult(false, genericErrorResult); + if(string.IsNullOrEmpty(input)) + return new ValidationResult(false, genericErrorResult); - // Check if it is a valid IPv4 address like 192.168.0.1 - if (Regex.IsMatch(input, RegexHelper.IPv4AddressRegex)) - return ValidationResult.ValidResult; + // Check if it is a valid IPv4 address like 192.168.0.1 + if (Regex.IsMatch(input, RegexHelper.IPv4AddressRegex)) + return ValidationResult.ValidResult; - // Check if it is a valid IPv6 address like ::1 - if (Regex.IsMatch(input, RegexHelper.IPv6AddressRegex)) - return ValidationResult.ValidResult; + // Check if it is a valid IPv6 address like ::1 + if (Regex.IsMatch(input, RegexHelper.IPv6AddressRegex)) + return ValidationResult.ValidResult; - // Check if it is a valid hostname like server-01 or server-01.example.com - if (Regex.IsMatch(input, RegexHelper.HostnameRegex) && !allowOnlyIPAddress) - return ValidationResult.ValidResult; + // Check if it is a valid hostname like server-01 or server-01.example.com + if (Regex.IsMatch(input, RegexHelper.HostnameRegex) && !allowOnlyIPAddress) + return ValidationResult.ValidResult; - return new ValidationResult(false, genericErrorResult); - } + return new ValidationResult(false, genericErrorResult); } } diff --git a/Source/NETworkManager.Validators/SubnetmaskValidator.cs b/Source/NETworkManager.Validators/SubnetmaskValidator.cs index 06cce5674d..bf6cf3f086 100644 --- a/Source/NETworkManager.Validators/SubnetmaskValidator.cs +++ b/Source/NETworkManager.Validators/SubnetmaskValidator.cs @@ -3,13 +3,12 @@ using System.Text.RegularExpressions; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class SubnetmaskValidator : ValidationRule { - public class SubnetmaskValidator : ValidationRule + public override ValidationResult Validate(object value, CultureInfo cultureInfo) { - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - return value != null && Regex.IsMatch((string) value, RegexHelper.SubnetmaskRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmask); - } + return value != null && Regex.IsMatch((string) value, RegexHelper.SubnetmaskRegex) ? ValidationResult.ValidResult : new ValidationResult(false, Localization.Resources.Strings.EnterValidSubnetmask); } } diff --git a/Source/NETworkManager.Validators/TigerVNCPathValidator.cs b/Source/NETworkManager.Validators/TigerVNCPathValidator.cs index 1d8647f643..9cda6ab8ca 100644 --- a/Source/NETworkManager.Validators/TigerVNCPathValidator.cs +++ b/Source/NETworkManager.Validators/TigerVNCPathValidator.cs @@ -3,20 +3,19 @@ using System.Linq; using System.Windows.Controls; -namespace NETworkManager.Validators +namespace NETworkManager.Validators; + +public class TigerVNCPathValidator : ValidationRule { - public class TigerVNCPathValidator : ValidationRule - { - private static string[] fileNames = new[] { "vncviewer-", "vncviewer64-" }; + private static string[] fileNames = new[] { "vncviewer-", "vncviewer64-" }; - public override ValidationResult Validate(object value, CultureInfo cultureInfo) - { - string fileName = Path.GetFileName((string)value).ToLower(); + public override ValidationResult Validate(object value, CultureInfo cultureInfo) + { + string fileName = Path.GetFileName((string)value).ToLower(); - if (fileNames.Any(x => fileName.StartsWith(x) && fileName.EndsWith(".exe"))) - return ValidationResult.ValidResult; + if (fileNames.Any(x => fileName.StartsWith(x) && fileName.EndsWith(".exe"))) + return ValidationResult.ValidResult; - return new ValidationResult(false, Localization.Resources.Strings.NoValidTigerVNCPath); - } + return new ValidationResult(false, Localization.Resources.Strings.NoValidTigerVNCPath); } } From 3c38309d4c10a9600344796a85b73c6e2f740941 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:17:28 +0100 Subject: [PATCH 02/11] Chore: Make readonly --- Source/NETworkManager.Validators/PowerShellPathValidator.cs | 2 +- Source/NETworkManager.Validators/PuTTYPathValidator.cs | 2 +- Source/NETworkManager.Validators/TigerVNCPathValidator.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/NETworkManager.Validators/PowerShellPathValidator.cs b/Source/NETworkManager.Validators/PowerShellPathValidator.cs index fc6fe9af35..e8f65fa583 100644 --- a/Source/NETworkManager.Validators/PowerShellPathValidator.cs +++ b/Source/NETworkManager.Validators/PowerShellPathValidator.cs @@ -7,7 +7,7 @@ namespace NETworkManager.Validators; public class PowerShellPathValidator : ValidationRule { - private static string[] fileNames = new[] { "powershell.exe", "pwsh.exe" }; + private static readonly string[] fileNames = new[] { "powershell.exe", "pwsh.exe" }; public override ValidationResult Validate(object value, CultureInfo cultureInfo) { diff --git a/Source/NETworkManager.Validators/PuTTYPathValidator.cs b/Source/NETworkManager.Validators/PuTTYPathValidator.cs index ca810c33a1..87fb3eb1ad 100644 --- a/Source/NETworkManager.Validators/PuTTYPathValidator.cs +++ b/Source/NETworkManager.Validators/PuTTYPathValidator.cs @@ -7,7 +7,7 @@ namespace NETworkManager.Validators; public class PuTTYPathValidator : ValidationRule { - private static string[] fileNames = new[] { "putty.exe" }; + private static readonly string[] fileNames = new[] { "putty.exe" }; public override ValidationResult Validate(object value, CultureInfo cultureInfo) { diff --git a/Source/NETworkManager.Validators/TigerVNCPathValidator.cs b/Source/NETworkManager.Validators/TigerVNCPathValidator.cs index 9cda6ab8ca..753901139e 100644 --- a/Source/NETworkManager.Validators/TigerVNCPathValidator.cs +++ b/Source/NETworkManager.Validators/TigerVNCPathValidator.cs @@ -7,7 +7,7 @@ namespace NETworkManager.Validators; public class TigerVNCPathValidator : ValidationRule { - private static string[] fileNames = new[] { "vncviewer-", "vncviewer64-" }; + private static readonly string[] fileNames = new[] { "vncviewer-", "vncviewer64-" }; public override ValidationResult Validate(object value, CultureInfo cultureInfo) { From eb3160e3e9384bba8091ddfba3c8621c384fe410 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:20:56 +0100 Subject: [PATCH 03/11] Chore: Use .NET 7 syntax --- Source/NETworkManager.Update/Updater.cs | 139 ++++++++-------- .../NETworkManager.Utilities/ArrayHelper.cs | 33 ++-- .../AutoRefreshTime.cs | 73 +++++---- .../AutoRefreshTimeInfo.cs | 59 ++++--- .../ClipboardHelper.cs | 21 ++- .../NETworkManager.Utilities/CryptoHelper.cs | 111 +++++++------ .../NETworkManager.Utilities/CustomCommand.cs | 23 ++- .../CustomCommandInfo.cs | 115 +++++++------- .../ExternalProcessStarter.cs | 63 ++++---- .../FileSizeConverter.cs | 131 ++++++++------- Source/NETworkManager.Utilities/HotKeys.cs | 149 +++++++++--------- Source/NETworkManager.Utilities/ListHelper.cs | 43 +++-- .../LvlChartsDefaultInfo.cs | 20 +-- .../MACAddressHelper.cs | 87 +++++----- .../NETworkManager.Utilities/NativeMethods.cs | 145 +++++++++-------- .../PortRangeHelper.cs | 45 +++--- .../NETworkManager.Utilities/RegexHelper.cs | 121 +++++++------- .../NETworkManager.Utilities/RelayCommand.cs | 77 +++++---- .../SecureStringHelper.cs | 45 +++--- .../SingleInstance.cs | 21 ++- .../NETworkManager.Utilities/SingletonBase.cs | 35 ++-- .../NETworkManager.Utilities/StringHelper.cs | 21 ++- Source/NETworkManager.Utilities/TimeUnit.cs | 41 +++-- .../TimestampHelper.cs | 11 +- .../VisualTreeHelper.cs | 31 ++-- 25 files changed, 818 insertions(+), 842 deletions(-) diff --git a/Source/NETworkManager.Update/Updater.cs b/Source/NETworkManager.Update/Updater.cs index 5478fe93f2..564c78e619 100644 --- a/Source/NETworkManager.Update/Updater.cs +++ b/Source/NETworkManager.Update/Updater.cs @@ -2,89 +2,88 @@ using System.Threading.Tasks; using Octokit; -namespace NETworkManager.Update +namespace NETworkManager.Update; + +/// +/// Updater to check if a new program version is available. +/// +public class Updater { + #region Events /// - /// Updater to check if a new program version is available. + /// Is triggered when update check is complete and an update is available. /// - public class Updater - { - #region Events - /// - /// Is triggered when update check is complete and an update is available. - /// - public event EventHandler UpdateAvailable; + public event EventHandler UpdateAvailable; - /// - /// Triggers the event. - /// - /// Passes to the event. - protected virtual void OnUpdateAvailable(UpdateAvailableArgs e) - { - UpdateAvailable?.Invoke(this, e); - } + /// + /// Triggers the event. + /// + /// Passes to the event. + protected virtual void OnUpdateAvailable(UpdateAvailableArgs e) + { + UpdateAvailable?.Invoke(this, e); + } - /// - /// Is triggered when update check is complete and no update is available. - /// - public event EventHandler NoUpdateAvailable; + /// + /// Is triggered when update check is complete and no update is available. + /// + public event EventHandler NoUpdateAvailable; - /// - /// Triggers the event. - /// - protected virtual void OnNoUpdateAvailable() - { - NoUpdateAvailable?.Invoke(this, EventArgs.Empty); - } + /// + /// Triggers the event. + /// + protected virtual void OnNoUpdateAvailable() + { + NoUpdateAvailable?.Invoke(this, EventArgs.Empty); + } - /// - /// Is triggered when an error occurs during the update check. - /// - public event EventHandler Error; + /// + /// Is triggered when an error occurs during the update check. + /// + public event EventHandler Error; - /// - /// Triggers the event. - /// - protected virtual void OnError() - { - Error?.Invoke(this, EventArgs.Empty); - } - #endregion + /// + /// Triggers the event. + /// + protected virtual void OnError() + { + Error?.Invoke(this, EventArgs.Empty); + } + #endregion - #region Methods - /// - /// Checks on GitHub whether a new version of the program is available - /// - /// GitHub username like "BornToBeRoot". - /// GitHub repository like "NETworkManager". - /// Version like 1.2.0.0. - public void CheckOnGitHub(string userName, string projectName, Version currentVersion, bool includePreRelease) + #region Methods + /// + /// Checks on GitHub whether a new version of the program is available + /// + /// GitHub username like "BornToBeRoot". + /// GitHub repository like "NETworkManager". + /// Version like 1.2.0.0. + public void CheckOnGitHub(string userName, string projectName, Version currentVersion, bool includePreRelease) + { + Task.Run(() => { - Task.Run(() => + try { - try - { - var client = new GitHubClient(new ProductHeaderValue(userName + "_" + projectName)); + var client = new GitHubClient(new ProductHeaderValue(userName + "_" + projectName)); - Release release = null; + Release release = null; - if (includePreRelease) - release = client.Repository.Release.GetAll(userName, projectName).Result[0]; - else - release = client.Repository.Release.GetLatest(userName, projectName).Result; + if (includePreRelease) + release = client.Repository.Release.GetAll(userName, projectName).Result[0]; + else + release = client.Repository.Release.GetLatest(userName, projectName).Result; - // Compare versions (tag=2021.2.15.0, version=2021.2.15.0) - if (new Version(release.TagName) > currentVersion) - OnUpdateAvailable(new UpdateAvailableArgs(release)); - else - OnNoUpdateAvailable(); - } - catch - { - OnError(); - } - }); - } - #endregion + // Compare versions (tag=2021.2.15.0, version=2021.2.15.0) + if (new Version(release.TagName) > currentVersion) + OnUpdateAvailable(new UpdateAvailableArgs(release)); + else + OnNoUpdateAvailable(); + } + catch + { + OnError(); + } + }); } + #endregion } diff --git a/Source/NETworkManager.Utilities/ArrayHelper.cs b/Source/NETworkManager.Utilities/ArrayHelper.cs index 418cb3ced3..e07cacf6ec 100644 --- a/Source/NETworkManager.Utilities/ArrayHelper.cs +++ b/Source/NETworkManager.Utilities/ArrayHelper.cs @@ -1,25 +1,24 @@ using System; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Collection of useful methods to interact with an array. +/// +public static class ArrayHelper { /// - /// Collection of useful methods to interact with an array. + /// Create a sub array from an array. /// - public static class ArrayHelper + /// Object array. + /// Any array. + /// Start index. + /// Length of the new array. + /// Sub array of the array. + public static T[] SubArray(this T[] data, int index, int length) { - /// - /// Create a sub array from an array. - /// - /// Object array. - /// Any array. - /// Start index. - /// Length of the new array. - /// Sub array of the array. - public static T[] SubArray(this T[] data, int index, int length) - { - var result = new T[length]; - Array.Copy(data, index, result, 0, length); - return result; - } + var result = new T[length]; + Array.Copy(data, index, result, 0, length); + return result; } } diff --git a/Source/NETworkManager.Utilities/AutoRefreshTime.cs b/Source/NETworkManager.Utilities/AutoRefreshTime.cs index f42018f3dc..5c69125bb1 100644 --- a/Source/NETworkManager.Utilities/AutoRefreshTime.cs +++ b/Source/NETworkManager.Utilities/AutoRefreshTime.cs @@ -1,47 +1,46 @@ using System; using System.Collections.Generic; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Class provides static methods to manage auto refresh time. +/// +public static class AutoRefreshTime { /// - /// Class provides static methods to manage auto refresh time. + /// Method returns a list with default s. /// - public static class AutoRefreshTime + public static IEnumerable GetDefaults => new List { - /// - /// Method returns a list with default s. - /// - public static IEnumerable GetDefaults => new List - { - new AutoRefreshTimeInfo(5, TimeUnit.Second), - new AutoRefreshTimeInfo(15, TimeUnit.Second), - new AutoRefreshTimeInfo(30, TimeUnit.Second), - new AutoRefreshTimeInfo(1, TimeUnit.Minute), - new AutoRefreshTimeInfo(5, TimeUnit.Minute), - }; + new AutoRefreshTimeInfo(5, TimeUnit.Second), + new AutoRefreshTimeInfo(15, TimeUnit.Second), + new AutoRefreshTimeInfo(30, TimeUnit.Second), + new AutoRefreshTimeInfo(1, TimeUnit.Minute), + new AutoRefreshTimeInfo(5, TimeUnit.Minute), + }; - /// - /// Method to calculate a based on . - /// - /// to calculate - /// Returns the calculated . - public static TimeSpan CalculateTimeSpan(AutoRefreshTimeInfo info) + /// + /// Method to calculate a based on . + /// + /// to calculate + /// Returns the calculated . + public static TimeSpan CalculateTimeSpan(AutoRefreshTimeInfo info) + { + switch (info.TimeUnit) { - switch (info.TimeUnit) - { - // Calculate the seconds - case TimeUnit.Second: - return new TimeSpan(0, 0, info.Value); - // Calculate the minutes - case TimeUnit.Minute: - return new TimeSpan(0, info.Value * 60, 0); - // Calculate the hours - case TimeUnit.Hour: - return new TimeSpan(info.Value * 60, 0, 0); - case TimeUnit.None: - default: - throw new Exception("Wrong time unit."); - } - } - } + // Calculate the seconds + case TimeUnit.Second: + return new TimeSpan(0, 0, info.Value); + // Calculate the minutes + case TimeUnit.Minute: + return new TimeSpan(0, info.Value * 60, 0); + // Calculate the hours + case TimeUnit.Hour: + return new TimeSpan(info.Value * 60, 0, 0); + case TimeUnit.None: + default: + throw new Exception("Wrong time unit."); + } + } } \ No newline at end of file diff --git a/Source/NETworkManager.Utilities/AutoRefreshTimeInfo.cs b/Source/NETworkManager.Utilities/AutoRefreshTimeInfo.cs index 0093f4f34a..40c044f153 100644 --- a/Source/NETworkManager.Utilities/AutoRefreshTimeInfo.cs +++ b/Source/NETworkManager.Utilities/AutoRefreshTimeInfo.cs @@ -1,38 +1,37 @@ -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Class stores auto refresh time informations. +/// +public class AutoRefreshTimeInfo { /// - /// Class stores auto refresh time informations. + /// Value is combined with . + /// Example: 5 Mintues, 2 Hours. /// - public class AutoRefreshTimeInfo - { - /// - /// Value is combined with . - /// Example: 5 Mintues, 2 Hours. - /// - public int Value { get; set; } + public int Value { get; set; } - /// - /// is combined with . - /// - public TimeUnit TimeUnit { get; set; } + /// + /// is combined with . + /// + public TimeUnit TimeUnit { get; set; } - /// - /// Initializes a new instance of the class. - /// - public AutoRefreshTimeInfo() - { + /// + /// Initializes a new instance of the class. + /// + public AutoRefreshTimeInfo() + { - } + } - /// - /// Initializes a new instance of the class with parameters. - /// - /// . - /// . - public AutoRefreshTimeInfo(int value, TimeUnit timenUnit) - { - Value = value; - TimeUnit = timenUnit; - } + /// + /// Initializes a new instance of the class with parameters. + /// + /// . + /// . + public AutoRefreshTimeInfo(int value, TimeUnit timenUnit) + { + Value = value; + TimeUnit = timenUnit; } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Utilities/ClipboardHelper.cs b/Source/NETworkManager.Utilities/ClipboardHelper.cs index a93ef271c2..80a9ccae2f 100644 --- a/Source/NETworkManager.Utilities/ClipboardHelper.cs +++ b/Source/NETworkManager.Utilities/ClipboardHelper.cs @@ -1,19 +1,18 @@ using System.Windows; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Class provides static methods to interact with the clipboard. +/// +public static class ClipboardHelper { /// - /// Class provides static methods to interact with the clipboard. + /// Methods to set a text to the clipboard. /// - public static class ClipboardHelper + /// Some text... + public static void SetClipboard(string text) { - /// - /// Methods to set a text to the clipboard. - /// - /// Some text... - public static void SetClipboard(string text) - { - Clipboard.SetDataObject(text, true); - } + Clipboard.SetDataObject(text, true); } } diff --git a/Source/NETworkManager.Utilities/CryptoHelper.cs b/Source/NETworkManager.Utilities/CryptoHelper.cs index 69b1300dcf..3bec1a31ea 100644 --- a/Source/NETworkManager.Utilities/CryptoHelper.cs +++ b/Source/NETworkManager.Utilities/CryptoHelper.cs @@ -1,63 +1,62 @@ using System; using System.Security.Cryptography; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class CryptoHelper { - public static class CryptoHelper + private static readonly int blockSize = 128; + /// + /// + /// + /// + /// + /// + /// + /// + public static byte[] Encrypt(byte[] decryptedBytes, string password, int keySize, int iterations) { - private static readonly int blockSize = 128; - /// - /// - /// - /// - /// - /// - /// - /// - public static byte[] Encrypt(byte[] decryptedBytes, string password, int keySize, int iterations) - { - ReadOnlySpan salt = RandomNumberGenerator.GetBytes(keySize / 8); // Generate salt based - ReadOnlySpan iv = RandomNumberGenerator.GetBytes(blockSize / 8); // Generate iv, has to be the same as the block size - - byte[] key = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, keySize / 8); - - using Aes aes = Aes.Create(); - aes.Key = key; - - int encryptedSize = aes.GetCiphertextLengthCbc(decryptedBytes.Length); - - byte[] cipher = new byte[salt.Length + iv.Length + encryptedSize]; - - Span cipherSpan = cipher; - - salt.CopyTo(cipherSpan); - iv.CopyTo(cipherSpan[salt.Length..]); - - int encrypted = aes.EncryptCbc(decryptedBytes, iv, cipherSpan[(salt.Length + iv.Length)..]); - - return cipher; - } - - /// - /// - /// - /// - /// - /// - /// - /// - public static byte[] Decrypt(byte[] encryptedBytesWithSaltAndIV, string password, int keySize, int iterations) - { - ReadOnlySpan salt = encryptedBytesWithSaltAndIV.AsSpan(0, keySize / 8); // Take salt bytes - ReadOnlySpan iv = encryptedBytesWithSaltAndIV.AsSpan(keySize / 8, blockSize / 8); // Skip salt bytes, take iv bytes - ReadOnlySpan cipher = encryptedBytesWithSaltAndIV.AsSpan((keySize / 8) + (blockSize / 8)); - - byte[] key = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, keySize / 8); - - using Aes aes = Aes.Create(); - aes.Key = key; - - return aes.DecryptCbc(cipher, iv); - } + ReadOnlySpan salt = RandomNumberGenerator.GetBytes(keySize / 8); // Generate salt based + ReadOnlySpan iv = RandomNumberGenerator.GetBytes(blockSize / 8); // Generate iv, has to be the same as the block size + + byte[] key = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, keySize / 8); + + using Aes aes = Aes.Create(); + aes.Key = key; + + int encryptedSize = aes.GetCiphertextLengthCbc(decryptedBytes.Length); + + byte[] cipher = new byte[salt.Length + iv.Length + encryptedSize]; + + Span cipherSpan = cipher; + + salt.CopyTo(cipherSpan); + iv.CopyTo(cipherSpan[salt.Length..]); + + int encrypted = aes.EncryptCbc(decryptedBytes, iv, cipherSpan[(salt.Length + iv.Length)..]); + + return cipher; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public static byte[] Decrypt(byte[] encryptedBytesWithSaltAndIV, string password, int keySize, int iterations) + { + ReadOnlySpan salt = encryptedBytesWithSaltAndIV.AsSpan(0, keySize / 8); // Take salt bytes + ReadOnlySpan iv = encryptedBytesWithSaltAndIV.AsSpan(keySize / 8, blockSize / 8); // Skip salt bytes, take iv bytes + ReadOnlySpan cipher = encryptedBytesWithSaltAndIV.AsSpan((keySize / 8) + (blockSize / 8)); + + byte[] key = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA512, keySize / 8); + + using Aes aes = Aes.Create(); + aes.Key = key; + + return aes.DecryptCbc(cipher, iv); } } diff --git a/Source/NETworkManager.Utilities/CustomCommand.cs b/Source/NETworkManager.Utilities/CustomCommand.cs index 9158526211..130bea5f94 100644 --- a/Source/NETworkManager.Utilities/CustomCommand.cs +++ b/Source/NETworkManager.Utilities/CustomCommand.cs @@ -1,17 +1,16 @@ -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Class provides static methods to manage custom commands. +/// +public static class CustomCommand { /// - /// Class provides static methods to manage custom commands. + /// Method to execute a . /// - public static class CustomCommand + /// which is executed. + public static void Run(CustomCommandInfo info) { - /// - /// Method to execute a . - /// - /// which is executed. - public static void Run(CustomCommandInfo info) - { - ExternalProcessStarter.RunProcess(info.FilePath, info.Arguments); - } + ExternalProcessStarter.RunProcess(info.FilePath, info.Arguments); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Utilities/CustomCommandInfo.cs b/Source/NETworkManager.Utilities/CustomCommandInfo.cs index c11db8b4b4..d80284d360 100644 --- a/Source/NETworkManager.Utilities/CustomCommandInfo.cs +++ b/Source/NETworkManager.Utilities/CustomCommandInfo.cs @@ -1,71 +1,70 @@ using System; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Class stores custom command informations. +/// +public class CustomCommandInfo : ICloneable { /// - /// Class stores custom command informations. + /// Unique Identifiert for this custom command. /// - public class CustomCommandInfo : ICloneable - { - /// - /// Unique Identifiert for this custom command. - /// - public Guid ID { get; set; } + public Guid ID { get; set; } - /// - /// Name of this custom command. - /// - public string Name { get; set; } + /// + /// Name of this custom command. + /// + public string Name { get; set; } - /// - /// Filepath to the application to execute. - /// - public string FilePath { get; set; } + /// + /// Filepath to the application to execute. + /// + public string FilePath { get; set; } - /// - /// Arguments to start the application. - /// - public string Arguments { get; set; } + /// + /// Arguments to start the application. + /// + public string Arguments { get; set; } - /// - /// Create an empty with an - /// - public CustomCommandInfo() - { - ID = Guid.NewGuid(); - } + /// + /// Create an empty with an + /// + public CustomCommandInfo() + { + ID = Guid.NewGuid(); + } - /// - /// Create an . - /// - /// . - /// . - /// . - public CustomCommandInfo(Guid id, string name, string filePath) - { - ID = id; - Name = name; - FilePath = filePath; - } + /// + /// Create an . + /// + /// . + /// . + /// . + public CustomCommandInfo(Guid id, string name, string filePath) + { + ID = id; + Name = name; + FilePath = filePath; + } - /// - /// Create an . - /// - /// . - /// . - /// . - /// . - public CustomCommandInfo(Guid id, string name, string filePath, string arguments) : this(id, name, filePath) - { - Arguments = arguments; - } + /// + /// Create an . + /// + /// . + /// . + /// . + /// . + public CustomCommandInfo(Guid id, string name, string filePath, string arguments) : this(id, name, filePath) + { + Arguments = arguments; + } - /// - /// Method to clone this object. - /// - public object Clone() - { - return MemberwiseClone(); - } + /// + /// Method to clone this object. + /// + public object Clone() + { + return MemberwiseClone(); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Utilities/ExternalProcessStarter.cs b/Source/NETworkManager.Utilities/ExternalProcessStarter.cs index b215a52707..61b9b434c8 100644 --- a/Source/NETworkManager.Utilities/ExternalProcessStarter.cs +++ b/Source/NETworkManager.Utilities/ExternalProcessStarter.cs @@ -1,46 +1,45 @@ using System.Diagnostics; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class ExternalProcessStarter { - public static class ExternalProcessStarter + /// + /// Open an url with the default browser. + /// + /// Url like: https://github.com/BornToBeRoot + public static void OpenUrl(string url) { - /// - /// Open an url with the default browser. - /// - /// Url like: https://github.com/BornToBeRoot - public static void OpenUrl(string url) - { - // Escape the $ in the command promp - url = url.Replace("&", "^&"); + // Escape the $ in the command promp + url = url.Replace("&", "^&"); - Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); - } + Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); + } - public static void RunProcess(string filename) - { - RunProcess(filename, false); - } + public static void RunProcess(string filename) + { + RunProcess(filename, false); + } - public static void RunProcess(string filename, bool asAdmin) - { - RunProcess(filename, "", asAdmin); - } + public static void RunProcess(string filename, bool asAdmin) + { + RunProcess(filename, "", asAdmin); + } - public static void RunProcess(string filename, string arguments = "", bool asAdmin = false) + public static void RunProcess(string filename, string arguments = "", bool asAdmin = false) + { + ProcessStartInfo info = new() { - ProcessStartInfo info = new() - { - FileName = filename, - UseShellExecute = true - }; + FileName = filename, + UseShellExecute = true + }; - if (!string.IsNullOrEmpty(arguments)) - info.Arguments = arguments; + if (!string.IsNullOrEmpty(arguments)) + info.Arguments = arguments; - if (asAdmin) - info.Verb = "runas"; + if (asAdmin) + info.Verb = "runas"; - Process.Start(info); - } + Process.Start(info); } } diff --git a/Source/NETworkManager.Utilities/FileSizeConverter.cs b/Source/NETworkManager.Utilities/FileSizeConverter.cs index 7b4e4cc714..fd3b897d9c 100644 --- a/Source/NETworkManager.Utilities/FileSizeConverter.cs +++ b/Source/NETworkManager.Utilities/FileSizeConverter.cs @@ -1,77 +1,76 @@ -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Class provides static methods to convert file size. +/// +public static class FileSizeConverter { /// - /// Class provides static methods to convert file size. + /// Returns the human-readable file size for an arbitrary, 64-bit file size. + /// The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB". + /// See also: https://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net /// - public static class FileSizeConverter + /// File size as to convert. + /// File size as human readable . + public static string GetBytesReadable(long i) { - /// - /// Returns the human-readable file size for an arbitrary, 64-bit file size. - /// The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB". - /// See also: https://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net - /// - /// File size as to convert. - /// File size as human readable . - public static string GetBytesReadable(long i) - { - // Get absolute value - var absolute_i = (i < 0 ? -i : i); - - // Determine the suffix and readable value - string suffix; - double readable; + // Get absolute value + var absolute_i = (i < 0 ? -i : i); - if (absolute_i >= 0x1000000000000000) // Exabyte - { - suffix = "EB"; - readable = (i >> 50); - } - else if (absolute_i >= 0x4000000000000) // Petabyte - { - suffix = "PB"; - readable = (i >> 40); - } - else if (absolute_i >= 0x10000000000) // Terabyte - { - suffix = "TB"; - readable = (i >> 30); - } - else if (absolute_i >= 0x40000000) // Gigabyte - { - suffix = "GB"; - readable = (i >> 20); - } - else if (absolute_i >= 0x100000) // Megabyte - { - suffix = "MB"; - readable = (i >> 10); - } - else if (absolute_i >= 0x400) // Kilobyte - { - suffix = "KB"; - readable = i; - } - else - { - return i.ToString("0 B"); // Byte - } + // Determine the suffix and readable value + string suffix; + double readable; - // Divide by 1024 to get fractional value - readable /= 1024; - - // Return formatted number with suffix - return readable.ToString("0.## ") + suffix; + if (absolute_i >= 0x1000000000000000) // Exabyte + { + suffix = "EB"; + readable = (i >> 50); } - - /// - /// Method to convert speed as bytes to human readable string. - /// - /// Bytes as . - /// Suffix which is appended to the converted bytes. - /// Speed as human readable . - public static string GetBytesSpeedReadable(long i, string suffix) + else if (absolute_i >= 0x4000000000000) // Petabyte + { + suffix = "PB"; + readable = (i >> 40); + } + else if (absolute_i >= 0x10000000000) // Terabyte + { + suffix = "TB"; + readable = (i >> 30); + } + else if (absolute_i >= 0x40000000) // Gigabyte + { + suffix = "GB"; + readable = (i >> 20); + } + else if (absolute_i >= 0x100000) // Megabyte { - return GetBytesReadable(i) + suffix; + suffix = "MB"; + readable = (i >> 10); } + else if (absolute_i >= 0x400) // Kilobyte + { + suffix = "KB"; + readable = i; + } + else + { + return i.ToString("0 B"); // Byte + } + + // Divide by 1024 to get fractional value + readable /= 1024; + + // Return formatted number with suffix + return readable.ToString("0.## ") + suffix; + } + + /// + /// Method to convert speed as bytes to human readable string. + /// + /// Bytes as . + /// Suffix which is appended to the converted bytes. + /// Speed as human readable . + public static string GetBytesSpeedReadable(long i, string suffix) + { + return GetBytesReadable(i) + suffix; } } diff --git a/Source/NETworkManager.Utilities/HotKeys.cs b/Source/NETworkManager.Utilities/HotKeys.cs index a097506e57..6b96595887 100644 --- a/Source/NETworkManager.Utilities/HotKeys.cs +++ b/Source/NETworkManager.Utilities/HotKeys.cs @@ -1,98 +1,97 @@ using System.Windows.Input; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Class provides static methods for hotkeys. +/// +public static class HotKeys { /// - /// Class provides static methods for hotkeys. + /// Method to calculate the sum of the modifier keys. /// - public static class HotKeys + /// . + /// Sum of the calculated modifier keys. + public static int GetModifierKeysSum(ModifierKeys modifierKeys) { - /// - /// Method to calculate the sum of the modifier keys. - /// - /// . - /// Sum of the calculated modifier keys. - public static int GetModifierKeysSum(ModifierKeys modifierKeys) - { - var sum = 0x0000; + var sum = 0x0000; - if (modifierKeys.HasFlag(ModifierKeys.Alt)) - sum += 0x0001; + if (modifierKeys.HasFlag(ModifierKeys.Alt)) + sum += 0x0001; - if (modifierKeys.HasFlag(ModifierKeys.Control)) - sum += 0x0002; + if (modifierKeys.HasFlag(ModifierKeys.Control)) + sum += 0x0002; - if (modifierKeys.HasFlag(ModifierKeys.Shift)) - sum += 0x0004; + if (modifierKeys.HasFlag(ModifierKeys.Shift)) + sum += 0x0004; - if (modifierKeys.HasFlag(ModifierKeys.Windows)) - sum += 0x0008; + if (modifierKeys.HasFlag(ModifierKeys.Windows)) + sum += 0x0008; - return sum; - } + return sum; + } - /// - /// Method to convert WPF key to WinForms key. - /// - /// WPF key. - /// WinForms key. - public static System.Windows.Forms.Keys WpfKeyToFormsKeys(Key key) - { - return (System.Windows.Forms.Keys)KeyInterop.VirtualKeyFromKey(key); - } + /// + /// Method to convert WPF key to WinForms key. + /// + /// WPF key. + /// WinForms key. + public static System.Windows.Forms.Keys WpfKeyToFormsKeys(Key key) + { + return (System.Windows.Forms.Keys)KeyInterop.VirtualKeyFromKey(key); + } + + /// + /// Method to convert WinForms key to WPF key. + /// + /// WinForms key. + /// WPF key. + public static Key FormsKeysToWpfKey(System.Windows.Forms.Keys keys) + { + return FormsKeysToWpfKey((int)keys); + } + + /// + /// Method to convert WinForms key to WPF key. + /// + /// WinForms key as . + /// WPF key. + + public static Key FormsKeysToWpfKey(int keys) + { + return KeyInterop.KeyFromVirtualKey(keys); + } - /// - /// Method to convert WinForms key to WPF key. - /// - /// WinForms key. - /// WPF key. - public static Key FormsKeysToWpfKey(System.Windows.Forms.Keys keys) + /// + /// Method to get modifier keys from an value. + /// + /// Modifier key as . + /// Return . + public static ModifierKeys GetModifierKeysFromInt(int modifierKeys) + { + var modKeys = ModifierKeys.None; + + if (modifierKeys - 0x0008 >= 0) { - return FormsKeysToWpfKey((int)keys); + modKeys |= ModifierKeys.Windows; + modifierKeys -= 0x0008; } - /// - /// Method to convert WinForms key to WPF key. - /// - /// WinForms key as . - /// WPF key. - - public static Key FormsKeysToWpfKey(int keys) + if (modifierKeys - 0x0004 >= 0) { - return KeyInterop.KeyFromVirtualKey(keys); + modKeys |= ModifierKeys.Shift; + modifierKeys -= 0x0004; } - /// - /// Method to get modifier keys from an value. - /// - /// Modifier key as . - /// Return . - public static ModifierKeys GetModifierKeysFromInt(int modifierKeys) + if (modifierKeys - 0x0002 >= 0) { - var modKeys = ModifierKeys.None; - - if (modifierKeys - 0x0008 >= 0) - { - modKeys |= ModifierKeys.Windows; - modifierKeys -= 0x0008; - } - - if (modifierKeys - 0x0004 >= 0) - { - modKeys |= ModifierKeys.Shift; - modifierKeys -= 0x0004; - } - - if (modifierKeys - 0x0002 >= 0) - { - modKeys |= ModifierKeys.Control; - modifierKeys -= 0x0002; - } - - if (modifierKeys - 0x0001 >= 0) - modKeys |= ModifierKeys.Alt; - - return modKeys; + modKeys |= ModifierKeys.Control; + modifierKeys -= 0x0002; } + + if (modifierKeys - 0x0001 >= 0) + modKeys |= ModifierKeys.Alt; + + return modKeys; } } diff --git a/Source/NETworkManager.Utilities/ListHelper.cs b/Source/NETworkManager.Utilities/ListHelper.cs index 099d11ae95..79fef96082 100644 --- a/Source/NETworkManager.Utilities/ListHelper.cs +++ b/Source/NETworkManager.Utilities/ListHelper.cs @@ -1,35 +1,34 @@ using System.Collections.Generic; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class ListHelper { - public static class ListHelper + public static List Modify(List list, string entry, int length) { - public static List Modify(List list, string entry, int length) - { - var index = list.IndexOf(entry); + var index = list.IndexOf(entry); - if (index != -1) - list.RemoveAt(index); - else if (list.Count == length) - list.RemoveAt(length - 1); + if (index != -1) + list.RemoveAt(index); + else if (list.Count == length) + list.RemoveAt(length - 1); - list.Insert(0, entry); + list.Insert(0, entry); - return list; - } + return list; + } - public static List Modify(List list, int entry, int length) - { - var index = list.IndexOf(entry); + public static List Modify(List list, int entry, int length) + { + var index = list.IndexOf(entry); - if (index != -1) - list.RemoveAt(index); - else if (list.Count == length) - list.RemoveAt(length - 1); + if (index != -1) + list.RemoveAt(index); + else if (list.Count == length) + list.RemoveAt(length - 1); - list.Insert(0, entry); + list.Insert(0, entry); - return list; - } + return list; } } diff --git a/Source/NETworkManager.Utilities/LvlChartsDefaultInfo.cs b/Source/NETworkManager.Utilities/LvlChartsDefaultInfo.cs index 3d31ad5813..853c4dfacd 100644 --- a/Source/NETworkManager.Utilities/LvlChartsDefaultInfo.cs +++ b/Source/NETworkManager.Utilities/LvlChartsDefaultInfo.cs @@ -1,15 +1,15 @@ using System; -namespace NETworkManager.Utilities + +namespace NETworkManager.Utilities; + +public class LvlChartsDefaultInfo { - public class LvlChartsDefaultInfo - { - public DateTime DateTime { get; } - public double Value { get; set; } + public DateTime DateTime { get; } + public double Value { get; set; } - public LvlChartsDefaultInfo(DateTime dateTime, double value) - { - DateTime = dateTime; - Value = value; - } + public LvlChartsDefaultInfo(DateTime dateTime, double value) + { + DateTime = dateTime; + Value = value; } } diff --git a/Source/NETworkManager.Utilities/MACAddressHelper.cs b/Source/NETworkManager.Utilities/MACAddressHelper.cs index 60c6bdca92..9d0b6cc79e 100644 --- a/Source/NETworkManager.Utilities/MACAddressHelper.cs +++ b/Source/NETworkManager.Utilities/MACAddressHelper.cs @@ -3,51 +3,50 @@ using System.Net.NetworkInformation; using System.Text.RegularExpressions; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class MACAddressHelper { - public static class MACAddressHelper + /// + /// Convert a MAC-Address to a byte array + /// + /// + /// + public static byte[] ConvertStringToByteArray(string macAddress) + { + // Regex to replace "-" and ":" in MAC-Address + var regex = new Regex("[-|:|.]"); + var mac = regex.Replace(macAddress, ""); + + // Build the byte-array + var bytes = new byte[mac.Length / 2]; + + // Convert the MAC-Address into byte and fill it... + for (var i = 0; i < 12; i += 2) + bytes[i / 2] = Convert.ToByte(mac.Substring(i, 2), 16); + + return bytes; + } + + public static string GetDefaultFormat(string macAddress) + { + macAddress = macAddress.ToUpper(); + + if (macAddress.Contains("-")) + return macAddress.Replace("-", ":"); + + return !macAddress.Contains(":") ? string.Join(":", Enumerable.Range(0, 6).Select(i => macAddress.Substring(i * 2, 2))) : macAddress; + } + + public static string GetDefaultFormat(PhysicalAddress macAddress) { - /// - /// Convert a MAC-Address to a byte array - /// - /// - /// - public static byte[] ConvertStringToByteArray(string macAddress) - { - // Regex to replace "-" and ":" in MAC-Address - var regex = new Regex("[-|:|.]"); - var mac = regex.Replace(macAddress, ""); - - // Build the byte-array - var bytes = new byte[mac.Length / 2]; - - // Convert the MAC-Address into byte and fill it... - for (var i = 0; i < 12; i += 2) - bytes[i / 2] = Convert.ToByte(mac.Substring(i, 2), 16); - - return bytes; - } - - public static string GetDefaultFormat(string macAddress) - { - macAddress = macAddress.ToUpper(); - - if (macAddress.Contains("-")) - return macAddress.Replace("-", ":"); - - return !macAddress.Contains(":") ? string.Join(":", Enumerable.Range(0, 6).Select(i => macAddress.Substring(i * 2, 2))) : macAddress; - } - - public static string GetDefaultFormat(PhysicalAddress macAddress) - { - return GetDefaultFormat(macAddress.ToString()); - } - - public static string Format(string macAddress, string separator = "") - { - macAddress = macAddress.ToUpper().Replace("-", "").Replace(":", ""); - - return string.Join(separator, Enumerable.Range(0, 6).Select(i => macAddress.Substring(i * 2, 2))); - } + return GetDefaultFormat(macAddress.ToString()); + } + + public static string Format(string macAddress, string separator = "") + { + macAddress = macAddress.ToUpper().Replace("-", "").Replace(":", ""); + + return string.Join(separator, Enumerable.Range(0, 6).Select(i => macAddress.Substring(i * 2, 2))); } } diff --git a/Source/NETworkManager.Utilities/NativeMethods.cs b/Source/NETworkManager.Utilities/NativeMethods.cs index 26262b8173..c89505f38c 100644 --- a/Source/NETworkManager.Utilities/NativeMethods.cs +++ b/Source/NETworkManager.Utilities/NativeMethods.cs @@ -4,80 +4,79 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public class NativeMethods { - public class NativeMethods + #region Win32 Constants + public const int GWL_STYLE = -16; + public const int WS_THICKFRAME = 0x00040000; + public const int SWP_NOZORDER = 0x0004; + public const int SWP_NOACTIVATE = 0x0010; + public const long WS_POPUP = 0x80000000L; + public const long WS_CAPTION = 0x00C00000L; + #endregion + + #region Enum + + public enum WindowShowStyle : uint { - #region Win32 Constants - public const int GWL_STYLE = -16; - public const int WS_THICKFRAME = 0x00040000; - public const int SWP_NOZORDER = 0x0004; - public const int SWP_NOACTIVATE = 0x0010; - public const long WS_POPUP = 0x80000000L; - public const long WS_CAPTION = 0x00C00000L; - #endregion - - #region Enum - - public enum WindowShowStyle : uint - { - Hide = 0, - ShowNormal = 1, - ShowMinimized = 2, - ShowMaximized = 3, - Maximize = 3, - ShowNormalNoActivate = 4, - Show = 5, - Minimize = 6, - ShowMinNoActivate = 7, - ShowNoActivate = 8, - Restore = 9, - ShowDefault = 10, - ForceMinimized = 11 - } - - public enum WM : uint - { - SYSCOMMAND = 0x0112 - } - #endregion - - #region Pinvoke/Win32 Methods - [DllImport("user32.dll")] - public static extern IntPtr GetForegroundWindow(); - - [DllImport("user32.dll", SetLastError = true)] - public static extern long SetParent(IntPtr hWndChild, IntPtr hWndParent); - - [DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)] - public static extern long GetWindowLong(IntPtr hWnd, int nIndex); - - // http://msdn.microsoft.com/en-us/library/windows/desktop/ms644898%28v=vs.85%29.aspx - public static IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong) - { - return IntPtr.Size == 8 ? SetWindowLongPtr64(hWnd, nIndex, dwNewLong) : new IntPtr(SetWindowLong32(hWnd, nIndex, dwNewLong)); - } - - [DllImport("user32.dll", EntryPoint = "SetWindowLong")] - private static extern int SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); - - [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] - private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong); - - [DllImport("user32.dll", EntryPoint = "SetWindowPos")] - public static extern IntPtr SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags); - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); - - [DllImport("user32.dll", SetLastError = true)] - public static extern bool MoveWindow(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint); - - [DllImport("user32.dll")] - public static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); - - [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - public static extern bool SetForegroundWindow(IntPtr hWnd); - #endregion + Hide = 0, + ShowNormal = 1, + ShowMinimized = 2, + ShowMaximized = 3, + Maximize = 3, + ShowNormalNoActivate = 4, + Show = 5, + Minimize = 6, + ShowMinNoActivate = 7, + ShowNoActivate = 8, + Restore = 9, + ShowDefault = 10, + ForceMinimized = 11 } + + public enum WM : uint + { + SYSCOMMAND = 0x0112 + } + #endregion + + #region Pinvoke/Win32 Methods + [DllImport("user32.dll")] + public static extern IntPtr GetForegroundWindow(); + + [DllImport("user32.dll", SetLastError = true)] + public static extern long SetParent(IntPtr hWndChild, IntPtr hWndParent); + + [DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)] + public static extern long GetWindowLong(IntPtr hWnd, int nIndex); + + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms644898%28v=vs.85%29.aspx + public static IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong) + { + return IntPtr.Size == 8 ? SetWindowLongPtr64(hWnd, nIndex, dwNewLong) : new IntPtr(SetWindowLong32(hWnd, nIndex, dwNewLong)); + } + + [DllImport("user32.dll", EntryPoint = "SetWindowLong")] + private static extern int SetWindowLong32(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] + private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, IntPtr dwNewLong); + + [DllImport("user32.dll", EntryPoint = "SetWindowPos")] + public static extern IntPtr SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", SetLastError = true)] + public static extern bool MoveWindow(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint); + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, WindowShowStyle nCmdShow); + + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern bool SetForegroundWindow(IntPtr hWnd); + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager.Utilities/PortRangeHelper.cs b/Source/NETworkManager.Utilities/PortRangeHelper.cs index dbd7217c94..b6afeeaee1 100644 --- a/Source/NETworkManager.Utilities/PortRangeHelper.cs +++ b/Source/NETworkManager.Utilities/PortRangeHelper.cs @@ -1,38 +1,37 @@ using System.Threading.Tasks; using System.Collections.Generic; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class PortRangeHelper { - public static class PortRangeHelper + public static Task ConvertPortRangeToIntArrayAsync(string portRange) { - public static Task ConvertPortRangeToIntArrayAsync(string portRange) - { - return Task.Run(() => ConvertPortRangeToIntArray(portRange)); - } + return Task.Run(() => ConvertPortRangeToIntArray(portRange)); + } - // Generate from a string like "9; 11-13; 15" an list with "9,11,12,13,15" - public static int[] ConvertPortRangeToIntArray(string portRange) - { - var list = new List(); + // Generate from a string like "9; 11-13; 15" an list with "9,11,12,13,15" + public static int[] ConvertPortRangeToIntArray(string portRange) + { + var list = new List(); - foreach (var portOrRange in portRange.Replace(" ", "").Split(';')) + foreach (var portOrRange in portRange.Replace(" ", "").Split(';')) + { + if (portOrRange.Contains("-")) { - if (portOrRange.Contains("-")) - { - var portRangeSplit = portOrRange.Split('-'); + var portRangeSplit = portOrRange.Split('-'); - for (var i = int.Parse(portRangeSplit[0]); i < int.Parse(portRangeSplit[1]) + 1; i++) - { - list.Add(i); - } - } - else + for (var i = int.Parse(portRangeSplit[0]); i < int.Parse(portRangeSplit[1]) + 1; i++) { - list.Add(int.Parse(portOrRange)); + list.Add(i); } } - - return list.ToArray(); + else + { + list.Add(int.Parse(portOrRange)); + } } + + return list.ToArray(); } } \ No newline at end of file diff --git a/Source/NETworkManager.Utilities/RegexHelper.cs b/Source/NETworkManager.Utilities/RegexHelper.cs index cfa91eafe4..cfb0e31cb5 100644 --- a/Source/NETworkManager.Utilities/RegexHelper.cs +++ b/Source/NETworkManager.Utilities/RegexHelper.cs @@ -1,87 +1,86 @@ using System.Diagnostics.CodeAnalysis; -namespace NETworkManager.Utilities -{ - public static class RegexHelper - { - /// - /// Match an IPv4-Address like 192.168.178.1 - /// - private const string IPv4AddressValues = @"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; +namespace NETworkManager.Utilities; - /// - /// Match exactly an IPv4-Address like 192.168.178.1 - /// - public const string IPv4AddressRegex = "^" + IPv4AddressValues + "$"; +public static class RegexHelper +{ + /// + /// Match an IPv4-Address like 192.168.178.1 + /// + private const string IPv4AddressValues = @"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; - // Match IPv4-Address within a string - public const string IPv4AddressExctractRegex = IPv4AddressValues; + /// + /// Match exactly an IPv4-Address like 192.168.178.1 + /// + public const string IPv4AddressRegex = "^" + IPv4AddressValues + "$"; - // Match IPv4-Address Range like 192.168.178.1-192.168.178.127 - public const string IPv4AddressRangeRegex = "^" + IPv4AddressValues + "-" + IPv4AddressValues + "$"; + // Match IPv4-Address within a string + public const string IPv4AddressExctractRegex = IPv4AddressValues; - // Match a MAC-Address 000000000000 00:00:00:00:00:00, 00-00-00-00-00-00-00 or 0000.0000.0000 - public const string MACAddressRegex = @"^^[A-Fa-f0-9]{12}$|^[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}$|^[A-Fa-f0-9]{4}.[A-Fa-f0-9]{4}.[A-Fa-f0-9]{4}$$"; + // Match IPv4-Address Range like 192.168.178.1-192.168.178.127 + public const string IPv4AddressRangeRegex = "^" + IPv4AddressValues + "-" + IPv4AddressValues + "$"; - // Matche the first 3 bytes of a MAC-Address 000000, 00:00:00, 00-00-00 - public const string MACAddressFirst3BytesRegex = @"^[A-Fa-f0-9]{6}$|^[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}$|^[A-Fa-f0-9]{4}.[A-Fa-f0-9]{2}$"; + // Match a MAC-Address 000000000000 00:00:00:00:00:00, 00-00-00-00-00-00-00 or 0000.0000.0000 + public const string MACAddressRegex = @"^^[A-Fa-f0-9]{12}$|^[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}$|^[A-Fa-f0-9]{4}.[A-Fa-f0-9]{4}.[A-Fa-f0-9]{4}$$"; - // Private subnetmask / cidr values - private const string SubnetmaskValues = @"(((255\.){3}(255|254|252|248|240|224|192|128|0+))|((255\.){2}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){2})|((255|254|252|248|240|224|192|128|0+)(\.0+){3}))"; - private const string CidrRegex = @"([1-9]|[1-2][0-9]|3[0-2])"; + // Matche the first 3 bytes of a MAC-Address 000000, 00:00:00, 00-00-00 + public const string MACAddressFirst3BytesRegex = @"^[A-Fa-f0-9]{6}$|^[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}(:|-){1}[A-Fa-f0-9]{2}$|^[A-Fa-f0-9]{4}.[A-Fa-f0-9]{2}$"; - // Match a Subnetmask like 255.255.255.0 - public const string SubnetmaskRegex = @"^" + SubnetmaskValues + @"$"; + // Private subnetmask / cidr values + private const string SubnetmaskValues = @"(((255\.){3}(255|254|252|248|240|224|192|128|0+))|((255\.){2}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){2})|((255|254|252|248|240|224|192|128|0+)(\.0+){3}))"; + private const string CidrRegex = @"([1-9]|[1-2][0-9]|3[0-2])"; - // Match a subnet from 192.168.178.0/1 to 192.168.178.0/32 - public const string IPv4AddressCidrRegex = @"^" + IPv4AddressValues + @"\/" + CidrRegex + @"$"; + // Match a Subnetmask like 255.255.255.0 + public const string SubnetmaskRegex = @"^" + SubnetmaskValues + @"$"; - // Match a subnet from 192.168.178.0/192.0.0.0 to 192.168.178.0/255.255.255.255 - public const string IPv4AddressSubnetmaskRegex = @"^" + IPv4AddressValues + @"\/" + SubnetmaskValues + @"$"; + // Match a subnet from 192.168.178.0/1 to 192.168.178.0/32 + public const string IPv4AddressCidrRegex = @"^" + IPv4AddressValues + @"\/" + CidrRegex + @"$"; - // Match IPv6 address like ::1 - public const string IPv6AddressRegex = @"(?:^|(?<=\s))(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(?=\s|$)"; + // Match a subnet from 192.168.178.0/192.0.0.0 to 192.168.178.0/255.255.255.255 + public const string IPv4AddressSubnetmaskRegex = @"^" + IPv4AddressValues + @"\/" + SubnetmaskValues + @"$"; - // Match a subnet like 2001:0db8::/64 - public const string IPv6AddressCidrRegex = @"^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])){1}?$"; + // Match IPv6 address like ::1 + public const string IPv6AddressRegex = @"(?:^|(?<=\s))(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(?=\s|$)"; - // Match a range like [0-255], [0,2,4] and [2,4-6] - public const string SpecialRangeRegex = @"\[((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)-(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))([,]((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)-(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))))*\]"; + // Match a subnet like 2001:0db8::/64 + public const string IPv6AddressCidrRegex = @"^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])){1}?$"; - // Match a IPv4-Address like 192.168.[50-100].1 - public const string IPv4AddressSpecialRangeRegex = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|" + SpecialRangeRegex + @")\.){3}((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|" + SpecialRangeRegex + @")$"; + // Match a range like [0-255], [0,2,4] and [2,4-6] + public const string SpecialRangeRegex = @"\[((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)-(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))([,]((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)-(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))))*\]"; - // Private hostname values - private const string HostnameValues = @"(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])"; + // Match a IPv4-Address like 192.168.[50-100].1 + public const string IPv4AddressSpecialRangeRegex = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|" + SpecialRangeRegex + @")\.){3}((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|" + SpecialRangeRegex + @")$"; - // Hostname regex like server-01 or server-01.example.com - public const string HostnameRegex = @"^" + HostnameValues + @"$"; + // Private hostname values + private const string HostnameValues = @"(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])"; - // Match a hostname with cidr like server-01.example.com/24 - public const string HostnameCidrRegex = @"^" + HostnameValues + @"\/" + CidrRegex + @"$"; + // Hostname regex like server-01 or server-01.example.com + public const string HostnameRegex = @"^" + HostnameValues + @"$"; - // Match a hostname with subnetmask like server-01.example.com/255.255.255.0 - public const string HostnameSubnetmaskRegex = @"^" + HostnameValues + @"\/" + SubnetmaskValues + @"$"; + // Match a hostname with cidr like server-01.example.com/24 + public const string HostnameCidrRegex = @"^" + HostnameValues + @"\/" + CidrRegex + @"$"; - // Match a domain local.example.com - public const string DomainRegex = @"^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$"; + // Match a hostname with subnetmask like server-01.example.com/255.255.255.0 + public const string HostnameSubnetmaskRegex = @"^" + HostnameValues + @"\/" + SubnetmaskValues + @"$"; - // Private port values - private const string PortValues = @"((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))"; + // Match a domain local.example.com + public const string DomainRegex = @"^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$"; - // Match a port between 1-65535 - public const string PortRegex = @"^" + PortValues + @"$"; - - // Match any filepath (like "c:\temp\") --> https://www.codeproject.com/Tips/216238/Regular-Expression-to-Validate-File-Path-and-Exten - public const string FilePathRegex = @"^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+$"; + // Private port values + private const string PortValues = @"((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))"; - // Match any fullname (like "c:\temp\test.txt") --> https://www.codeproject.com/Tips/216238/Regular-Expression-to-Validate-File-Path-and-Exten - public const string FullNameRegex = @"^(?:[\w]\:|\\)(\\[a-zA-Z0-9_\-\s\.()~!@#$%^&=+';,{}\[\]]+)+\.[a-zA-z0-9]{1,4}$"; + // Match a port between 1-65535 + public const string PortRegex = @"^" + PortValues + @"$"; + + // Match any filepath (like "c:\temp\") --> https://www.codeproject.com/Tips/216238/Regular-Expression-to-Validate-File-Path-and-Exten + public const string FilePathRegex = @"^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+$"; - // Match a string that doesn't end with ";" (like "80; ldap; ssh; 443") - public const string StringNotEndWithSemicolonRegex = @"^.*[^;]$"; + // Match any fullname (like "c:\temp\test.txt") --> https://www.codeproject.com/Tips/216238/Regular-Expression-to-Validate-File-Path-and-Exten + public const string FullNameRegex = @"^(?:[\w]\:|\\)(\\[a-zA-Z0-9_\-\s\.()~!@#$%^&=+';,{}\[\]]+)+\.[a-zA-z0-9]{1,4}$"; - // Match a number (like 12, 12.4, 12,3) - public const string NumberRegex = @"^\d+((\.|,)\d+)?$"; - } + // Match a string that doesn't end with ";" (like "80; ldap; ssh; 443") + public const string StringNotEndWithSemicolonRegex = @"^.*[^;]$"; + + // Match a number (like 12, 12.4, 12,3) + public const string NumberRegex = @"^\d+((\.|,)\d+)?$"; } diff --git a/Source/NETworkManager.Utilities/RelayCommand.cs b/Source/NETworkManager.Utilities/RelayCommand.cs index 48bbbb57d3..cea11039db 100644 --- a/Source/NETworkManager.Utilities/RelayCommand.cs +++ b/Source/NETworkManager.Utilities/RelayCommand.cs @@ -4,46 +4,45 @@ // Source: https://msdn.microsoft.com/en-us/magazine/dd419663.aspx?f=255&MSPPError=-2147217396#id0090030 -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public class RelayCommand : ICommand { - public class RelayCommand : ICommand + #region Fields + + private readonly Action _execute; + + private readonly Predicate _canExecute; + #endregion + + #region Constructors + public RelayCommand(Action execute) : this(execute, null) + { + + } + + public RelayCommand(Action execute, Predicate canExecute) + { + _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; + } + #endregion + + #region ICommand Members + [DebuggerStepThrough] + public bool CanExecute(object parameter) + { + return _canExecute?.Invoke(parameter) ?? true; + } + + public event EventHandler CanExecuteChanged + { + add => CommandManager.RequerySuggested += value; + remove => CommandManager.RequerySuggested -= value; + } + + public void Execute(object parameter) { - #region Fields - - private readonly Action _execute; - - private readonly Predicate _canExecute; - #endregion - - #region Constructors - public RelayCommand(Action execute) : this(execute, null) - { - - } - - public RelayCommand(Action execute, Predicate canExecute) - { - _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; - } - #endregion - - #region ICommand Members - [DebuggerStepThrough] - public bool CanExecute(object parameter) - { - return _canExecute?.Invoke(parameter) ?? true; - } - - public event EventHandler CanExecuteChanged - { - add => CommandManager.RequerySuggested += value; - remove => CommandManager.RequerySuggested -= value; - } - - public void Execute(object parameter) - { - _execute(parameter); - } - #endregion + _execute(parameter); } + #endregion } diff --git a/Source/NETworkManager.Utilities/SecureStringHelper.cs b/Source/NETworkManager.Utilities/SecureStringHelper.cs index 33d2fb5ed3..2261b2fec3 100644 --- a/Source/NETworkManager.Utilities/SecureStringHelper.cs +++ b/Source/NETworkManager.Utilities/SecureStringHelper.cs @@ -2,36 +2,35 @@ using System; using System.Runtime.InteropServices; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class SecureStringHelper { - public static class SecureStringHelper + public static string ConvertToString(SecureString secureString) { - public static string ConvertToString(SecureString secureString) + var valuePtr = IntPtr.Zero; + try { - var valuePtr = IntPtr.Zero; - try - { - valuePtr = Marshal.SecureStringToGlobalAllocUnicode(secureString); - return Marshal.PtrToStringUni(valuePtr); - } - finally - { - Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); - } + valuePtr = Marshal.SecureStringToGlobalAllocUnicode(secureString); + return Marshal.PtrToStringUni(valuePtr); } - - public static SecureString ConvertToSecureString(string clearText) + finally { - if (clearText == null) - throw new ArgumentNullException(nameof(clearText)); + Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); + } + } - var securePassword = new SecureString(); + public static SecureString ConvertToSecureString(string clearText) + { + if (clearText == null) + throw new ArgumentNullException(nameof(clearText)); - foreach (var c in clearText) - securePassword.AppendChar(c); + var securePassword = new SecureString(); - securePassword.MakeReadOnly(); - return securePassword; - } + foreach (var c in clearText) + securePassword.AppendChar(c); + + securePassword.MakeReadOnly(); + return securePassword; } } \ No newline at end of file diff --git a/Source/NETworkManager.Utilities/SingleInstance.cs b/Source/NETworkManager.Utilities/SingleInstance.cs index 64d8d9b98f..018db974a1 100644 --- a/Source/NETworkManager.Utilities/SingleInstance.cs +++ b/Source/NETworkManager.Utilities/SingleInstance.cs @@ -3,15 +3,14 @@ using System; using System.Runtime.InteropServices; -namespace NETworkManager.Utilities -{ - public class SingleInstance - { - public const int HWND_BROADCAST = 0xffff; - public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); - [DllImport("user32")] - public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); - [DllImport("user32")] - public static extern int RegisterWindowMessage(string message); - } +namespace NETworkManager.Utilities; + +public class SingleInstance +{ + public const int HWND_BROADCAST = 0xffff; + public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); + [DllImport("user32")] + public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); + [DllImport("user32")] + public static extern int RegisterWindowMessage(string message); } diff --git a/Source/NETworkManager.Utilities/SingletonBase.cs b/Source/NETworkManager.Utilities/SingletonBase.cs index 3b1bc37eb4..f94a8102cc 100644 --- a/Source/NETworkManager.Utilities/SingletonBase.cs +++ b/Source/NETworkManager.Utilities/SingletonBase.cs @@ -1,25 +1,24 @@ -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Abstract class to implement a generic singleton. +/// +/// Class +public abstract class SingletonBase where T : class, new() { /// - /// Abstract class to implement a generic singleton. + /// Holds the instance of the class. /// - /// Class - public abstract class SingletonBase where T : class, new() - { - /// - /// Holds the instance of the class. - /// - private static T _instance; + private static T _instance; - /// - /// Returns the current instance of the class. - /// - /// Instance of the class. - public static T GetInstance() - { - _instance ??= new T(); + /// + /// Returns the current instance of the class. + /// + /// Instance of the class. + public static T GetInstance() + { + _instance ??= new T(); - return _instance; - } + return _instance; } } diff --git a/Source/NETworkManager.Utilities/StringHelper.cs b/Source/NETworkManager.Utilities/StringHelper.cs index 657dffac25..d42fe64d58 100644 --- a/Source/NETworkManager.Utilities/StringHelper.cs +++ b/Source/NETworkManager.Utilities/StringHelper.cs @@ -1,17 +1,16 @@ using System.Text.RegularExpressions; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class StringHelper { - public static class StringHelper + /// + /// Method to remove whitespaces from a string. + /// + /// Text with whitespaces. + /// Text without whitespaces. + public static string RemoveWhitespace(string input) { - /// - /// Method to remove whitespaces from a string. - /// - /// Text with whitespaces. - /// Text without whitespaces. - public static string RemoveWhitespace(string input) - { - return Regex.Replace(input, @"\s+", ""); - } + return Regex.Replace(input, @"\s+", ""); } } diff --git a/Source/NETworkManager.Utilities/TimeUnit.cs b/Source/NETworkManager.Utilities/TimeUnit.cs index dabaf0ac13..065bef12fe 100644 --- a/Source/NETworkManager.Utilities/TimeUnit.cs +++ b/Source/NETworkManager.Utilities/TimeUnit.cs @@ -1,28 +1,27 @@ -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +/// +/// Enum for time units. +/// +public enum TimeUnit { /// - /// Enum for time units. + /// No time unit. /// - public enum TimeUnit - { - /// - /// No time unit. - /// - None, + None, - /// - /// Second(s) time unit. - /// - Second, + /// + /// Second(s) time unit. + /// + Second, - /// - /// Minute(s) time unit. - /// - Minute, + /// + /// Minute(s) time unit. + /// + Minute, - /// - /// Hour(s) time unit. - /// - Hour - } + /// + /// Hour(s) time unit. + /// + Hour } diff --git a/Source/NETworkManager.Utilities/TimestampHelper.cs b/Source/NETworkManager.Utilities/TimestampHelper.cs index e02206d9bd..93c5956704 100644 --- a/Source/NETworkManager.Utilities/TimestampHelper.cs +++ b/Source/NETworkManager.Utilities/TimestampHelper.cs @@ -1,12 +1,11 @@ using System; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public static class TimestampHelper { - public static class TimestampHelper + public static string GetTimestamp() { - public static string GetTimestamp() - { - return DateTime.Now.ToString("yyyyMMddHHmmss"); - } + return DateTime.Now.ToString("yyyyMMddHHmmss"); } } diff --git a/Source/NETworkManager.Utilities/VisualTreeHelper.cs b/Source/NETworkManager.Utilities/VisualTreeHelper.cs index fcd0830627..67e5f75e03 100644 --- a/Source/NETworkManager.Utilities/VisualTreeHelper.cs +++ b/Source/NETworkManager.Utilities/VisualTreeHelper.cs @@ -1,28 +1,27 @@ using System.Collections.Generic; using System.Windows; -namespace NETworkManager.Utilities +namespace NETworkManager.Utilities; + +public class VisualTreeHelper { - public class VisualTreeHelper + public static IEnumerable FindVisualChildren(DependencyObject depObj) where T : DependencyObject { - public static IEnumerable FindVisualChildren(DependencyObject depObj) where T : DependencyObject + if (depObj == null) + yield break; + + for (var i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(depObj); i++) { - if (depObj == null) - yield break; + var child = System.Windows.Media.VisualTreeHelper.GetChild(depObj, i); - for (var i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(depObj); i++) + if (child is T variable) { - var child = System.Windows.Media.VisualTreeHelper.GetChild(depObj, i); - - if (child is T variable) - { - yield return variable; - } + yield return variable; + } - foreach (var childOfChild in FindVisualChildren(child)) - { - yield return childOfChild; - } + foreach (var childOfChild in FindVisualChildren(child)) + { + yield return childOfChild; } } } From 4e12f6a9759da34374790d50d3af9fb18f49a07b Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:23:48 +0100 Subject: [PATCH 04/11] Chore: Use .NET 7 syntax --- .../AccentColorInfo.cs | 14 +- .../AppearanceManager.cs | 207 +- .../Application/PuTTY.cs | 55 +- .../NETworkManager.Settings/AssemblyInfo.cs | 19 +- .../AssemblyManager.cs | 29 +- .../AutostartManager.cs | 71 +- .../NETworkManager.Settings/BaseColorInfo.cs | 17 +- .../CommandLineInfo.cs | 23 +- .../CommandLineManager.cs | 135 +- .../ConfigurationInfo.cs | 63 +- .../ConfigurationManager.cs | 33 +- .../GlobalStaticConfiguration.cs | 361 +- .../SettingsFileInfo.cs | 21 - .../NETworkManager.Settings/SettingsInfo.cs | 5935 ++++++++--------- .../SettingsViewGroup.cs | 11 +- .../SettingsViewInfo.cs | 45 +- .../SettingsViewManager.cs | 73 +- .../SettingsViewName.cs | 61 +- .../NETworkManager.Settings/ThemeColorInfo.cs | 14 +- Source/NETworkManager.Settings/ThemeInfo.cs | 43 +- .../UpdateAvailableArgs.cs | 31 +- 21 files changed, 3611 insertions(+), 3650 deletions(-) delete mode 100644 Source/NETworkManager.Settings/SettingsFileInfo.cs diff --git a/Source/NETworkManager.Settings/AccentColorInfo.cs b/Source/NETworkManager.Settings/AccentColorInfo.cs index 3c028182ea..84f761a060 100644 --- a/Source/NETworkManager.Settings/AccentColorInfo.cs +++ b/Source/NETworkManager.Settings/AccentColorInfo.cs @@ -1,10 +1,10 @@  -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +/// +/// Class contains informations about MahApps.Metro accents. +/// +public class AccentColorInfo : BaseColorInfo { - /// - /// Class contains informations about MahApps.Metro accents. - /// - public class AccentColorInfo : BaseColorInfo - { - } + } diff --git a/Source/NETworkManager.Settings/AppearanceManager.cs b/Source/NETworkManager.Settings/AppearanceManager.cs index c3798af003..5e1f254b45 100644 --- a/Source/NETworkManager.Settings/AppearanceManager.cs +++ b/Source/NETworkManager.Settings/AppearanceManager.cs @@ -8,126 +8,125 @@ using System.Windows; using System.Windows.Media; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +/// +/// Class provides static variables and methods to change the theme and accent of the application. +/// +public static class AppearanceManager { /// - /// Class provides static variables and methods to change the theme and accent of the application. + /// Name of the folder inside the application directory where the custom themes are stored. /// - public static class AppearanceManager - { - /// - /// Name of the folder inside the application directory where the custom themes are stored. - /// - private const string ThemeFolderName = "Themes"; - - /// - /// List who contains all MahApps.Metro themes. - /// - public static List Themes { get; set; } - - /// - /// List who contains all MahApps.Metro custom themes. - /// - public static List CustomThemes { get; set; } - - /// - /// List who contains all MahApps.Metro accents. - /// - public static List Accents { get; set; } - - /// - /// Containes the default settings for a new - /// - public static MetroDialogSettings MetroDialog = new(); - - /// - /// Load the MahApps.Metro themes and accents when needed. - /// - static AppearanceManager() - { - Themes = ThemeManager.Current.Themes - .GroupBy(x => x.BaseColorScheme) - .Select(x => x.First()) - .Select(x => new ThemeColorInfo { Name = x.BaseColorScheme, Color = x.Resources["MahApps.Brushes.ThemeBackground"] as Brush }) - .ToList(); - - Accents = ThemeManager.Current.Themes - .GroupBy(x => x.ColorScheme) - .OrderBy(x => x.Key) - .Select(x => new AccentColorInfo { Name = x.Key, Color = x.First().ShowcaseBrush }) - .ToList(); - - LoadCustomThemes(); - - MetroDialog.CustomResourceDictionary = new ResourceDictionary - { - Source = new Uri("NETworkManager;component/Resources/Styles/MetroDialogStyles.xaml", UriKind.RelativeOrAbsolute), - }; - - MetroDialog.DialogButtonFontSize = 14; - MetroDialog.DialogMessageFontSize = 14; - } + private const string ThemeFolderName = "Themes"; - /// - /// Change the appearance based on the user settings. This method should be called once, when starting the application. - /// - public static void Load() - { - if (SettingsManager.Current.Appearance_UseCustomTheme && CustomThemes.Count > 0) - { - ChangeTheme(CustomThemes.FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_CustomThemeName) ?? CustomThemes.First()); - } - else - { - ChangeTheme(SettingsManager.Current.Appearance_Theme); - ChangeAccent(SettingsManager.Current.Appearance_Accent); - } - } + /// + /// List who contains all MahApps.Metro themes. + /// + public static List Themes { get; set; } - /// - /// Method to load the custom themes from a folder into the . - /// - private static void LoadCustomThemes() - { - List customThemes = new(); + /// + /// List who contains all MahApps.Metro custom themes. + /// + public static List CustomThemes { get; set; } + + /// + /// List who contains all MahApps.Metro accents. + /// + public static List Accents { get; set; } - foreach (var file in Directory.GetFiles(Path.Combine(ConfigurationManager.Current.ExecutionPath, ThemeFolderName))) - { - LibraryTheme libraryTheme = new(new Uri(file), MahAppsLibraryThemeProvider.DefaultInstance); + /// + /// Containes the default settings for a new + /// + public static MetroDialogSettings MetroDialog = new(); - customThemes.Add(new ThemeInfo(libraryTheme.Name, libraryTheme.DisplayName)); + /// + /// Load the MahApps.Metro themes and accents when needed. + /// + static AppearanceManager() + { + Themes = ThemeManager.Current.Themes + .GroupBy(x => x.BaseColorScheme) + .Select(x => x.First()) + .Select(x => new ThemeColorInfo { Name = x.BaseColorScheme, Color = x.Resources["MahApps.Brushes.ThemeBackground"] as Brush }) + .ToList(); - ThemeManager.Current.AddLibraryTheme(libraryTheme); - } + Accents = ThemeManager.Current.Themes + .GroupBy(x => x.ColorScheme) + .OrderBy(x => x.Key) + .Select(x => new AccentColorInfo { Name = x.Key, Color = x.First().ShowcaseBrush }) + .ToList(); - CustomThemes = customThemes; - } + LoadCustomThemes(); - /// - /// Method to change the application theme. - /// - /// Name of the MahApps theme base color. - public static void ChangeTheme(string name) + MetroDialog.CustomResourceDictionary = new ResourceDictionary { - ThemeManager.Current.ChangeThemeBaseColor(System.Windows.Application.Current, name); - } + Source = new Uri("NETworkManager;component/Resources/Styles/MetroDialogStyles.xaml", UriKind.RelativeOrAbsolute), + }; + + MetroDialog.DialogButtonFontSize = 14; + MetroDialog.DialogMessageFontSize = 14; + } - /// - /// Method to change the application accent. - /// - /// Name of the MahApps theme accent color. - public static void ChangeAccent(string name) + /// + /// Change the appearance based on the user settings. This method should be called once, when starting the application. + /// + public static void Load() + { + if (SettingsManager.Current.Appearance_UseCustomTheme && CustomThemes.Count > 0) { - ThemeManager.Current.ChangeThemeColorScheme(System.Windows.Application.Current, name); + ChangeTheme(CustomThemes.FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_CustomThemeName) ?? CustomThemes.First()); } + else + { + ChangeTheme(SettingsManager.Current.Appearance_Theme); + ChangeAccent(SettingsManager.Current.Appearance_Accent); + } + } + + /// + /// Method to load the custom themes from a folder into the . + /// + private static void LoadCustomThemes() + { + List customThemes = new(); - /// - /// Method to change the application theme based on the name in . - /// - /// Theme as to apply. - public static void ChangeTheme(ThemeInfo themeInfo) + foreach (var file in Directory.GetFiles(Path.Combine(ConfigurationManager.Current.ExecutionPath, ThemeFolderName))) { - ThemeManager.Current.ChangeTheme(System.Windows.Application.Current, themeInfo.Name); + LibraryTheme libraryTheme = new(new Uri(file), MahAppsLibraryThemeProvider.DefaultInstance); + + customThemes.Add(new ThemeInfo(libraryTheme.Name, libraryTheme.DisplayName)); + + ThemeManager.Current.AddLibraryTheme(libraryTheme); } + + CustomThemes = customThemes; + } + + /// + /// Method to change the application theme. + /// + /// Name of the MahApps theme base color. + public static void ChangeTheme(string name) + { + ThemeManager.Current.ChangeThemeBaseColor(System.Windows.Application.Current, name); + } + + /// + /// Method to change the application accent. + /// + /// Name of the MahApps theme accent color. + public static void ChangeAccent(string name) + { + ThemeManager.Current.ChangeThemeColorScheme(System.Windows.Application.Current, name); + } + + /// + /// Method to change the application theme based on the name in . + /// + /// Theme as to apply. + public static void ChangeTheme(ThemeInfo themeInfo) + { + ThemeManager.Current.ChangeTheme(System.Windows.Application.Current, themeInfo.Name); } } diff --git a/Source/NETworkManager.Settings/Application/PuTTY.cs b/Source/NETworkManager.Settings/Application/PuTTY.cs index 7c55941e2f..76c49e21e4 100644 --- a/Source/NETworkManager.Settings/Application/PuTTY.cs +++ b/Source/NETworkManager.Settings/Application/PuTTY.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.PuTTY; using System.IO; -namespace NETworkManager.Settings.Application -{ - public static class PuTTY - { - public static string PortableLogPath => Path.Combine(ConfigurationManager.Current.ExecutionPath, "PuTTY_LogFiles"); +namespace NETworkManager.Settings.Application; - public static string LogPath => ConfigurationManager.Current.IsPortable ? PortableLogPath : SettingsManager.Current.PuTTY_LogPath; +public static class PuTTY +{ + public static string PortableLogPath => Path.Combine(ConfigurationManager.Current.ExecutionPath, "PuTTY_LogFiles"); - public static int GetPortOrBaudByConnectionMode(ConnectionMode mode) - { - var portOrBaud = 0; + public static string LogPath => ConfigurationManager.Current.IsPortable ? PortableLogPath : SettingsManager.Current.PuTTY_LogPath; - switch (mode) - { - case ConnectionMode.SSH: - portOrBaud = SettingsManager.Current.PuTTY_SSHPort; - break; - case ConnectionMode.Telnet: - portOrBaud = SettingsManager.Current.PuTTY_TelnetPort; - break; - case ConnectionMode.Rlogin: - portOrBaud = SettingsManager.Current.PuTTY_RloginPort; - break; - case ConnectionMode.RAW: - portOrBaud = SettingsManager.Current.PuTTY_DefaultRaw; - break; - case ConnectionMode.Serial: - portOrBaud = SettingsManager.Current.PuTTY_BaudRate; - break; - } + public static int GetPortOrBaudByConnectionMode(ConnectionMode mode) + { + var portOrBaud = 0; - return portOrBaud; + switch (mode) + { + case ConnectionMode.SSH: + portOrBaud = SettingsManager.Current.PuTTY_SSHPort; + break; + case ConnectionMode.Telnet: + portOrBaud = SettingsManager.Current.PuTTY_TelnetPort; + break; + case ConnectionMode.Rlogin: + portOrBaud = SettingsManager.Current.PuTTY_RloginPort; + break; + case ConnectionMode.RAW: + portOrBaud = SettingsManager.Current.PuTTY_DefaultRaw; + break; + case ConnectionMode.Serial: + portOrBaud = SettingsManager.Current.PuTTY_BaudRate; + break; } + + return portOrBaud; } } diff --git a/Source/NETworkManager.Settings/AssemblyInfo.cs b/Source/NETworkManager.Settings/AssemblyInfo.cs index 704bef9cb4..4b5b12cdd1 100644 --- a/Source/NETworkManager.Settings/AssemblyInfo.cs +++ b/Source/NETworkManager.Settings/AssemblyInfo.cs @@ -1,17 +1,16 @@ using System; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public class AssemblyInfo { - public class AssemblyInfo - { - public string Title { get; set; } - public Version Version { get; set; } - public string Location { get; set; } - public string Name { get; set; } + public string Title { get; set; } + public Version Version { get; set; } + public string Location { get; set; } + public string Name { get; set; } - public AssemblyInfo() - { + public AssemblyInfo() + { - } } } \ No newline at end of file diff --git a/Source/NETworkManager.Settings/AssemblyManager.cs b/Source/NETworkManager.Settings/AssemblyManager.cs index c73333c435..2d2552f6fe 100644 --- a/Source/NETworkManager.Settings/AssemblyManager.cs +++ b/Source/NETworkManager.Settings/AssemblyManager.cs @@ -1,24 +1,23 @@ using System.Reflection; using System.IO; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public static class AssemblyManager { - public static class AssemblyManager - { - public static AssemblyInfo Current { get; set; } + public static AssemblyInfo Current { get; set; } - static AssemblyManager() - { - var assembly = Assembly.GetEntryAssembly(); + static AssemblyManager() + { + var assembly = Assembly.GetEntryAssembly(); - var name = assembly.GetName(); + var name = assembly.GetName(); - Current = new AssemblyInfo - { - Version = name.Version, - Location = Path.GetDirectoryName(assembly.Location), - Name = name.Name - }; - } + Current = new AssemblyInfo + { + Version = name.Version, + Location = Path.GetDirectoryName(assembly.Location), + Name = name.Name + }; } } diff --git a/Source/NETworkManager.Settings/AutostartManager.cs b/Source/NETworkManager.Settings/AutostartManager.cs index ec7186dd04..898d4d570a 100644 --- a/Source/NETworkManager.Settings/AutostartManager.cs +++ b/Source/NETworkManager.Settings/AutostartManager.cs @@ -1,55 +1,54 @@ using Microsoft.Win32; using System.Threading.Tasks; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public class AutostartManager { - public class AutostartManager - { - // Key where the autorun entries for the current user are stored - private const string RunKeyCurrentUser = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; + // Key where the autorun entries for the current user are stored + private const string RunKeyCurrentUser = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; - public static bool IsEnabled + public static bool IsEnabled + { + get { - get - { - var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser); + var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser); - return registryKey?.GetValue(ConfigurationManager.Current.ApplicationName) != null; - } + return registryKey?.GetValue(ConfigurationManager.Current.ApplicationName) != null; } + } - public static Task EnableAsync() - { - return Task.Run(() => Enable()); - } + public static Task EnableAsync() + { + return Task.Run(() => Enable()); + } - public static void Enable() - { - var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser, true); + public static void Enable() + { + var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser, true); - var command = $"{ConfigurationManager.Current.ApplicationFullName} {CommandLineManager.ParameterAutostart}"; + var command = $"{ConfigurationManager.Current.ApplicationFullName} {CommandLineManager.ParameterAutostart}"; - if (registryKey == null) - return; // LOG + if (registryKey == null) + return; // LOG - registryKey.SetValue(ConfigurationManager.Current.ApplicationName, command); - registryKey.Close(); - } + registryKey.SetValue(ConfigurationManager.Current.ApplicationName, command); + registryKey.Close(); + } - public static Task DisableAsync() - { - return Task.Run(() => Disable()); - } + public static Task DisableAsync() + { + return Task.Run(() => Disable()); + } - public static void Disable() - { - var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser, true); + public static void Disable() + { + var registryKey = Registry.CurrentUser.OpenSubKey(RunKeyCurrentUser, true); - if (registryKey == null) - return; // LOG + if (registryKey == null) + return; // LOG - registryKey.DeleteValue(ConfigurationManager.Current.ApplicationName); - registryKey.Close(); - } + registryKey.DeleteValue(ConfigurationManager.Current.ApplicationName); + registryKey.Close(); } } diff --git a/Source/NETworkManager.Settings/BaseColorInfo.cs b/Source/NETworkManager.Settings/BaseColorInfo.cs index 9ebe48f2e3..d2b7ecd2bf 100644 --- a/Source/NETworkManager.Settings/BaseColorInfo.cs +++ b/Source/NETworkManager.Settings/BaseColorInfo.cs @@ -1,13 +1,12 @@ using System.Windows.Media; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +/// +/// Base class for MahApps.Metro theme/accent informations. +/// +public abstract class BaseColorInfo { - /// - /// Base class for MahApps.Metro theme/accent informations. - /// - public abstract class BaseColorInfo - { - public string Name { get; set; } - public Brush Color { get; set; } - } + public string Name { get; set; } + public Brush Color { get; set; } } diff --git a/Source/NETworkManager.Settings/CommandLineInfo.cs b/Source/NETworkManager.Settings/CommandLineInfo.cs index 688b145aa7..89884ff78c 100644 --- a/Source/NETworkManager.Settings/CommandLineInfo.cs +++ b/Source/NETworkManager.Settings/CommandLineInfo.cs @@ -1,20 +1,19 @@ using NETworkManager.Models; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public class CommandLineInfo { - public class CommandLineInfo - { - public bool Help { get; set; } - public bool Autostart { get; set; } - public bool ResetSettings { get; set; } - public int RestartPid { get; set; } = -1; + public bool Help { get; set; } + public bool Autostart { get; set; } + public bool ResetSettings { get; set; } + public int RestartPid { get; set; } = -1; - public ApplicationName Application { get; set; } = ApplicationName.None; - public string WrongParameter { get; set; } + public ApplicationName Application { get; set; } = ApplicationName.None; + public string WrongParameter { get; set; } - public CommandLineInfo() - { + public CommandLineInfo() + { - } } } diff --git a/Source/NETworkManager.Settings/CommandLineManager.cs b/Source/NETworkManager.Settings/CommandLineManager.cs index b8dec5b39d..72e1db1468 100644 --- a/Source/NETworkManager.Settings/CommandLineManager.cs +++ b/Source/NETworkManager.Settings/CommandLineManager.cs @@ -1,72 +1,66 @@ using NETworkManager.Models; using System; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public static class CommandLineManager { - public static class CommandLineManager - { - public const string ParameterIdentifier = "--"; - public const char ValueSplitIdentifier = ':'; + public const string ParameterIdentifier = "--"; + public const char ValueSplitIdentifier = ':'; - // Public - public static string ParameterHelp => $"{ParameterIdentifier}help"; - public static string ParameterResetSettings => $"{ParameterIdentifier}reset-settings"; - public static string ParameterApplication => $"{ParameterIdentifier}application"; + // Public + public static string ParameterHelp => $"{ParameterIdentifier}help"; + public static string ParameterResetSettings => $"{ParameterIdentifier}reset-settings"; + public static string ParameterApplication => $"{ParameterIdentifier}application"; - // Internal use only - public static string ParameterAutostart => $"{ParameterIdentifier}autostart"; - public static string ParameterRestartPid => $"{ParameterIdentifier}restart-pid"; + // Internal use only + public static string ParameterAutostart => $"{ParameterIdentifier}autostart"; + public static string ParameterRestartPid => $"{ParameterIdentifier}restart-pid"; - public static CommandLineInfo Current { get; set; } - - static CommandLineManager() - { - Current = new CommandLineInfo(); + public static CommandLineInfo Current { get; set; } + + static CommandLineManager() + { + Current = new CommandLineInfo(); - // Detect start parameters - var parameters = Environment.GetCommandLineArgs(); + // Detect start parameters + var parameters = Environment.GetCommandLineArgs(); - for (var i = 1; i < parameters.Length; i++) - { - var param = parameters[i].Split(ValueSplitIdentifier); + for (var i = 1; i < parameters.Length; i++) + { + var param = parameters[i].Split(ValueSplitIdentifier); - if (param[0].StartsWith(ParameterIdentifier)) + if (param[0].StartsWith(ParameterIdentifier)) + { + if (param[0].Equals(ParameterHelp, StringComparison.InvariantCultureIgnoreCase)) { - if (param[0].Equals(ParameterHelp, StringComparison.InvariantCultureIgnoreCase)) - { - Current.Help = true; - }// Autostart - else if (param[0].Equals(ParameterAutostart, StringComparison.InvariantCultureIgnoreCase)) - { - Current.Autostart = true; - } // Reset Settings - else if (param[0].Equals(ParameterResetSettings, StringComparison.InvariantCultureIgnoreCase)) + Current.Help = true; + }// Autostart + else if (param[0].Equals(ParameterAutostart, StringComparison.InvariantCultureIgnoreCase)) + { + Current.Autostart = true; + } // Reset Settings + else if (param[0].Equals(ParameterResetSettings, StringComparison.InvariantCultureIgnoreCase)) + { + Current.ResetSettings = true; + } // Restart + else if (param[0].Equals(ParameterRestartPid, StringComparison.InvariantCultureIgnoreCase)) + { + if (int.TryParse(param[1], out int restartPid)) { - Current.ResetSettings = true; - } // Restart - else if (param[0].Equals(ParameterRestartPid, StringComparison.InvariantCultureIgnoreCase)) + Current.RestartPid = restartPid; + } + else { - if (int.TryParse(param[1], out int restartPid)) - { - Current.RestartPid = restartPid; - } - else - { - WrongParameterDetected(parameters); - return; - } - } // Application - else if (param[0].Equals(ParameterApplication, StringComparison.InvariantCultureIgnoreCase)) + WrongParameterDetected(parameters); + return; + } + } // Application + else if (param[0].Equals(ParameterApplication, StringComparison.InvariantCultureIgnoreCase)) + { + if (System.Enum.TryParse(param[1], out ApplicationName application)) { - if (System.Enum.TryParse(param[1], out ApplicationName application)) - { - Current.Application = application; - } - else - { - WrongParameterDetected(parameters); - return; - } + Current.Application = application; } else { @@ -76,25 +70,30 @@ static CommandLineManager() } else { - // Ignore the first parameter because it's the path of the .exe - if (i == 0) - continue; - WrongParameterDetected(parameters); return; } } - } + else + { + // Ignore the first parameter because it's the path of the .exe + if (i == 0) + continue; - public static string GetParameterWithSplitIdentifier(string parameter) - { - return $"{parameter}{ValueSplitIdentifier}"; + WrongParameterDetected(parameters); + return; + } } + } - private static void WrongParameterDetected(string[] parameters) - { - Current.WrongParameter = string.Join(" ", parameters); - Current.Help = true; - } + public static string GetParameterWithSplitIdentifier(string parameter) + { + return $"{parameter}{ValueSplitIdentifier}"; + } + + private static void WrongParameterDetected(string[] parameters) + { + Current.WrongParameter = string.Join(" ", parameters); + Current.Help = true; } } diff --git a/Source/NETworkManager.Settings/ConfigurationInfo.cs b/Source/NETworkManager.Settings/ConfigurationInfo.cs index 00c18499b4..b3a8501bf8 100644 --- a/Source/NETworkManager.Settings/ConfigurationInfo.cs +++ b/Source/NETworkManager.Settings/ConfigurationInfo.cs @@ -2,46 +2,45 @@ using System.ComponentModel; using System.Runtime.CompilerServices; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public class ConfigurationInfo : INotifyPropertyChanged { - public class ConfigurationInfo : INotifyPropertyChanged - { - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } - public bool IsAdmin { get; set; } - public string ExecutionPath { get; set; } - public string ApplicationFullName { get; set; } - public string ApplicationName { get; set; } - public bool IsPortable { get; set; } - public Version OSVersion { get; set; } + public bool IsAdmin { get; set; } + public string ExecutionPath { get; set; } + public string ApplicationFullName { get; set; } + public string ApplicationName { get; set; } + public bool IsPortable { get; set; } + public Version OSVersion { get; set; } - // Everything below will be set dynamically in the application - public bool ShowSettingsResetNoteOnStartup { get; set; } - public bool DisableSaveSettings { get; set; } - public bool Restart { get; set; } + // Everything below will be set dynamically in the application + public bool ShowSettingsResetNoteOnStartup { get; set; } + public bool DisableSaveSettings { get; set; } + public bool Restart { get; set; } - private bool _isDialogOpen; - public bool IsDialogOpen + private bool _isDialogOpen; + public bool IsDialogOpen + { + get => _isDialogOpen; + set { - get => _isDialogOpen; - set - { - if (value == _isDialogOpen) - return; - - _isDialogOpen = value; - OnPropertyChanged(); - } + if (value == _isDialogOpen) + return; + + _isDialogOpen = value; + OnPropertyChanged(); } + } - public ConfigurationInfo() - { + public ConfigurationInfo() + { - } } } diff --git a/Source/NETworkManager.Settings/ConfigurationManager.cs b/Source/NETworkManager.Settings/ConfigurationManager.cs index a1a8ece66e..9f528f21da 100644 --- a/Source/NETworkManager.Settings/ConfigurationManager.cs +++ b/Source/NETworkManager.Settings/ConfigurationManager.cs @@ -1,26 +1,25 @@ using System.Security.Principal; using System.IO; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public static class ConfigurationManager { - public static class ConfigurationManager - { - private const string IsPortableFileName = "IsPortable"; - private const string IsPortableExtension = "settings"; + private const string IsPortableFileName = "IsPortable"; + private const string IsPortableExtension = "settings"; - public static ConfigurationInfo Current { get; set; } + public static ConfigurationInfo Current { get; set; } - static ConfigurationManager() + static ConfigurationManager() + { + Current = new ConfigurationInfo { - Current = new ConfigurationInfo - { - IsAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator), - ExecutionPath = AssemblyManager.Current.Location, - ApplicationFullName = Path.Combine(AssemblyManager.Current.Location, AssemblyManager.Current.Name + ".exe"), - ApplicationName = AssemblyManager.Current.Name, - OSVersion = System.Environment.OSVersion.Version, - IsPortable = File.Exists(Path.Combine(AssemblyManager.Current.Location, $"{IsPortableFileName}.{IsPortableExtension}")) - }; - } + IsAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator), + ExecutionPath = AssemblyManager.Current.Location, + ApplicationFullName = Path.Combine(AssemblyManager.Current.Location, AssemblyManager.Current.Name + ".exe"), + ApplicationName = AssemblyManager.Current.Name, + OSVersion = System.Environment.OSVersion.Version, + IsPortable = File.Exists(Path.Combine(AssemblyManager.Current.Location, $"{IsPortableFileName}.{IsPortableExtension}")) + }; } } diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index 4afca3715e..d86a9ab90c 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -11,186 +11,185 @@ using DnsClient; using NETworkManager.Models; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public static class GlobalStaticConfiguration { - public static class GlobalStaticConfiguration - { - // Type to search (average type speed --> 187 chars/min) - public static TimeSpan SearchDispatcherTimerTimeSpan => new(0, 0, 0, 0, 750); - public static TimeSpan CredentialsUILockTime => new(0, 0, 120); - - // Filter - public static string ApplicationFileExtensionFilter => "Application (*.exe)|*.exe"; - public static string PuTTYPrivateKeyFileExtensionFilter => "PuTTY Private Key Files (*.ppk)|*.ppk"; - public static string ZipFileExtensionFilter => "ZIP Archive (*.zip)|*.zip"; - public static string XmlFileExtensionFilter => "XML-File (*.xml)|*.xml"; - - // Settings - public static ApplicationName General_DefaultApplicationViewName => ApplicationName.Dashboard; - public static int General_BackgroundJobInterval => 5; - public static int General_HistoryListEntries => 10; - public static bool SplashScreen_Enabled => true; - public static string Appearance_Theme => "Dark"; - public static string Appearance_Accent => "Lime"; - public static bool Appearance_UseCustomTheme => false; - - public static bool Network_ResolveHostnamePreferIPv4 => true; - public static bool Status_ShowWindowOnNetworkChange => true; - public static int Status_WindowCloseTime => 10; - public static string Status_IPAddressToDetectLocalIPAddressBasedOnRouting => "1.1.1.1"; - - // Fixes - public static double FloatPointFix => 1.0; - - // HotKey - public static int HotKey_ShowWindowKey => 79; - public static int HotKey_ShowWindowModifier => 3; - - // Profile - public static double Profile_WidthCollapsed => 40; - public static double Profile_DefaultWidthExpanded => 250; - public static double Profile_MaxWidthExpanded => 350; - public static int Profile_EncryptionKeySize => 256; - public static int Profile_EncryptionIterations => 1000000; - - // Application: Dashboard - public static string Dashboard_PublicIPv4Address => "1.1.1.1"; - public static string Dashboard_PublicIPv6Address => "2606:4700:4700::1111"; - public static bool Dashboard_CheckPublicIPAddress => true; - public static string Dashboard_PublicIPv4AddressAPI => "https://api.ipify.org"; - public static string Dashboard_PublicIPv6AddressAPI => "https://api6.ipify.org"; - - // Application: WiFi - public static bool WiFi_Show2dot4GHzNetworks => true; - public static bool WiFi_Show5GHzNetworks => true; - public static AutoRefreshTimeInfo WiFi_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); - public static ExportManager.ExportFileType WiFi_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: IP Scanner - public static int IPScanner_Threads => 256; - public static int IPScanner_ICMPAttempts => 2; - public static int IPScanner_ICMPBuffer => 32; - public static bool IPScanner_DNSShowErrorMessage => false; - public static int IPScanner_ICMPTimeout => 4000; - public static ExportManager.ExportFileType IPScanner_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: Port Scanner - public static int PortScanner_HostThreads => 5; - public static int PortScanner_PortThreads => 100; - public static int PortScanner_Timeout => 4000; - public static ExportManager.ExportFileType PortScanner_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: Ping Monitor - public static int PingMonitor_Buffer => 32; - public static int PingMonitor_Timeout => 4000; - public static int PingMonitor_TTL => 64; - public static int PingMonitor_WaitTime => 1000; - public static ExportManager.ExportFileType PingMonitor_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: Traceroute - public static int Traceroute_MaximumHops => 30; - public static int Traceroute_Timeout => 4000; - public static int Traceroute_Buffer => 32; - public static ExportManager.ExportFileType Traceroute_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: DNS Lookup - public static QueryClass DNSLookup_QueryClass => QueryClass.IN; - public static QueryType DNSLookup_QueryType => QueryType.ANY; - public static bool DNSLookup_UseTCPOnly => false; - public static int DNSLookup_Retries => 3; - public static int DNSLookup_Timeout => 2; - public static ExportManager.ExportFileType DNSLookup_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: RemoteDesktop - public static bool RemoteDesktop_UseCurrentViewSize => true; - public static int RemoteDesktop_ScreenWidth => 1280; - public static int RemoteDesktop_ScreenHeight => 768; - - public static int RemoteDesktop_ColorDepth = 32; - public static int RemoteDesktop_Port => 3389; - public static AudioRedirectionMode RemoteDesktop_AudioRedirectionMode => AudioRedirectionMode.PlayOnThisComputer; - public static AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode => AudioCaptureRedirectionMode.DoNotRecord; - public static KeyboardHookMode RemoteDesktop_KeyboardHookMode => KeyboardHookMode.OnTheRemoteComputer; - public static uint RemoteDesktop_AuthenticationLevel => 2; - - public static NetworkConnectionType RemoteDesktop_NetworkConnectionType => NetworkConnectionType.DetectAutomatically; - - // Application: PowerShell - public static string PowerShell_Command => "Set-Location ~"; - public static PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy => PowerShell.ExecutionPolicy.RemoteSigned; - - // Application: PuTTY - public static ConnectionMode PuTTY_DefaultConnectionMode => ConnectionMode.SSH; - public static string PuTTY_DefaultProfile => "NETworkManager"; - public static LogMode PuTTY_LogMode => LogMode.SessionLog; - public static string PuTTY_LogPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyManager.Current.Name, "PuTTY_Log"); - public static string PuTTY_LogFileName => "&H_&Y-&M-&D_&T.log"; - public static int PuTTY_SSHPort => 22; - public static string PuTTY_SerialLine => "COM1"; - public static int PuTTY_TelnetPort => 23; - public static int PuTTY_RloginPort => 513; - public static int PuTTY_BaudRate => 9600; - public static int PuTTY_Raw => 0; - - // Application: AWSSessionManager - public static bool AWSSessionManager_EnableSyncInstanceIDsFromAWS => false; - public static bool AWSSessionManager_SyncOnlyRunningInstancesFromAWS => true; - - // Application: TigerVNC - public static int TigerVNC_DefaultVNCPort => 5900; - - // WebConsole - public static string WebConsole_Cache => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyManager.Current.Name, "WebConsole_Cache"); - - // Application: SNMP - public static WalkMode SNMP_WalkMode => WalkMode.WithinSubtree; - public static int SNMP_Timeout => 60000; - public static SNMPMode SNMP_Mode => SNMPMode.Walk; - public static SNMPVersion SNMP_Version => SNMPVersion.V2C; - public static SNMPV3Security SNMP_Security => SNMPV3Security.AuthPriv; - public static SNMPV3AuthenticationProvider SNMP_AuthenticationProvider => SNMPV3AuthenticationProvider.SHA1; - public static SNMPV3PrivacyProvider SNMP_PrivacyProvider => SNMPV3PrivacyProvider.AES; - public static ExportManager.ExportFileType SNMP_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: SNTP Lookup - public static int SNTPLookup_Timeout => 4000; - public static ExportManager.ExportFileType SNTPLookup_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: Discovery Protocol - public static DiscoveryProtocol.Protocol DiscoveryProtocol_Protocol => DiscoveryProtocol.Protocol.LLDP_CDP; - public static int DiscoveryProtocol_Duration => 60; - - // Application: Wake on LAN - public static int WakeOnLAN_Port => 7; - - // Application: HTTP Header - public static int HTTPHeaders_Timeout => 10000; - public static ExportManager.ExportFileType HTTPHeaders_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: Subnet Calculator - public static ExportManager.ExportFileType SubnetCalculator_Subnetting_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: Bit Calculator - public static BitCaluclatorUnit BitCalculator_Unit => BitCaluclatorUnit.Bytes; - public static BitCaluclatorNotation BitCalculator_Notation => BitCaluclatorNotation.Binary; - - // Application: Lookup - public static ExportManager.ExportFileType Lookup_OUI_ExportFileType => ExportManager.ExportFileType.CSV; - public static ExportManager.ExportFileType Lookup_Port_ExportFileType => ExportManager.ExportFileType.CSV; - - // Application: Whois - public static ExportManager.ExportFileType Whois_ExportFileType => ExportManager.ExportFileType.TXT; - - // Application: Connections - public static ExportManager.ExportFileType Connections_ExportFileType => ExportManager.ExportFileType.CSV; - public static AutoRefreshTimeInfo Connections_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); - - // Application: Listeners - public static ExportManager.ExportFileType Listeners_ExportFileType => ExportManager.ExportFileType.CSV; - public static AutoRefreshTimeInfo Listeners_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); - - // Application: ARP Table - public static ExportManager.ExportFileType ARPTable_ExportFileType => ExportManager.ExportFileType.CSV; - public static AutoRefreshTimeInfo ARPTable_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); - } + // Type to search (average type speed --> 187 chars/min) + public static TimeSpan SearchDispatcherTimerTimeSpan => new(0, 0, 0, 0, 750); + public static TimeSpan CredentialsUILockTime => new(0, 0, 120); + + // Filter + public static string ApplicationFileExtensionFilter => "Application (*.exe)|*.exe"; + public static string PuTTYPrivateKeyFileExtensionFilter => "PuTTY Private Key Files (*.ppk)|*.ppk"; + public static string ZipFileExtensionFilter => "ZIP Archive (*.zip)|*.zip"; + public static string XmlFileExtensionFilter => "XML-File (*.xml)|*.xml"; + + // Settings + public static ApplicationName General_DefaultApplicationViewName => ApplicationName.Dashboard; + public static int General_BackgroundJobInterval => 5; + public static int General_HistoryListEntries => 10; + public static bool SplashScreen_Enabled => true; + public static string Appearance_Theme => "Dark"; + public static string Appearance_Accent => "Lime"; + public static bool Appearance_UseCustomTheme => false; + + public static bool Network_ResolveHostnamePreferIPv4 => true; + public static bool Status_ShowWindowOnNetworkChange => true; + public static int Status_WindowCloseTime => 10; + public static string Status_IPAddressToDetectLocalIPAddressBasedOnRouting => "1.1.1.1"; + + // Fixes + public static double FloatPointFix => 1.0; + + // HotKey + public static int HotKey_ShowWindowKey => 79; + public static int HotKey_ShowWindowModifier => 3; + + // Profile + public static double Profile_WidthCollapsed => 40; + public static double Profile_DefaultWidthExpanded => 250; + public static double Profile_MaxWidthExpanded => 350; + public static int Profile_EncryptionKeySize => 256; + public static int Profile_EncryptionIterations => 1000000; + + // Application: Dashboard + public static string Dashboard_PublicIPv4Address => "1.1.1.1"; + public static string Dashboard_PublicIPv6Address => "2606:4700:4700::1111"; + public static bool Dashboard_CheckPublicIPAddress => true; + public static string Dashboard_PublicIPv4AddressAPI => "https://api.ipify.org"; + public static string Dashboard_PublicIPv6AddressAPI => "https://api6.ipify.org"; + + // Application: WiFi + public static bool WiFi_Show2dot4GHzNetworks => true; + public static bool WiFi_Show5GHzNetworks => true; + public static AutoRefreshTimeInfo WiFi_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); + public static ExportManager.ExportFileType WiFi_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: IP Scanner + public static int IPScanner_Threads => 256; + public static int IPScanner_ICMPAttempts => 2; + public static int IPScanner_ICMPBuffer => 32; + public static bool IPScanner_DNSShowErrorMessage => false; + public static int IPScanner_ICMPTimeout => 4000; + public static ExportManager.ExportFileType IPScanner_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: Port Scanner + public static int PortScanner_HostThreads => 5; + public static int PortScanner_PortThreads => 100; + public static int PortScanner_Timeout => 4000; + public static ExportManager.ExportFileType PortScanner_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: Ping Monitor + public static int PingMonitor_Buffer => 32; + public static int PingMonitor_Timeout => 4000; + public static int PingMonitor_TTL => 64; + public static int PingMonitor_WaitTime => 1000; + public static ExportManager.ExportFileType PingMonitor_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: Traceroute + public static int Traceroute_MaximumHops => 30; + public static int Traceroute_Timeout => 4000; + public static int Traceroute_Buffer => 32; + public static ExportManager.ExportFileType Traceroute_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: DNS Lookup + public static QueryClass DNSLookup_QueryClass => QueryClass.IN; + public static QueryType DNSLookup_QueryType => QueryType.ANY; + public static bool DNSLookup_UseTCPOnly => false; + public static int DNSLookup_Retries => 3; + public static int DNSLookup_Timeout => 2; + public static ExportManager.ExportFileType DNSLookup_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: RemoteDesktop + public static bool RemoteDesktop_UseCurrentViewSize => true; + public static int RemoteDesktop_ScreenWidth => 1280; + public static int RemoteDesktop_ScreenHeight => 768; + + public static int RemoteDesktop_ColorDepth = 32; + public static int RemoteDesktop_Port => 3389; + public static AudioRedirectionMode RemoteDesktop_AudioRedirectionMode => AudioRedirectionMode.PlayOnThisComputer; + public static AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode => AudioCaptureRedirectionMode.DoNotRecord; + public static KeyboardHookMode RemoteDesktop_KeyboardHookMode => KeyboardHookMode.OnTheRemoteComputer; + public static uint RemoteDesktop_AuthenticationLevel => 2; + + public static NetworkConnectionType RemoteDesktop_NetworkConnectionType => NetworkConnectionType.DetectAutomatically; + + // Application: PowerShell + public static string PowerShell_Command => "Set-Location ~"; + public static PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy => PowerShell.ExecutionPolicy.RemoteSigned; + + // Application: PuTTY + public static ConnectionMode PuTTY_DefaultConnectionMode => ConnectionMode.SSH; + public static string PuTTY_DefaultProfile => "NETworkManager"; + public static LogMode PuTTY_LogMode => LogMode.SessionLog; + public static string PuTTY_LogPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyManager.Current.Name, "PuTTY_Log"); + public static string PuTTY_LogFileName => "&H_&Y-&M-&D_&T.log"; + public static int PuTTY_SSHPort => 22; + public static string PuTTY_SerialLine => "COM1"; + public static int PuTTY_TelnetPort => 23; + public static int PuTTY_RloginPort => 513; + public static int PuTTY_BaudRate => 9600; + public static int PuTTY_Raw => 0; + + // Application: AWSSessionManager + public static bool AWSSessionManager_EnableSyncInstanceIDsFromAWS => false; + public static bool AWSSessionManager_SyncOnlyRunningInstancesFromAWS => true; + + // Application: TigerVNC + public static int TigerVNC_DefaultVNCPort => 5900; + + // WebConsole + public static string WebConsole_Cache => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyManager.Current.Name, "WebConsole_Cache"); + + // Application: SNMP + public static WalkMode SNMP_WalkMode => WalkMode.WithinSubtree; + public static int SNMP_Timeout => 60000; + public static SNMPMode SNMP_Mode => SNMPMode.Walk; + public static SNMPVersion SNMP_Version => SNMPVersion.V2C; + public static SNMPV3Security SNMP_Security => SNMPV3Security.AuthPriv; + public static SNMPV3AuthenticationProvider SNMP_AuthenticationProvider => SNMPV3AuthenticationProvider.SHA1; + public static SNMPV3PrivacyProvider SNMP_PrivacyProvider => SNMPV3PrivacyProvider.AES; + public static ExportManager.ExportFileType SNMP_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: SNTP Lookup + public static int SNTPLookup_Timeout => 4000; + public static ExportManager.ExportFileType SNTPLookup_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: Discovery Protocol + public static DiscoveryProtocol.Protocol DiscoveryProtocol_Protocol => DiscoveryProtocol.Protocol.LLDP_CDP; + public static int DiscoveryProtocol_Duration => 60; + + // Application: Wake on LAN + public static int WakeOnLAN_Port => 7; + + // Application: HTTP Header + public static int HTTPHeaders_Timeout => 10000; + public static ExportManager.ExportFileType HTTPHeaders_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: Subnet Calculator + public static ExportManager.ExportFileType SubnetCalculator_Subnetting_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: Bit Calculator + public static BitCaluclatorUnit BitCalculator_Unit => BitCaluclatorUnit.Bytes; + public static BitCaluclatorNotation BitCalculator_Notation => BitCaluclatorNotation.Binary; + + // Application: Lookup + public static ExportManager.ExportFileType Lookup_OUI_ExportFileType => ExportManager.ExportFileType.CSV; + public static ExportManager.ExportFileType Lookup_Port_ExportFileType => ExportManager.ExportFileType.CSV; + + // Application: Whois + public static ExportManager.ExportFileType Whois_ExportFileType => ExportManager.ExportFileType.TXT; + + // Application: Connections + public static ExportManager.ExportFileType Connections_ExportFileType => ExportManager.ExportFileType.CSV; + public static AutoRefreshTimeInfo Connections_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); + + // Application: Listeners + public static ExportManager.ExportFileType Listeners_ExportFileType => ExportManager.ExportFileType.CSV; + public static AutoRefreshTimeInfo Listeners_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); + + // Application: ARP Table + public static ExportManager.ExportFileType ARPTable_ExportFileType => ExportManager.ExportFileType.CSV; + public static AutoRefreshTimeInfo ARPTable_AutoRefreshTime => AutoRefreshTime.GetDefaults.First(x => x.Value == 30 && x.TimeUnit == TimeUnit.Second); } \ No newline at end of file diff --git a/Source/NETworkManager.Settings/SettingsFileInfo.cs b/Source/NETworkManager.Settings/SettingsFileInfo.cs deleted file mode 100644 index 3dd52840af..0000000000 --- a/Source/NETworkManager.Settings/SettingsFileInfo.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace NETworkManager.Settings -{ - public class SettingsFileInfo - { - public bool Export { get; set; } - public string FileName { get; set; } - public string FilePath { get; set; } - - public SettingsFileInfo() - { - - } - - public SettingsFileInfo(bool export, string fileName, string filePath) - { - Export = export; - FileName = fileName; - FilePath = filePath; - } - } -} diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index 2a51daa676..d36e9f1f51 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -15,4027 +15,4026 @@ using NETworkManager.Models.RemoteDesktop; using NETworkManager.Utilities; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public class SettingsInfo : INotifyPropertyChanged { - public class SettingsInfo : INotifyPropertyChanged - { - #region Events - public event PropertyChangedEventHandler PropertyChanged; + #region Events + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - [XmlIgnore] public bool SettingsChanged { get; set; } + #region Variables + [XmlIgnore] public bool SettingsChanged { get; set; } - private bool _firstRun = true; - public bool FirstRun + private bool _firstRun = true; + public bool FirstRun + { + get => _firstRun; + set { - get => _firstRun; - set - { - if (value == _firstRun) - return; + if (value == _firstRun) + return; - _firstRun = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _firstRun = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _version { get; set; } + private string _version { get; set; } - public string Version + public string Version + { + get => _version; + set { - get => _version; - set - { - if (value == _version) - return; + if (value == _version) + return; - _version = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _version = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - #region General - // General - private ApplicationName _general_DefaultApplicationViewName = GlobalStaticConfiguration.General_DefaultApplicationViewName; - public ApplicationName General_DefaultApplicationViewName + #region General + // General + private ApplicationName _general_DefaultApplicationViewName = GlobalStaticConfiguration.General_DefaultApplicationViewName; + public ApplicationName General_DefaultApplicationViewName + { + get => _general_DefaultApplicationViewName; + set { - get => _general_DefaultApplicationViewName; - set - { - if (value == _general_DefaultApplicationViewName) - return; + if (value == _general_DefaultApplicationViewName) + return; - _general_DefaultApplicationViewName = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _general_DefaultApplicationViewName = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _general_BackgroundJobInterval = GlobalStaticConfiguration.General_BackgroundJobInterval; - public int General_BackgroundJobInterval + private int _general_BackgroundJobInterval = GlobalStaticConfiguration.General_BackgroundJobInterval; + public int General_BackgroundJobInterval + { + get => _general_BackgroundJobInterval; + set { - get => _general_BackgroundJobInterval; - set - { - if (value == _general_BackgroundJobInterval) - return; + if (value == _general_BackgroundJobInterval) + return; - _general_BackgroundJobInterval = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _general_BackgroundJobInterval = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _general_HistoryListEntries = GlobalStaticConfiguration.General_HistoryListEntries; - public int General_HistoryListEntries + private int _general_HistoryListEntries = GlobalStaticConfiguration.General_HistoryListEntries; + public int General_HistoryListEntries + { + get => _general_HistoryListEntries; + set { - get => _general_HistoryListEntries; - set - { - if (value == _general_HistoryListEntries) - return; + if (value == _general_HistoryListEntries) + return; - _general_HistoryListEntries = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _general_HistoryListEntries = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableSetCollection _general_ApplicationList = new(); - public ObservableSetCollection General_ApplicationList + private ObservableSetCollection _general_ApplicationList = new(); + public ObservableSetCollection General_ApplicationList + { + get => _general_ApplicationList; + set { - get => _general_ApplicationList; - set - { - if (value == _general_ApplicationList) - return; + if (value == _general_ApplicationList) + return; - _general_ApplicationList = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _general_ApplicationList = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Window - private bool _window_ConfirmClose; - public bool Window_ConfirmClose + // Window + private bool _window_ConfirmClose; + public bool Window_ConfirmClose + { + get => _window_ConfirmClose; + set { - get => _window_ConfirmClose; - set - { - if (value == _window_ConfirmClose) - return; + if (value == _window_ConfirmClose) + return; - _window_ConfirmClose = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _window_ConfirmClose = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _window_MinimizeInsteadOfTerminating; - public bool Window_MinimizeInsteadOfTerminating + private bool _window_MinimizeInsteadOfTerminating; + public bool Window_MinimizeInsteadOfTerminating + { + get => _window_MinimizeInsteadOfTerminating; + set { - get => _window_MinimizeInsteadOfTerminating; - set - { - if (value == _window_MinimizeInsteadOfTerminating) - return; + if (value == _window_MinimizeInsteadOfTerminating) + return; - _window_MinimizeInsteadOfTerminating = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _window_MinimizeInsteadOfTerminating = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _window_MultipleInstances; - public bool Window_MultipleInstances + private bool _window_MultipleInstances; + public bool Window_MultipleInstances + { + get => _window_MultipleInstances; + set { - get => _window_MultipleInstances; - set - { - if (value == _window_MultipleInstances) - return; + if (value == _window_MultipleInstances) + return; - _window_MultipleInstances = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _window_MultipleInstances = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _window_MinimizeToTrayInsteadOfTaskbar; - public bool Window_MinimizeToTrayInsteadOfTaskbar + private bool _window_MinimizeToTrayInsteadOfTaskbar; + public bool Window_MinimizeToTrayInsteadOfTaskbar + { + get => _window_MinimizeToTrayInsteadOfTaskbar; + set { - get => _window_MinimizeToTrayInsteadOfTaskbar; - set - { - if (value == _window_MinimizeToTrayInsteadOfTaskbar) - return; + if (value == _window_MinimizeToTrayInsteadOfTaskbar) + return; - _window_MinimizeToTrayInsteadOfTaskbar = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _window_MinimizeToTrayInsteadOfTaskbar = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // TrayIcon - private bool _trayIcon_AlwaysShowIcon; - public bool TrayIcon_AlwaysShowIcon + // TrayIcon + private bool _trayIcon_AlwaysShowIcon; + public bool TrayIcon_AlwaysShowIcon + { + get => _trayIcon_AlwaysShowIcon; + set { - get => _trayIcon_AlwaysShowIcon; - set - { - if (value == _trayIcon_AlwaysShowIcon) - return; + if (value == _trayIcon_AlwaysShowIcon) + return; - _trayIcon_AlwaysShowIcon = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _trayIcon_AlwaysShowIcon = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // SplashScreen - private bool _splashScreen_Enabled = GlobalStaticConfiguration.SplashScreen_Enabled; - public bool SplashScreen_Enabled + // SplashScreen + private bool _splashScreen_Enabled = GlobalStaticConfiguration.SplashScreen_Enabled; + public bool SplashScreen_Enabled + { + get => _splashScreen_Enabled; + set { - get => _splashScreen_Enabled; - set - { - if (value == _splashScreen_Enabled) - return; + if (value == _splashScreen_Enabled) + return; - _splashScreen_Enabled = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _splashScreen_Enabled = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Appearance - private string _appearance_Theme = GlobalStaticConfiguration.Appearance_Theme; - public string Appearance_Theme + // Appearance + private string _appearance_Theme = GlobalStaticConfiguration.Appearance_Theme; + public string Appearance_Theme + { + get => _appearance_Theme; + set { - get => _appearance_Theme; - set - { - if (value == _appearance_Theme) - return; + if (value == _appearance_Theme) + return; - _appearance_Theme = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _appearance_Theme = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _appearance_Accent = GlobalStaticConfiguration.Appearance_Accent; - public string Appearance_Accent + private string _appearance_Accent = GlobalStaticConfiguration.Appearance_Accent; + public string Appearance_Accent + { + get => _appearance_Accent; + set { - get => _appearance_Accent; - set - { - if (value == _appearance_Accent) - return; + if (value == _appearance_Accent) + return; - _appearance_Accent = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _appearance_Accent = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _appearance_UseCustomTheme = GlobalStaticConfiguration.Appearance_UseCustomTheme; - public bool Appearance_UseCustomTheme + private bool _appearance_UseCustomTheme = GlobalStaticConfiguration.Appearance_UseCustomTheme; + public bool Appearance_UseCustomTheme + { + get => _appearance_UseCustomTheme; + set { - get => _appearance_UseCustomTheme; - set - { - if (value == _appearance_UseCustomTheme) - return; + if (value == _appearance_UseCustomTheme) + return; - _appearance_UseCustomTheme = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _appearance_UseCustomTheme = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _appearance_CustomThemeName; - public string Appearance_CustomThemeName + private string _appearance_CustomThemeName; + public string Appearance_CustomThemeName + { + get => _appearance_CustomThemeName; + set { - get => _appearance_CustomThemeName; - set - { - if (value == _appearance_CustomThemeName) - return; + if (value == _appearance_CustomThemeName) + return; - _appearance_CustomThemeName = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _appearance_CustomThemeName = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _appearance_PowerShellModifyGlobalProfile; - public bool Appearance_PowerShellModifyGlobalProfile + private bool _appearance_PowerShellModifyGlobalProfile; + public bool Appearance_PowerShellModifyGlobalProfile + { + get => _appearance_PowerShellModifyGlobalProfile; + set { - get => _appearance_PowerShellModifyGlobalProfile; - set - { - if (value == _appearance_PowerShellModifyGlobalProfile) - return; + if (value == _appearance_PowerShellModifyGlobalProfile) + return; - _appearance_PowerShellModifyGlobalProfile = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _appearance_PowerShellModifyGlobalProfile = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Localization - private string _localization_CultureCode; - public string Localization_CultureCode + // Localization + private string _localization_CultureCode; + public string Localization_CultureCode + { + get => _localization_CultureCode; + set { - get => _localization_CultureCode; - set - { - if (value == _localization_CultureCode) - return; + if (value == _localization_CultureCode) + return; - _localization_CultureCode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _localization_CultureCode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Network - private bool _network_UseCustomDNSServer; - public bool Network_UseCustomDNSServer + // Network + private bool _network_UseCustomDNSServer; + public bool Network_UseCustomDNSServer + { + get => _network_UseCustomDNSServer; + set { - get => _network_UseCustomDNSServer; - set - { - if (value == _network_UseCustomDNSServer) - return; + if (value == _network_UseCustomDNSServer) + return; - _network_UseCustomDNSServer = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _network_UseCustomDNSServer = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _network_CustomDNSServer; - public string Network_CustomDNSServer + private string _network_CustomDNSServer; + public string Network_CustomDNSServer + { + get => _network_CustomDNSServer; + set { - get => _network_CustomDNSServer; - set - { - if (value == _network_CustomDNSServer) - return; + if (value == _network_CustomDNSServer) + return; - _network_CustomDNSServer = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _network_CustomDNSServer = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _network_ResolveHostnamePreferIPv4 = GlobalStaticConfiguration.Network_ResolveHostnamePreferIPv4; - public bool Network_ResolveHostnamePreferIPv4 + private bool _network_ResolveHostnamePreferIPv4 = GlobalStaticConfiguration.Network_ResolveHostnamePreferIPv4; + public bool Network_ResolveHostnamePreferIPv4 + { + get => _network_ResolveHostnamePreferIPv4; + set { - get => _network_ResolveHostnamePreferIPv4; - set - { - if (value == _network_ResolveHostnamePreferIPv4) - return; + if (value == _network_ResolveHostnamePreferIPv4) + return; - _network_ResolveHostnamePreferIPv4 = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _network_ResolveHostnamePreferIPv4 = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Status - private bool _status_ShowWindowOnNetworkChange = GlobalStaticConfiguration.Status_ShowWindowOnNetworkChange; - public bool Status_ShowWindowOnNetworkChange + // Status + private bool _status_ShowWindowOnNetworkChange = GlobalStaticConfiguration.Status_ShowWindowOnNetworkChange; + public bool Status_ShowWindowOnNetworkChange + { + get => _status_ShowWindowOnNetworkChange; + set { - get => _status_ShowWindowOnNetworkChange; - set - { - if (value == _status_ShowWindowOnNetworkChange) - return; + if (value == _status_ShowWindowOnNetworkChange) + return; - _status_ShowWindowOnNetworkChange = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _status_ShowWindowOnNetworkChange = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _status_WindowCloseTime = GlobalStaticConfiguration.Status_WindowCloseTime; - public int Status_WindowCloseTime + private int _status_WindowCloseTime = GlobalStaticConfiguration.Status_WindowCloseTime; + public int Status_WindowCloseTime + { + get => _status_WindowCloseTime; + set { - get => _status_WindowCloseTime; - set - { - if (value == _status_WindowCloseTime) - return; + if (value == _status_WindowCloseTime) + return; - _status_WindowCloseTime = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _status_WindowCloseTime = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _status_IPAddressToDetectLocalIPAddressBasedOnRouting = GlobalStaticConfiguration.Status_IPAddressToDetectLocalIPAddressBasedOnRouting; - public string Status_IPAddressToDetectLocalIPAddressBasedOnRouting + private string _status_IPAddressToDetectLocalIPAddressBasedOnRouting = GlobalStaticConfiguration.Status_IPAddressToDetectLocalIPAddressBasedOnRouting; + public string Status_IPAddressToDetectLocalIPAddressBasedOnRouting + { + get => _status_IPAddressToDetectLocalIPAddressBasedOnRouting; + set { - get => _status_IPAddressToDetectLocalIPAddressBasedOnRouting; - set - { - if (value == _status_IPAddressToDetectLocalIPAddressBasedOnRouting) - return; + if (value == _status_IPAddressToDetectLocalIPAddressBasedOnRouting) + return; - _status_IPAddressToDetectLocalIPAddressBasedOnRouting = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _status_IPAddressToDetectLocalIPAddressBasedOnRouting = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Autostart - private bool _autostart_StartMinimizedInTray; - public bool Autostart_StartMinimizedInTray + // Autostart + private bool _autostart_StartMinimizedInTray; + public bool Autostart_StartMinimizedInTray + { + get => _autostart_StartMinimizedInTray; + set { - get => _autostart_StartMinimizedInTray; - set - { - if (value == _autostart_StartMinimizedInTray) - return; + if (value == _autostart_StartMinimizedInTray) + return; - _autostart_StartMinimizedInTray = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _autostart_StartMinimizedInTray = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // HotKey - private bool _hotKey_ShowWindowEnabled; - public bool HotKey_ShowWindowEnabled + // HotKey + private bool _hotKey_ShowWindowEnabled; + public bool HotKey_ShowWindowEnabled + { + get => _hotKey_ShowWindowEnabled; + set { - get => _hotKey_ShowWindowEnabled; - set - { - if (value == _hotKey_ShowWindowEnabled) - return; + if (value == _hotKey_ShowWindowEnabled) + return; - _hotKey_ShowWindowEnabled = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _hotKey_ShowWindowEnabled = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _hotKey_ShowWindowKey = GlobalStaticConfiguration.HotKey_ShowWindowKey; - public int HotKey_ShowWindowKey + private int _hotKey_ShowWindowKey = GlobalStaticConfiguration.HotKey_ShowWindowKey; + public int HotKey_ShowWindowKey + { + get => _hotKey_ShowWindowKey; + set { - get => _hotKey_ShowWindowKey; - set - { - if (value == _hotKey_ShowWindowKey) - return; + if (value == _hotKey_ShowWindowKey) + return; - _hotKey_ShowWindowKey = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _hotKey_ShowWindowKey = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _hotKey_ShowWindowModifier = GlobalStaticConfiguration.HotKey_ShowWindowModifier; - public int HotKey_ShowWindowModifier + private int _hotKey_ShowWindowModifier = GlobalStaticConfiguration.HotKey_ShowWindowModifier; + public int HotKey_ShowWindowModifier + { + get => _hotKey_ShowWindowModifier; + set { - get => _hotKey_ShowWindowModifier; - set - { - if (value == _hotKey_ShowWindowModifier) - return; + if (value == _hotKey_ShowWindowModifier) + return; - _hotKey_ShowWindowModifier = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _hotKey_ShowWindowModifier = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Update - private bool _update_CheckForUpdatesAtStartup = true; - public bool Update_CheckForUpdatesAtStartup + // Update + private bool _update_CheckForUpdatesAtStartup = true; + public bool Update_CheckForUpdatesAtStartup + { + get => _update_CheckForUpdatesAtStartup; + set { - get => _update_CheckForUpdatesAtStartup; - set - { - if (value == _update_CheckForUpdatesAtStartup) - return; + if (value == _update_CheckForUpdatesAtStartup) + return; - _update_CheckForUpdatesAtStartup = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _update_CheckForUpdatesAtStartup = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _update_CheckForPreReleases; - public bool Update_CheckForPreReleases + private bool _update_CheckForPreReleases; + public bool Update_CheckForPreReleases + { + get => _update_CheckForPreReleases; + set { - get => _update_CheckForPreReleases; - set - { - if (value == _update_CheckForPreReleases) - return; + if (value == _update_CheckForPreReleases) + return; - _update_CheckForPreReleases = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _update_CheckForPreReleases = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - // Profiles - private string _profiles_CustomProfilesLocation; - public string Profiles_CustomProfilesLocation + // Profiles + private string _profiles_CustomProfilesLocation; + public string Profiles_CustomProfilesLocation + { + get => _profiles_CustomProfilesLocation; + set { - get => _profiles_CustomProfilesLocation; - set - { - if (value == _profiles_CustomProfilesLocation) - return; + if (value == _profiles_CustomProfilesLocation) + return; - _profiles_CustomProfilesLocation = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _profiles_CustomProfilesLocation = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _profiles_LastSelected; - public string Profiles_LastSelected + private string _profiles_LastSelected; + public string Profiles_LastSelected + { + get => _profiles_LastSelected; + set { - get => _profiles_LastSelected; - set - { - if (value == _profiles_LastSelected) - return; + if (value == _profiles_LastSelected) + return; - _profiles_LastSelected = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _profiles_LastSelected = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Others - // Application view - private bool _expandApplicationView; - public bool ExpandApplicationView + #region Others + // Application view + private bool _expandApplicationView; + public bool ExpandApplicationView + { + get => _expandApplicationView; + set { - get => _expandApplicationView; - set - { - if (value == _expandApplicationView) - return; + if (value == _expandApplicationView) + return; - _expandApplicationView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _expandApplicationView = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Dashboard - private string _dashboard_PublicIPv4Address = GlobalStaticConfiguration.Dashboard_PublicIPv4Address; - public string Dashboard_PublicIPv4Address + #region Dashboard + private string _dashboard_PublicIPv4Address = GlobalStaticConfiguration.Dashboard_PublicIPv4Address; + public string Dashboard_PublicIPv4Address + { + get => _dashboard_PublicIPv4Address; + set { - get => _dashboard_PublicIPv4Address; - set - { - if (value == _dashboard_PublicIPv4Address) - return; + if (value == _dashboard_PublicIPv4Address) + return; - _dashboard_PublicIPv4Address = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dashboard_PublicIPv4Address = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _dashboard_PublicIPv6Address = GlobalStaticConfiguration.Dashboard_PublicIPv6Address; - public string Dashboard_PublicIPv6Address + private string _dashboard_PublicIPv6Address = GlobalStaticConfiguration.Dashboard_PublicIPv6Address; + public string Dashboard_PublicIPv6Address + { + get => _dashboard_PublicIPv6Address; + set { - get => _dashboard_PublicIPv6Address; - set - { - if (value == _dashboard_PublicIPv6Address) - return; + if (value == _dashboard_PublicIPv6Address) + return; - _dashboard_PublicIPv6Address = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dashboard_PublicIPv6Address = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dashboard_CheckPublicIPAddress = GlobalStaticConfiguration.Dashboard_CheckPublicIPAddress; - public bool Dashboard_CheckPublicIPAddress + private bool _dashboard_CheckPublicIPAddress = GlobalStaticConfiguration.Dashboard_CheckPublicIPAddress; + public bool Dashboard_CheckPublicIPAddress + { + get => _dashboard_CheckPublicIPAddress; + set { - get => _dashboard_CheckPublicIPAddress; - set - { - if (value == _dashboard_CheckPublicIPAddress) - return; + if (value == _dashboard_CheckPublicIPAddress) + return; - _dashboard_CheckPublicIPAddress = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dashboard_CheckPublicIPAddress = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dashboard_UseCustomPublicIPv4AddressAPI; - public bool Dashboard_UseCustomPublicIPv4AddressAPI + private bool _dashboard_UseCustomPublicIPv4AddressAPI; + public bool Dashboard_UseCustomPublicIPv4AddressAPI + { + get => _dashboard_UseCustomPublicIPv4AddressAPI; + set { - get => _dashboard_UseCustomPublicIPv4AddressAPI; - set - { - if (value == _dashboard_UseCustomPublicIPv4AddressAPI) - return; + if (value == _dashboard_UseCustomPublicIPv4AddressAPI) + return; - _dashboard_UseCustomPublicIPv4AddressAPI = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dashboard_UseCustomPublicIPv4AddressAPI = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _dashboard_CustomPublicIPv4AddressAPI; - public string Dashboard_CustomPublicIPv4AddressAPI + private string _dashboard_CustomPublicIPv4AddressAPI; + public string Dashboard_CustomPublicIPv4AddressAPI + { + get => _dashboard_CustomPublicIPv4AddressAPI; + set { - get => _dashboard_CustomPublicIPv4AddressAPI; - set - { - if (value == _dashboard_CustomPublicIPv4AddressAPI) - return; + if (value == _dashboard_CustomPublicIPv4AddressAPI) + return; - _dashboard_CustomPublicIPv4AddressAPI = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dashboard_CustomPublicIPv4AddressAPI = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dashboard_UseCustomPublicIPv6AddressAPI; - public bool Dashboard_UseCustomPublicIPv6AddressAPI + private bool _dashboard_UseCustomPublicIPv6AddressAPI; + public bool Dashboard_UseCustomPublicIPv6AddressAPI + { + get => _dashboard_UseCustomPublicIPv6AddressAPI; + set { - get => _dashboard_UseCustomPublicIPv6AddressAPI; - set - { - if (value == _dashboard_UseCustomPublicIPv6AddressAPI) - return; + if (value == _dashboard_UseCustomPublicIPv6AddressAPI) + return; - _dashboard_UseCustomPublicIPv6AddressAPI = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dashboard_UseCustomPublicIPv6AddressAPI = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _dashboard_CustomPublicIPv6AddressAPI; - public string Dashboard_CustomPublicIPv6AddressAPI + private string _dashboard_CustomPublicIPv6AddressAPI; + public string Dashboard_CustomPublicIPv6AddressAPI + { + get => _dashboard_CustomPublicIPv6AddressAPI; + set { - get => _dashboard_CustomPublicIPv6AddressAPI; - set - { - if (value == _dashboard_CustomPublicIPv6AddressAPI) - return; + if (value == _dashboard_CustomPublicIPv6AddressAPI) + return; - _dashboard_CustomPublicIPv6AddressAPI = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dashboard_CustomPublicIPv6AddressAPI = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Network Interface - private string _networkInterface_InterfaceId; - public string NetworkInterface_InterfaceId + #region Network Interface + private string _networkInterface_InterfaceId; + public string NetworkInterface_InterfaceId + { + get => _networkInterface_InterfaceId; + set { - get => _networkInterface_InterfaceId; - set - { - if (value == _networkInterface_InterfaceId) - return; + if (value == _networkInterface_InterfaceId) + return; - _networkInterface_InterfaceId = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _networkInterface_InterfaceId = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _networkInterface_ExpandProfileView = true; - public bool NetworkInterface_ExpandProfileView + private bool _networkInterface_ExpandProfileView = true; + public bool NetworkInterface_ExpandProfileView + { + get => _networkInterface_ExpandProfileView; + set { - get => _networkInterface_ExpandProfileView; - set - { - if (value == _networkInterface_ExpandProfileView) - return; + if (value == _networkInterface_ExpandProfileView) + return; - _networkInterface_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _networkInterface_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _networkInterface_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double NetworkInterface_ProfileWidth + private double _networkInterface_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double NetworkInterface_ProfileWidth + { + get => _networkInterface_ProfileWidth; + set { - get => _networkInterface_ProfileWidth; - set - { - if (Math.Abs(value - _networkInterface_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _networkInterface_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _networkInterface_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _networkInterface_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region WiFi - private string _wiFi_InterfaceId; - public string WiFi_InterfaceId + #region WiFi + private string _wiFi_InterfaceId; + public string WiFi_InterfaceId + { + get => _wiFi_InterfaceId; + set { - get => _wiFi_InterfaceId; - set - { - if (value == _wiFi_InterfaceId) - return; + if (value == _wiFi_InterfaceId) + return; - _wiFi_InterfaceId = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wiFi_InterfaceId = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _wiFi_Show2dot4GHzNetworks = GlobalStaticConfiguration.WiFi_Show2dot4GHzNetworks; - public bool WiFi_Show2dot4GHzNetworks + private bool _wiFi_Show2dot4GHzNetworks = GlobalStaticConfiguration.WiFi_Show2dot4GHzNetworks; + public bool WiFi_Show2dot4GHzNetworks + { + get => _wiFi_Show2dot4GHzNetworks; + set { - get => _wiFi_Show2dot4GHzNetworks; - set - { - if (value == _wiFi_Show2dot4GHzNetworks) - return; + if (value == _wiFi_Show2dot4GHzNetworks) + return; - _wiFi_Show2dot4GHzNetworks = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wiFi_Show2dot4GHzNetworks = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _wiFi_Show5GHzNetworks = GlobalStaticConfiguration.WiFi_Show5GHzNetworks; - public bool WiFi_Show5GHzNetworks + private bool _wiFi_Show5GHzNetworks = GlobalStaticConfiguration.WiFi_Show5GHzNetworks; + public bool WiFi_Show5GHzNetworks + { + get => _wiFi_Show5GHzNetworks; + set { - get => _wiFi_Show5GHzNetworks; - set - { - if (value == _wiFi_Show5GHzNetworks) - return; + if (value == _wiFi_Show5GHzNetworks) + return; - _wiFi_Show5GHzNetworks = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wiFi_Show5GHzNetworks = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _wiFi_AutoRefresh; - public bool WiFi_AutoRefresh + private bool _wiFi_AutoRefresh; + public bool WiFi_AutoRefresh + { + get => _wiFi_AutoRefresh; + set { - get => _wiFi_AutoRefresh; - set - { - if (value == _wiFi_AutoRefresh) - return; + if (value == _wiFi_AutoRefresh) + return; - _wiFi_AutoRefresh = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wiFi_AutoRefresh = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private AutoRefreshTimeInfo _wiFi_AutoRefreshTime = GlobalStaticConfiguration.WiFi_AutoRefreshTime; - public AutoRefreshTimeInfo WiFi_AutoRefreshTime + private AutoRefreshTimeInfo _wiFi_AutoRefreshTime = GlobalStaticConfiguration.WiFi_AutoRefreshTime; + public AutoRefreshTimeInfo WiFi_AutoRefreshTime + { + get => _wiFi_AutoRefreshTime; + set { - get => _wiFi_AutoRefreshTime; - set - { - if (value == _wiFi_AutoRefreshTime) - return; + if (value == _wiFi_AutoRefreshTime) + return; - _wiFi_AutoRefreshTime = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wiFi_AutoRefreshTime = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _wiFi_ExportFilePath; - public string WiFi_ExportFilePath + private string _wiFi_ExportFilePath; + public string WiFi_ExportFilePath + { + get => _wiFi_ExportFilePath; + set { - get => _wiFi_ExportFilePath; - set - { - if (value == _wiFi_ExportFilePath) - return; + if (value == _wiFi_ExportFilePath) + return; - _wiFi_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wiFi_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _wiFi_ExportFileType = GlobalStaticConfiguration.WiFi_ExportFileType; - public ExportManager.ExportFileType WiFi_ExportFileType + private ExportManager.ExportFileType _wiFi_ExportFileType = GlobalStaticConfiguration.WiFi_ExportFileType; + public ExportManager.ExportFileType WiFi_ExportFileType + { + get => _wiFi_ExportFileType; + set { - get => _wiFi_ExportFileType; - set - { - if (value == _wiFi_ExportFileType) - return; + if (value == _wiFi_ExportFileType) + return; - _wiFi_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wiFi_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region IPScanner - private bool _ipScanner_ShowScanResultForAllIPAddresses; - public bool IPScanner_ShowScanResultForAllIPAddresses + #region IPScanner + private bool _ipScanner_ShowScanResultForAllIPAddresses; + public bool IPScanner_ShowScanResultForAllIPAddresses + { + get => _ipScanner_ShowScanResultForAllIPAddresses; + set { - get => _ipScanner_ShowScanResultForAllIPAddresses; - set - { - if (value == _ipScanner_ShowScanResultForAllIPAddresses) - return; + if (value == _ipScanner_ShowScanResultForAllIPAddresses) + return; - _ipScanner_ShowScanResultForAllIPAddresses = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ShowScanResultForAllIPAddresses = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _ipScanner_Threads = GlobalStaticConfiguration.IPScanner_Threads; - public int IPScanner_Threads + private int _ipScanner_Threads = GlobalStaticConfiguration.IPScanner_Threads; + public int IPScanner_Threads + { + get => _ipScanner_Threads; + set { - get => _ipScanner_Threads; - set - { - if (value == _ipScanner_Threads) - return; + if (value == _ipScanner_Threads) + return; - _ipScanner_Threads = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_Threads = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _ipScanner_ICMPAttempts = GlobalStaticConfiguration.IPScanner_ICMPAttempts; - public int IPScanner_ICMPAttempts + private int _ipScanner_ICMPAttempts = GlobalStaticConfiguration.IPScanner_ICMPAttempts; + public int IPScanner_ICMPAttempts + { + get => _ipScanner_ICMPAttempts; + set { - get => _ipScanner_ICMPAttempts; - set - { - if (value == _ipScanner_ICMPAttempts) - return; + if (value == _ipScanner_ICMPAttempts) + return; - _ipScanner_ICMPAttempts = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ICMPAttempts = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _ipScanner_ICMPBuffer = GlobalStaticConfiguration.IPScanner_ICMPBuffer; - public int IPScanner_ICMPBuffer + private int _ipScanner_ICMPBuffer = GlobalStaticConfiguration.IPScanner_ICMPBuffer; + public int IPScanner_ICMPBuffer + { + get => _ipScanner_ICMPBuffer; + set { - get => _ipScanner_ICMPBuffer; - set - { - if (value == _ipScanner_ICMPBuffer) - return; + if (value == _ipScanner_ICMPBuffer) + return; - _ipScanner_ICMPBuffer = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ICMPBuffer = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _ipScanner_HostsHistory = new(); - public ObservableCollection IPScanner_HostsHistory + private ObservableCollection _ipScanner_HostsHistory = new(); + public ObservableCollection IPScanner_HostsHistory + { + get => _ipScanner_HostsHistory; + set { - get => _ipScanner_HostsHistory; - set - { - if (value == _ipScanner_HostsHistory) - return; + if (value == _ipScanner_HostsHistory) + return; - _ipScanner_HostsHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_HostsHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _ipScanner_ResolveHostname = true; - public bool IPScanner_ResolveHostname + private bool _ipScanner_ResolveHostname = true; + public bool IPScanner_ResolveHostname + { + get => _ipScanner_ResolveHostname; + set { - get => _ipScanner_ResolveHostname; - set - { - if (value == _ipScanner_ResolveHostname) - return; + if (value == _ipScanner_ResolveHostname) + return; - _ipScanner_ResolveHostname = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ResolveHostname = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _ipScanner_DNSShowErrorMessage = GlobalStaticConfiguration.IPScanner_DNSShowErrorMessage; - public bool IPScanner_DNSShowErrorMessage + private bool _ipScanner_DNSShowErrorMessage = GlobalStaticConfiguration.IPScanner_DNSShowErrorMessage; + public bool IPScanner_DNSShowErrorMessage + { + get => _ipScanner_DNSShowErrorMessage; + set { - get => _ipScanner_DNSShowErrorMessage; - set - { - if (value == _ipScanner_DNSShowErrorMessage) - return; + if (value == _ipScanner_DNSShowErrorMessage) + return; - _ipScanner_DNSShowErrorMessage = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_DNSShowErrorMessage = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _ipScanner_ResolveMACAddress; - public bool IPScanner_ResolveMACAddress + private bool _ipScanner_ResolveMACAddress; + public bool IPScanner_ResolveMACAddress + { + get => _ipScanner_ResolveMACAddress; + set { - get => _ipScanner_ResolveMACAddress; - set - { - if (value == _ipScanner_ResolveMACAddress) - return; + if (value == _ipScanner_ResolveMACAddress) + return; - _ipScanner_ResolveMACAddress = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ResolveMACAddress = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _ipScanner_ICMPTimeout = GlobalStaticConfiguration.IPScanner_ICMPTimeout; - public int IPScanner_ICMPTimeout + private int _ipScanner_ICMPTimeout = GlobalStaticConfiguration.IPScanner_ICMPTimeout; + public int IPScanner_ICMPTimeout + { + get => _ipScanner_ICMPTimeout; + set { - get => _ipScanner_ICMPTimeout; - set - { - if (value == _ipScanner_ICMPTimeout) - return; + if (value == _ipScanner_ICMPTimeout) + return; - _ipScanner_ICMPTimeout = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ICMPTimeout = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _ipScanner_CustomCommands = new(); - public ObservableCollection IPScanner_CustomCommands + private ObservableCollection _ipScanner_CustomCommands = new(); + public ObservableCollection IPScanner_CustomCommands + { + get => _ipScanner_CustomCommands; + set { - get => _ipScanner_CustomCommands; - set - { - if (value == _ipScanner_CustomCommands) - return; + if (value == _ipScanner_CustomCommands) + return; - _ipScanner_CustomCommands = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_CustomCommands = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _ipScanner_ExpandProfileView = true; - public bool IPScanner_ExpandProfileView + private bool _ipScanner_ExpandProfileView = true; + public bool IPScanner_ExpandProfileView + { + get => _ipScanner_ExpandProfileView; + set { - get => _ipScanner_ExpandProfileView; - set - { - if (value == _ipScanner_ExpandProfileView) - return; + if (value == _ipScanner_ExpandProfileView) + return; - _ipScanner_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _ipScanner_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double IPScanner_ProfileWidth + private double _ipScanner_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double IPScanner_ProfileWidth + { + get => _ipScanner_ProfileWidth; + set { - get => _ipScanner_ProfileWidth; - set - { - if (Math.Abs(value - _ipScanner_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _ipScanner_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _ipScanner_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _ipScanner_ExportFilePath; - public string IPScanner_ExportFilePath + private string _ipScanner_ExportFilePath; + public string IPScanner_ExportFilePath + { + get => _ipScanner_ExportFilePath; + set { - get => _ipScanner_ExportFilePath; - set - { - if (value == _ipScanner_ExportFilePath) - return; + if (value == _ipScanner_ExportFilePath) + return; - _ipScanner_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _ipScanner_ExportFileType = GlobalStaticConfiguration.IPScanner_ExportFileType; - public ExportManager.ExportFileType IPScanner_ExportFileType + private ExportManager.ExportFileType _ipScanner_ExportFileType = GlobalStaticConfiguration.IPScanner_ExportFileType; + public ExportManager.ExportFileType IPScanner_ExportFileType + { + get => _ipScanner_ExportFileType; + set { - get => _ipScanner_ExportFileType; - set - { - if (value == _ipScanner_ExportFileType) - return; + if (value == _ipScanner_ExportFileType) + return; - _ipScanner_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _ipScanner_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Port Scanner - private ObservableCollection _portScanner_HostsHistory = new(); - public ObservableCollection PortScanner_HostsHistory + #region Port Scanner + private ObservableCollection _portScanner_HostsHistory = new(); + public ObservableCollection PortScanner_HostsHistory + { + get => _portScanner_HostsHistory; + set { - get => _portScanner_HostsHistory; - set - { - if (value == _portScanner_HostsHistory) - return; + if (value == _portScanner_HostsHistory) + return; - _portScanner_HostsHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_HostsHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _portScanner_PortsHistory = new(); - public ObservableCollection PortScanner_PortsHistory + private ObservableCollection _portScanner_PortsHistory = new(); + public ObservableCollection PortScanner_PortsHistory + { + get => _portScanner_PortsHistory; + set { - get => _portScanner_PortsHistory; - set - { - if (value == _portScanner_PortsHistory) - return; + if (value == _portScanner_PortsHistory) + return; - _portScanner_PortsHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_PortsHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _portScanner_PortProfiles = new(); - public ObservableCollection PortScanner_PortProfiles + private ObservableCollection _portScanner_PortProfiles = new(); + public ObservableCollection PortScanner_PortProfiles + { + get => _portScanner_PortProfiles; + set { - get => _portScanner_PortProfiles; - set - { - if (value == _portScanner_PortProfiles) - return; + if (value == _portScanner_PortProfiles) + return; - _portScanner_PortProfiles = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_PortProfiles = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _portScanner_ResolveHostname = true; - public bool PortScanner_ResolveHostname + private bool _portScanner_ResolveHostname = true; + public bool PortScanner_ResolveHostname + { + get => _portScanner_ResolveHostname; + set { - get => _portScanner_ResolveHostname; - set - { - if (value == _portScanner_ResolveHostname) - return; + if (value == _portScanner_ResolveHostname) + return; - _portScanner_ResolveHostname = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_ResolveHostname = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _portScanner_HostThreads = GlobalStaticConfiguration.PortScanner_HostThreads; - public int PortScanner_HostThreads + private int _portScanner_HostThreads = GlobalStaticConfiguration.PortScanner_HostThreads; + public int PortScanner_HostThreads + { + get => _portScanner_HostThreads; + set { - get => _portScanner_HostThreads; - set - { - if (value == _portScanner_HostThreads) - return; + if (value == _portScanner_HostThreads) + return; - _portScanner_HostThreads = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_HostThreads = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _portScanner_PortThreads = GlobalStaticConfiguration.PortScanner_PortThreads; - public int PortScanner_PortThreads + private int _portScanner_PortThreads = GlobalStaticConfiguration.PortScanner_PortThreads; + public int PortScanner_PortThreads + { + get => _portScanner_PortThreads; + set { - get => _portScanner_PortThreads; - set - { - if (value == _portScanner_PortThreads) - return; + if (value == _portScanner_PortThreads) + return; - _portScanner_PortThreads = value; - SettingsChanged = true; - } + _portScanner_PortThreads = value; + SettingsChanged = true; } + } - private bool _portScanner_ShowClosed; - public bool PortScanner_ShowClosed + private bool _portScanner_ShowClosed; + public bool PortScanner_ShowClosed + { + get => _portScanner_ShowClosed; + set { - get => _portScanner_ShowClosed; - set - { - if (value == _portScanner_ShowClosed) - return; + if (value == _portScanner_ShowClosed) + return; - _portScanner_ShowClosed = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_ShowClosed = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _portScanner_Timeout = GlobalStaticConfiguration.PortScanner_Timeout; - public int PortScanner_Timeout + private int _portScanner_Timeout = GlobalStaticConfiguration.PortScanner_Timeout; + public int PortScanner_Timeout + { + get => _portScanner_Timeout; + set { - get => _portScanner_Timeout; - set - { - if (value == _portScanner_Timeout) - return; + if (value == _portScanner_Timeout) + return; - _portScanner_Timeout = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_Timeout = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _portScanner_ExpandProfileView = true; - public bool PortScanner_ExpandProfileView + private bool _portScanner_ExpandProfileView = true; + public bool PortScanner_ExpandProfileView + { + get => _portScanner_ExpandProfileView; + set { - get => _portScanner_ExpandProfileView; - set - { - if (value == _portScanner_ExpandProfileView) - return; + if (value == _portScanner_ExpandProfileView) + return; - _portScanner_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _portScanner_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double PortScanner_ProfileWidth + private double _portScanner_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double PortScanner_ProfileWidth + { + get => _portScanner_ProfileWidth; + set { - get => _portScanner_ProfileWidth; - set - { - if (Math.Abs(value - _portScanner_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _portScanner_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _portScanner_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _portScanner_ExportFilePath; - public string PortScanner_ExportFilePath + private string _portScanner_ExportFilePath; + public string PortScanner_ExportFilePath + { + get => _portScanner_ExportFilePath; + set { - get => _portScanner_ExportFilePath; - set - { - if (value == _portScanner_ExportFilePath) - return; + if (value == _portScanner_ExportFilePath) + return; - _portScanner_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _portScanner_ExportFileType = GlobalStaticConfiguration.PortScanner_ExportFileType; - public ExportManager.ExportFileType PortScanner_ExportFileType + private ExportManager.ExportFileType _portScanner_ExportFileType = GlobalStaticConfiguration.PortScanner_ExportFileType; + public ExportManager.ExportFileType PortScanner_ExportFileType + { + get => _portScanner_ExportFileType; + set { - get => _portScanner_ExportFileType; - set - { - if (value == _portScanner_ExportFileType) - return; + if (value == _portScanner_ExportFileType) + return; - _portScanner_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _portScanner_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Ping Monitor - private ObservableCollection _pingMonitor_HostHistory = new(); - public ObservableCollection PingMonitor_HostHistory + #region Ping Monitor + private ObservableCollection _pingMonitor_HostHistory = new(); + public ObservableCollection PingMonitor_HostHistory + { + get => _pingMonitor_HostHistory; + set { - get => _pingMonitor_HostHistory; - set - { - if (value == _pingMonitor_HostHistory) - return; + if (value == _pingMonitor_HostHistory) + return; - _pingMonitor_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _pingMonitor_Buffer = GlobalStaticConfiguration.PingMonitor_Buffer; - public int PingMonitor_Buffer + private int _pingMonitor_Buffer = GlobalStaticConfiguration.PingMonitor_Buffer; + public int PingMonitor_Buffer + { + get => _pingMonitor_Buffer; + set { - get => _pingMonitor_Buffer; - set - { - if (value == _pingMonitor_Buffer) - return; + if (value == _pingMonitor_Buffer) + return; - _pingMonitor_Buffer = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_Buffer = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _pingMonitor_DontFragement = true; - public bool PingMonitor_DontFragment + private bool _pingMonitor_DontFragement = true; + public bool PingMonitor_DontFragment + { + get => _pingMonitor_DontFragement; + set { - get => _pingMonitor_DontFragement; - set - { - if (value == _pingMonitor_DontFragement) - return; + if (value == _pingMonitor_DontFragement) + return; - _pingMonitor_DontFragement = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_DontFragement = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _pingMonitor_Timeout = GlobalStaticConfiguration.PingMonitor_Timeout; - public int PingMonitor_Timeout + private int _pingMonitor_Timeout = GlobalStaticConfiguration.PingMonitor_Timeout; + public int PingMonitor_Timeout + { + get => _pingMonitor_Timeout; + set { - get => _pingMonitor_Timeout; - set - { - if (value == _pingMonitor_Timeout) - return; + if (value == _pingMonitor_Timeout) + return; - _pingMonitor_Timeout = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_Timeout = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _pingMonitor_TTL = GlobalStaticConfiguration.PingMonitor_TTL; - public int PingMonitor_TTL + private int _pingMonitor_TTL = GlobalStaticConfiguration.PingMonitor_TTL; + public int PingMonitor_TTL + { + get => _pingMonitor_TTL; + set { - get => _pingMonitor_TTL; - set - { - if (value == _pingMonitor_TTL) - return; + if (value == _pingMonitor_TTL) + return; - _pingMonitor_TTL = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_TTL = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _pingMonitor_WaitTime = GlobalStaticConfiguration.PingMonitor_WaitTime; - public int PingMonitor_WaitTime + private int _pingMonitor_WaitTime = GlobalStaticConfiguration.PingMonitor_WaitTime; + public int PingMonitor_WaitTime + { + get => _pingMonitor_WaitTime; + set { - get => _pingMonitor_WaitTime; - set - { - if (value == _pingMonitor_WaitTime) - return; + if (value == _pingMonitor_WaitTime) + return; - _pingMonitor_WaitTime = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_WaitTime = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _pingMonitor_ExportFilePath; - public string PingMonitor_ExportFilePath + private string _pingMonitor_ExportFilePath; + public string PingMonitor_ExportFilePath + { + get => _pingMonitor_ExportFilePath; + set { - get => _pingMonitor_ExportFilePath; - set - { - if (value == _pingMonitor_ExportFilePath) - return; + if (value == _pingMonitor_ExportFilePath) + return; - _pingMonitor_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _pingMonitor_ExportFileType = GlobalStaticConfiguration.PingMonitor_ExportFileType; - public ExportManager.ExportFileType PingMonitor_ExportFileType + private ExportManager.ExportFileType _pingMonitor_ExportFileType = GlobalStaticConfiguration.PingMonitor_ExportFileType; + public ExportManager.ExportFileType PingMonitor_ExportFileType + { + get => _pingMonitor_ExportFileType; + set { - get => _pingMonitor_ExportFileType; - set - { - if (value == _pingMonitor_ExportFileType) - return; + if (value == _pingMonitor_ExportFileType) + return; - _pingMonitor_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _pingMonitor_ExpandProfileView = true; - public bool PingMonitor_ExpandProfileView + private bool _pingMonitor_ExpandProfileView = true; + public bool PingMonitor_ExpandProfileView + { + get => _pingMonitor_ExpandProfileView; + set { - get => _pingMonitor_ExpandProfileView; - set - { - if (value == _pingMonitor_ExpandProfileView) - return; + if (value == _pingMonitor_ExpandProfileView) + return; - _pingMonitor_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _pingMonitor_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double PingMonitor_ProfileWidth + private double _pingMonitor_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double PingMonitor_ProfileWidth + { + get => _pingMonitor_ProfileWidth; + set { - get => _pingMonitor_ProfileWidth; - set - { - if (Math.Abs(value - _pingMonitor_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _pingMonitor_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _pingMonitor_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _pingMonitor_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Traceroute - private ObservableCollection _traceroute_HostHistory = new(); - public ObservableCollection Traceroute_HostHistory + #region Traceroute + private ObservableCollection _traceroute_HostHistory = new(); + public ObservableCollection Traceroute_HostHistory + { + get => _traceroute_HostHistory; + set { - get => _traceroute_HostHistory; - set - { - if (value == _traceroute_HostHistory) - return; + if (value == _traceroute_HostHistory) + return; - _traceroute_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _traceroute_MaximumHops = GlobalStaticConfiguration.Traceroute_MaximumHops; - public int Traceroute_MaximumHops + private int _traceroute_MaximumHops = GlobalStaticConfiguration.Traceroute_MaximumHops; + public int Traceroute_MaximumHops + { + get => _traceroute_MaximumHops; + set { - get => _traceroute_MaximumHops; - set - { - if (value == _traceroute_MaximumHops) - return; + if (value == _traceroute_MaximumHops) + return; - _traceroute_MaximumHops = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_MaximumHops = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _traceroute_Timeout = GlobalStaticConfiguration.Traceroute_Timeout; - public int Traceroute_Timeout + private int _traceroute_Timeout = GlobalStaticConfiguration.Traceroute_Timeout; + public int Traceroute_Timeout + { + get => _traceroute_Timeout; + set { - get => _traceroute_Timeout; - set - { - if (value == _traceroute_Timeout) - return; + if (value == _traceroute_Timeout) + return; - _traceroute_Timeout = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_Timeout = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _traceroute_Buffer = GlobalStaticConfiguration.Traceroute_Buffer; - public int Traceroute_Buffer + private int _traceroute_Buffer = GlobalStaticConfiguration.Traceroute_Buffer; + public int Traceroute_Buffer + { + get => _traceroute_Buffer; + set { - get => _traceroute_Buffer; - set - { - if (value == _traceroute_Buffer) - return; + if (value == _traceroute_Buffer) + return; - _traceroute_Buffer = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_Buffer = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _traceroute_ResolveHostname = true; - public bool Traceroute_ResolveHostname + private bool _traceroute_ResolveHostname = true; + public bool Traceroute_ResolveHostname + { + get => _traceroute_ResolveHostname; + set { - get => _traceroute_ResolveHostname; - set - { - if (value == _traceroute_ResolveHostname) - return; + if (value == _traceroute_ResolveHostname) + return; - _traceroute_ResolveHostname = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_ResolveHostname = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _traceroute_ExpandProfileView = true; - public bool Traceroute_ExpandProfileView + private bool _traceroute_ExpandProfileView = true; + public bool Traceroute_ExpandProfileView + { + get => _traceroute_ExpandProfileView; + set { - get => _traceroute_ExpandProfileView; - set - { - if (value == _traceroute_ExpandProfileView) - return; + if (value == _traceroute_ExpandProfileView) + return; - _traceroute_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _traceroute_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double Traceroute_ProfileWidth + private double _traceroute_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double Traceroute_ProfileWidth + { + get => _traceroute_ProfileWidth; + set { - get => _traceroute_ProfileWidth; - set - { - if (Math.Abs(value - _traceroute_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _traceroute_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _traceroute_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _traceroute_ExportFilePath; - public string Traceroute_ExportFilePath + private string _traceroute_ExportFilePath; + public string Traceroute_ExportFilePath + { + get => _traceroute_ExportFilePath; + set { - get => _traceroute_ExportFilePath; - set - { - if (value == _traceroute_ExportFilePath) - return; + if (value == _traceroute_ExportFilePath) + return; - _traceroute_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _traceroute_ExportFileType = GlobalStaticConfiguration.Traceroute_ExportFileType; - public ExportManager.ExportFileType Traceroute_ExportFileType + private ExportManager.ExportFileType _traceroute_ExportFileType = GlobalStaticConfiguration.Traceroute_ExportFileType; + public ExportManager.ExportFileType Traceroute_ExportFileType + { + get => _traceroute_ExportFileType; + set { - get => _traceroute_ExportFileType; - set - { - if (value == _traceroute_ExportFileType) - return; + if (value == _traceroute_ExportFileType) + return; - _traceroute_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _traceroute_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region DNS Lookup - private ObservableCollection _dnsLookup_HostHistory = new(); - public ObservableCollection DNSLookup_HostHistory + #region DNS Lookup + private ObservableCollection _dnsLookup_HostHistory = new(); + public ObservableCollection DNSLookup_HostHistory + { + get => _dnsLookup_HostHistory; + set { - get => _dnsLookup_HostHistory; - set - { - if (value == _dnsLookup_HostHistory) - return; + if (value == _dnsLookup_HostHistory) + return; - _dnsLookup_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _dnsLookup_DNSServers_v2 = new(); - public ObservableCollection DNSLookup_DNSServers_v2 + private ObservableCollection _dnsLookup_DNSServers_v2 = new(); + public ObservableCollection DNSLookup_DNSServers_v2 + { + get => _dnsLookup_DNSServers_v2; + set { - get => _dnsLookup_DNSServers_v2; - set - { - if (value == _dnsLookup_DNSServers_v2) - return; + if (value == _dnsLookup_DNSServers_v2) + return; - _dnsLookup_DNSServers_v2 = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_DNSServers_v2 = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private DNSServerConnectionInfoProfile _dnsLookup_SelectedDNSServer_v2 = new(); - public DNSServerConnectionInfoProfile DNSLookup_SelectedDNSServer_v2 + private DNSServerConnectionInfoProfile _dnsLookup_SelectedDNSServer_v2 = new(); + public DNSServerConnectionInfoProfile DNSLookup_SelectedDNSServer_v2 + { + get => _dnsLookup_SelectedDNSServer_v2; + set { - get => _dnsLookup_SelectedDNSServer_v2; - set - { - if (value == _dnsLookup_SelectedDNSServer_v2) - return; + if (value == _dnsLookup_SelectedDNSServer_v2) + return; - _dnsLookup_SelectedDNSServer_v2 = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_SelectedDNSServer_v2 = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private QueryClass _dnsLookup_QueryClass = GlobalStaticConfiguration.DNSLookup_QueryClass; - public QueryClass DNSLookup_QueryClass + private QueryClass _dnsLookup_QueryClass = GlobalStaticConfiguration.DNSLookup_QueryClass; + public QueryClass DNSLookup_QueryClass + { + get => _dnsLookup_QueryClass; + set { - get => _dnsLookup_QueryClass; - set - { - if (value == _dnsLookup_QueryClass) - return; + if (value == _dnsLookup_QueryClass) + return; - _dnsLookup_QueryClass = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_QueryClass = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dnsLookup_ShowOnlyMostCommonQueryTypes = true; - public bool DNSLookup_ShowOnlyMostCommonQueryTypes + private bool _dnsLookup_ShowOnlyMostCommonQueryTypes = true; + public bool DNSLookup_ShowOnlyMostCommonQueryTypes + { + get => _dnsLookup_ShowOnlyMostCommonQueryTypes; + set { - get => _dnsLookup_ShowOnlyMostCommonQueryTypes; - set - { - if (value == _dnsLookup_ShowOnlyMostCommonQueryTypes) - return; + if (value == _dnsLookup_ShowOnlyMostCommonQueryTypes) + return; - _dnsLookup_ShowOnlyMostCommonQueryTypes = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_ShowOnlyMostCommonQueryTypes = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private QueryType _dnsLookup_QueryType = GlobalStaticConfiguration.DNSLookup_QueryType; - public QueryType DNSLookup_QueryType + private QueryType _dnsLookup_QueryType = GlobalStaticConfiguration.DNSLookup_QueryType; + public QueryType DNSLookup_QueryType + { + get => _dnsLookup_QueryType; + set { - get => _dnsLookup_QueryType; - set - { - if (value == _dnsLookup_QueryType) - return; + if (value == _dnsLookup_QueryType) + return; - _dnsLookup_QueryType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_QueryType = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dnsLookup_AddDNSSuffix = true; - public bool DNSLookup_AddDNSSuffix + private bool _dnsLookup_AddDNSSuffix = true; + public bool DNSLookup_AddDNSSuffix + { + get => _dnsLookup_AddDNSSuffix; + set { - get => _dnsLookup_AddDNSSuffix; - set - { - if (value == _dnsLookup_AddDNSSuffix) - return; + if (value == _dnsLookup_AddDNSSuffix) + return; - _dnsLookup_AddDNSSuffix = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_AddDNSSuffix = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dnsLookup_UseCustomDNSSuffix; - public bool DNSLookup_UseCustomDNSSuffix + private bool _dnsLookup_UseCustomDNSSuffix; + public bool DNSLookup_UseCustomDNSSuffix + { + get => _dnsLookup_UseCustomDNSSuffix; + set { - get => _dnsLookup_UseCustomDNSSuffix; - set - { - if (value == _dnsLookup_UseCustomDNSSuffix) - return; + if (value == _dnsLookup_UseCustomDNSSuffix) + return; - _dnsLookup_UseCustomDNSSuffix = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_UseCustomDNSSuffix = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _dnsLookup_CustomDNSSuffix; - public string DNSLookup_CustomDNSSuffix + private string _dnsLookup_CustomDNSSuffix; + public string DNSLookup_CustomDNSSuffix + { + get => _dnsLookup_CustomDNSSuffix; + set { - get => _dnsLookup_CustomDNSSuffix; - set - { - if (value == _dnsLookup_CustomDNSSuffix) - return; + if (value == _dnsLookup_CustomDNSSuffix) + return; - _dnsLookup_CustomDNSSuffix = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_CustomDNSSuffix = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dnsLookup_Recursion = true; - public bool DNSLookup_Recursion + private bool _dnsLookup_Recursion = true; + public bool DNSLookup_Recursion + { + get => _dnsLookup_Recursion; + set { - get => _dnsLookup_Recursion; - set - { - if (value == _dnsLookup_Recursion) - return; + if (value == _dnsLookup_Recursion) + return; - _dnsLookup_Recursion = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_Recursion = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dnsLookup_UseCache; - public bool DNSLookup_UseCache + private bool _dnsLookup_UseCache; + public bool DNSLookup_UseCache + { + get => _dnsLookup_UseCache; + set { - get => _dnsLookup_UseCache; - set - { - if (value == _dnsLookup_UseCache) - return; + if (value == _dnsLookup_UseCache) + return; - _dnsLookup_UseCache = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_UseCache = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dnsLookup_UseTCPOnly = GlobalStaticConfiguration.DNSLookup_UseTCPOnly; - public bool DNSLookup_UseTCPOnly + private bool _dnsLookup_UseTCPOnly = GlobalStaticConfiguration.DNSLookup_UseTCPOnly; + public bool DNSLookup_UseTCPOnly + { + get => _dnsLookup_UseTCPOnly; + set { - get => _dnsLookup_UseTCPOnly; - set - { - if (value == _dnsLookup_UseTCPOnly) - return; + if (value == _dnsLookup_UseTCPOnly) + return; - _dnsLookup_UseTCPOnly = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_UseTCPOnly = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _dnsLookup_Retries = GlobalStaticConfiguration.DNSLookup_Retries; - public int DNSLookup_Retries + private int _dnsLookup_Retries = GlobalStaticConfiguration.DNSLookup_Retries; + public int DNSLookup_Retries + { + get => _dnsLookup_Retries; + set { - get => _dnsLookup_Retries; - set - { - if (value == _dnsLookup_Retries) - return; + if (value == _dnsLookup_Retries) + return; - _dnsLookup_Retries = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_Retries = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _dnsLookup_Timeout = GlobalStaticConfiguration.DNSLookup_Timeout; - public int DNSLookup_Timeout + private int _dnsLookup_Timeout = GlobalStaticConfiguration.DNSLookup_Timeout; + public int DNSLookup_Timeout + { + get => _dnsLookup_Timeout; + set { - get => _dnsLookup_Timeout; - set - { - if (value == _dnsLookup_Timeout) - return; + if (value == _dnsLookup_Timeout) + return; - _dnsLookup_Timeout = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_Timeout = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _dnsLookup_ExpandProfileView = true; - public bool DNSLookup_ExpandProfileView + private bool _dnsLookup_ExpandProfileView = true; + public bool DNSLookup_ExpandProfileView + { + get => _dnsLookup_ExpandProfileView; + set { - get => _dnsLookup_ExpandProfileView; - set - { - if (value == _dnsLookup_ExpandProfileView) - return; + if (value == _dnsLookup_ExpandProfileView) + return; - _dnsLookup_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _dnsLookup_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double DNSLookup_ProfileWidth + private double _dnsLookup_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double DNSLookup_ProfileWidth + { + get => _dnsLookup_ProfileWidth; + set { - get => _dnsLookup_ProfileWidth; - set - { - if (Math.Abs(value - _dnsLookup_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _dnsLookup_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _dnsLookup_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _dnsLookup_ExportFilePath; - public string DNSLookup_ExportFilePath + private string _dnsLookup_ExportFilePath; + public string DNSLookup_ExportFilePath + { + get => _dnsLookup_ExportFilePath; + set { - get => _dnsLookup_ExportFilePath; - set - { - if (value == _dnsLookup_ExportFilePath) - return; + if (value == _dnsLookup_ExportFilePath) + return; - _dnsLookup_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _dnsLookup_ExportFileType = GlobalStaticConfiguration.DNSLookup_ExportFileType; - public ExportManager.ExportFileType DNSLookup_ExportFileType + private ExportManager.ExportFileType _dnsLookup_ExportFileType = GlobalStaticConfiguration.DNSLookup_ExportFileType; + public ExportManager.ExportFileType DNSLookup_ExportFileType + { + get => _dnsLookup_ExportFileType; + set { - get => _dnsLookup_ExportFileType; - set - { - if (value == _dnsLookup_ExportFileType) - return; + if (value == _dnsLookup_ExportFileType) + return; - _dnsLookup_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _dnsLookup_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Remote Desktop - private ObservableCollection _remoteDesktop_HostHistory = new(); - public ObservableCollection RemoteDesktop_HostHistory + #region Remote Desktop + private ObservableCollection _remoteDesktop_HostHistory = new(); + public ObservableCollection RemoteDesktop_HostHistory + { + get => _remoteDesktop_HostHistory; + set { - get => _remoteDesktop_HostHistory; - set - { - if (value == _remoteDesktop_HostHistory) - return; + if (value == _remoteDesktop_HostHistory) + return; - _remoteDesktop_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_AdjustScreenAutomatically; - public bool RemoteDesktop_AdjustScreenAutomatically + private bool _remoteDesktop_AdjustScreenAutomatically; + public bool RemoteDesktop_AdjustScreenAutomatically + { + get => _remoteDesktop_AdjustScreenAutomatically; + set { - get => _remoteDesktop_AdjustScreenAutomatically; - set - { - if (value == _remoteDesktop_AdjustScreenAutomatically) - return; + if (value == _remoteDesktop_AdjustScreenAutomatically) + return; - _remoteDesktop_AdjustScreenAutomatically = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_AdjustScreenAutomatically = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_UseCurrentViewSize = GlobalStaticConfiguration.RemoteDesktop_UseCurrentViewSize; - public bool RemoteDesktop_UseCurrentViewSize + private bool _remoteDesktop_UseCurrentViewSize = GlobalStaticConfiguration.RemoteDesktop_UseCurrentViewSize; + public bool RemoteDesktop_UseCurrentViewSize + { + get => _remoteDesktop_UseCurrentViewSize; + set { - get => _remoteDesktop_UseCurrentViewSize; - set - { - if (value == _remoteDesktop_UseCurrentViewSize) - return; + if (value == _remoteDesktop_UseCurrentViewSize) + return; - _remoteDesktop_UseCurrentViewSize = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_UseCurrentViewSize = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_UseFixedScreenSize; - public bool RemoteDesktop_UseFixedScreenSize + private bool _remoteDesktop_UseFixedScreenSize; + public bool RemoteDesktop_UseFixedScreenSize + { + get => _remoteDesktop_UseFixedScreenSize; + set { - get => _remoteDesktop_UseFixedScreenSize; - set - { - if (value == _remoteDesktop_UseFixedScreenSize) - return; + if (value == _remoteDesktop_UseFixedScreenSize) + return; - _remoteDesktop_UseFixedScreenSize = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_UseFixedScreenSize = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _remoteDesktop_ScreenWidth = GlobalStaticConfiguration.RemoteDesktop_ScreenWidth; - public int RemoteDesktop_ScreenWidth + private int _remoteDesktop_ScreenWidth = GlobalStaticConfiguration.RemoteDesktop_ScreenWidth; + public int RemoteDesktop_ScreenWidth + { + get => _remoteDesktop_ScreenWidth; + set { - get => _remoteDesktop_ScreenWidth; - set - { - if (value == _remoteDesktop_ScreenWidth) - return; + if (value == _remoteDesktop_ScreenWidth) + return; - _remoteDesktop_ScreenWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_ScreenWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _remoteDesktop_ScreenHeight = GlobalStaticConfiguration.RemoteDesktop_ScreenHeight; - public int RemoteDesktop_ScreenHeight + private int _remoteDesktop_ScreenHeight = GlobalStaticConfiguration.RemoteDesktop_ScreenHeight; + public int RemoteDesktop_ScreenHeight + { + get => _remoteDesktop_ScreenHeight; + set { - get => _remoteDesktop_ScreenHeight; - set - { - if (value == _remoteDesktop_ScreenHeight) - return; + if (value == _remoteDesktop_ScreenHeight) + return; - _remoteDesktop_ScreenHeight = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_ScreenHeight = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_UseCustomScreenSize; - public bool RemoteDesktop_UseCustomScreenSize + private bool _remoteDesktop_UseCustomScreenSize; + public bool RemoteDesktop_UseCustomScreenSize + { + get => _remoteDesktop_UseCustomScreenSize; + set { - get => _remoteDesktop_UseCustomScreenSize; - set - { - if (value == _remoteDesktop_UseCustomScreenSize) - return; + if (value == _remoteDesktop_UseCustomScreenSize) + return; - _remoteDesktop_UseCustomScreenSize = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_UseCustomScreenSize = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _remoteDesktop_CustomScreenWidth; - public int RemoteDesktop_CustomScreenWidth + private int _remoteDesktop_CustomScreenWidth; + public int RemoteDesktop_CustomScreenWidth + { + get => _remoteDesktop_CustomScreenWidth; + set { - get => _remoteDesktop_CustomScreenWidth; - set - { - if (value == _remoteDesktop_CustomScreenWidth) - return; + if (value == _remoteDesktop_CustomScreenWidth) + return; - _remoteDesktop_CustomScreenWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_CustomScreenWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _remoteDesktop_CustomScreenHeight; - public int RemoteDesktop_CustomScreenHeight + private int _remoteDesktop_CustomScreenHeight; + public int RemoteDesktop_CustomScreenHeight + { + get => _remoteDesktop_CustomScreenHeight; + set { - get => _remoteDesktop_CustomScreenHeight; - set - { - if (value == _remoteDesktop_CustomScreenHeight) - return; + if (value == _remoteDesktop_CustomScreenHeight) + return; - _remoteDesktop_CustomScreenHeight = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_CustomScreenHeight = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _remoteDesktop_ColorDepth = GlobalStaticConfiguration.RemoteDesktop_ColorDepth; - public int RemoteDesktop_ColorDepth + private int _remoteDesktop_ColorDepth = GlobalStaticConfiguration.RemoteDesktop_ColorDepth; + public int RemoteDesktop_ColorDepth + { + get => _remoteDesktop_ColorDepth; + set { - get => _remoteDesktop_ColorDepth; - set - { - if (value == _remoteDesktop_ColorDepth) - return; + if (value == _remoteDesktop_ColorDepth) + return; - _remoteDesktop_ColorDepth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_ColorDepth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _remoteDesktop_Port = GlobalStaticConfiguration.RemoteDesktop_Port; - public int RemoteDesktop_Port + private int _remoteDesktop_Port = GlobalStaticConfiguration.RemoteDesktop_Port; + public int RemoteDesktop_Port + { + get => _remoteDesktop_Port; + set { - get => _remoteDesktop_Port; - set - { - if (value == _remoteDesktop_Port) - return; + if (value == _remoteDesktop_Port) + return; - _remoteDesktop_Port = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_Port = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_EnableCredSspSupport = true; - public bool RemoteDesktop_EnableCredSspSupport + private bool _remoteDesktop_EnableCredSspSupport = true; + public bool RemoteDesktop_EnableCredSspSupport + { + get => _remoteDesktop_EnableCredSspSupport; + set { - get => _remoteDesktop_EnableCredSspSupport; - set - { - if (value == _remoteDesktop_EnableCredSspSupport) - return; + if (value == _remoteDesktop_EnableCredSspSupport) + return; - _remoteDesktop_EnableCredSspSupport = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_EnableCredSspSupport = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private uint _remoteDesktop_AuthenticationLevel = GlobalStaticConfiguration.RemoteDesktop_AuthenticationLevel; - public uint RemoteDesktop_AuthenticationLevel + private uint _remoteDesktop_AuthenticationLevel = GlobalStaticConfiguration.RemoteDesktop_AuthenticationLevel; + public uint RemoteDesktop_AuthenticationLevel + { + get => _remoteDesktop_AuthenticationLevel; + set { - get => _remoteDesktop_AuthenticationLevel; - set - { - if (value == _remoteDesktop_AuthenticationLevel) - return; + if (value == _remoteDesktop_AuthenticationLevel) + return; - _remoteDesktop_AuthenticationLevel = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_AuthenticationLevel = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private AudioRedirectionMode _remoteDesktop_AudioRedirectionMode = GlobalStaticConfiguration.RemoteDesktop_AudioRedirectionMode; - public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode + private AudioRedirectionMode _remoteDesktop_AudioRedirectionMode = GlobalStaticConfiguration.RemoteDesktop_AudioRedirectionMode; + public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode + { + get => _remoteDesktop_AudioRedirectionMode; + set { - get => _remoteDesktop_AudioRedirectionMode; - set - { - if (value == _remoteDesktop_AudioRedirectionMode) - return; + if (value == _remoteDesktop_AudioRedirectionMode) + return; - _remoteDesktop_AudioRedirectionMode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_AudioRedirectionMode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private AudioCaptureRedirectionMode _remoteDesktop_AudioCaptureRedirectionMode = GlobalStaticConfiguration.RemoteDesktop_AudioCaptureRedirectionMode; - public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode + private AudioCaptureRedirectionMode _remoteDesktop_AudioCaptureRedirectionMode = GlobalStaticConfiguration.RemoteDesktop_AudioCaptureRedirectionMode; + public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode + { + get => _remoteDesktop_AudioCaptureRedirectionMode; + set { - get => _remoteDesktop_AudioCaptureRedirectionMode; - set - { - if (value == _remoteDesktop_AudioCaptureRedirectionMode) - return; + if (value == _remoteDesktop_AudioCaptureRedirectionMode) + return; - _remoteDesktop_AudioCaptureRedirectionMode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_AudioCaptureRedirectionMode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private KeyboardHookMode _remoteDesktop_KeyboardHookMode = GlobalStaticConfiguration.RemoteDesktop_KeyboardHookMode; - public KeyboardHookMode RemoteDesktop_KeyboardHookMode + private KeyboardHookMode _remoteDesktop_KeyboardHookMode = GlobalStaticConfiguration.RemoteDesktop_KeyboardHookMode; + public KeyboardHookMode RemoteDesktop_KeyboardHookMode + { + get => _remoteDesktop_KeyboardHookMode; + set { - get => _remoteDesktop_KeyboardHookMode; - set - { - if (value == _remoteDesktop_KeyboardHookMode) - return; + if (value == _remoteDesktop_KeyboardHookMode) + return; - _remoteDesktop_KeyboardHookMode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_KeyboardHookMode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_RedirectClipboard = true; - public bool RemoteDesktop_RedirectClipboard + private bool _remoteDesktop_RedirectClipboard = true; + public bool RemoteDesktop_RedirectClipboard + { + get => _remoteDesktop_RedirectClipboard; + set { - get => _remoteDesktop_RedirectClipboard; - set - { - if (value == _remoteDesktop_RedirectClipboard) - return; + if (value == _remoteDesktop_RedirectClipboard) + return; - _remoteDesktop_RedirectClipboard = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_RedirectClipboard = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_RedirectDevices; - public bool RemoteDesktop_RedirectDevices + private bool _remoteDesktop_RedirectDevices; + public bool RemoteDesktop_RedirectDevices + { + get => _remoteDesktop_RedirectDevices; + set { - get => _remoteDesktop_RedirectDevices; - set - { - if (value == _remoteDesktop_RedirectDevices) - return; + if (value == _remoteDesktop_RedirectDevices) + return; - _remoteDesktop_RedirectDevices = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_RedirectDevices = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_RedirectDrives; - public bool RemoteDesktop_RedirectDrives + private bool _remoteDesktop_RedirectDrives; + public bool RemoteDesktop_RedirectDrives + { + get => _remoteDesktop_RedirectDrives; + set { - get => _remoteDesktop_RedirectDrives; - set - { - if (value == _remoteDesktop_RedirectDrives) - return; + if (value == _remoteDesktop_RedirectDrives) + return; - _remoteDesktop_RedirectDrives = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_RedirectDrives = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_RedirectPorts; - public bool RemoteDesktop_RedirectPorts + private bool _remoteDesktop_RedirectPorts; + public bool RemoteDesktop_RedirectPorts + { + get => _remoteDesktop_RedirectPorts; + set { - get => _remoteDesktop_RedirectPorts; - set - { - if (value == _remoteDesktop_RedirectPorts) - return; + if (value == _remoteDesktop_RedirectPorts) + return; - _remoteDesktop_RedirectPorts = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_RedirectPorts = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_RedirectSmartCards; - public bool RemoteDesktop_RedirectSmartCards + private bool _remoteDesktop_RedirectSmartCards; + public bool RemoteDesktop_RedirectSmartCards + { + get => _remoteDesktop_RedirectSmartCards; + set { - get => _remoteDesktop_RedirectSmartCards; - set - { - if (value == _remoteDesktop_RedirectSmartCards) - return; + if (value == _remoteDesktop_RedirectSmartCards) + return; - _remoteDesktop_RedirectSmartCards = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_RedirectSmartCards = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_RedirectPrinters; - public bool RemoteDesktop_RedirectPrinters + private bool _remoteDesktop_RedirectPrinters; + public bool RemoteDesktop_RedirectPrinters + { + get => _remoteDesktop_RedirectPrinters; + set { - get => _remoteDesktop_RedirectPrinters; - set - { - if (value == _remoteDesktop_RedirectPrinters) - return; + if (value == _remoteDesktop_RedirectPrinters) + return; - _remoteDesktop_RedirectPrinters = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_RedirectPrinters = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_PersistentBitmapCaching; - public bool RemoteDesktop_PersistentBitmapCaching + private bool _remoteDesktop_PersistentBitmapCaching; + public bool RemoteDesktop_PersistentBitmapCaching + { + get => _remoteDesktop_PersistentBitmapCaching; + set { - get => _remoteDesktop_PersistentBitmapCaching; - set - { - if (value == _remoteDesktop_PersistentBitmapCaching) - return; + if (value == _remoteDesktop_PersistentBitmapCaching) + return; - _remoteDesktop_PersistentBitmapCaching = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_PersistentBitmapCaching = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_ReconnectIfTheConnectionIsDropped; - public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped + private bool _remoteDesktop_ReconnectIfTheConnectionIsDropped; + public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped + { + get => _remoteDesktop_ReconnectIfTheConnectionIsDropped; + set { - get => _remoteDesktop_ReconnectIfTheConnectionIsDropped; - set - { - if (value == _remoteDesktop_ReconnectIfTheConnectionIsDropped) - return; + if (value == _remoteDesktop_ReconnectIfTheConnectionIsDropped) + return; - _remoteDesktop_ReconnectIfTheConnectionIsDropped = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_ReconnectIfTheConnectionIsDropped = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private NetworkConnectionType _remoteDesktop_NetworkConnectionType = GlobalStaticConfiguration.RemoteDesktop_NetworkConnectionType; - public NetworkConnectionType RemoteDesktop_NetworkConnectionType + private NetworkConnectionType _remoteDesktop_NetworkConnectionType = GlobalStaticConfiguration.RemoteDesktop_NetworkConnectionType; + public NetworkConnectionType RemoteDesktop_NetworkConnectionType + { + get => _remoteDesktop_NetworkConnectionType; + set { - get => _remoteDesktop_NetworkConnectionType; - set - { - if (value == _remoteDesktop_NetworkConnectionType) - return; + if (value == _remoteDesktop_NetworkConnectionType) + return; - _remoteDesktop_NetworkConnectionType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_NetworkConnectionType = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_DesktopBackground; - public bool RemoteDesktop_DesktopBackground + private bool _remoteDesktop_DesktopBackground; + public bool RemoteDesktop_DesktopBackground + { + get => _remoteDesktop_DesktopBackground; + set { - get => _remoteDesktop_DesktopBackground; - set - { - if (value == _remoteDesktop_DesktopBackground) - return; + if (value == _remoteDesktop_DesktopBackground) + return; - _remoteDesktop_DesktopBackground = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_DesktopBackground = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_FontSmoothing; - public bool RemoteDesktop_FontSmoothing + private bool _remoteDesktop_FontSmoothing; + public bool RemoteDesktop_FontSmoothing + { + get => _remoteDesktop_FontSmoothing; + set { - get => _remoteDesktop_FontSmoothing; - set - { - if (value == _remoteDesktop_FontSmoothing) - return; + if (value == _remoteDesktop_FontSmoothing) + return; - _remoteDesktop_FontSmoothing = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_FontSmoothing = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_DesktopComposition; - public bool RemoteDesktop_DesktopComposition + private bool _remoteDesktop_DesktopComposition; + public bool RemoteDesktop_DesktopComposition + { + get => _remoteDesktop_DesktopComposition; + set { - get => _remoteDesktop_DesktopComposition; - set - { - if (value == _remoteDesktop_DesktopComposition) - return; + if (value == _remoteDesktop_DesktopComposition) + return; - _remoteDesktop_DesktopComposition = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_DesktopComposition = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_ShowWindowContentsWhileDragging; - public bool RemoteDesktop_ShowWindowContentsWhileDragging + private bool _remoteDesktop_ShowWindowContentsWhileDragging; + public bool RemoteDesktop_ShowWindowContentsWhileDragging + { + get => _remoteDesktop_ShowWindowContentsWhileDragging; + set { - get => _remoteDesktop_ShowWindowContentsWhileDragging; - set - { - if (value == _remoteDesktop_ShowWindowContentsWhileDragging) - return; + if (value == _remoteDesktop_ShowWindowContentsWhileDragging) + return; - _remoteDesktop_ShowWindowContentsWhileDragging = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_ShowWindowContentsWhileDragging = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_MenuAndWindowAnimation; - public bool RemoteDesktop_MenuAndWindowAnimation + private bool _remoteDesktop_MenuAndWindowAnimation; + public bool RemoteDesktop_MenuAndWindowAnimation + { + get => _remoteDesktop_MenuAndWindowAnimation; + set { - get => _remoteDesktop_MenuAndWindowAnimation; - set - { - if (value == _remoteDesktop_MenuAndWindowAnimation) - return; + if (value == _remoteDesktop_MenuAndWindowAnimation) + return; - _remoteDesktop_MenuAndWindowAnimation = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_MenuAndWindowAnimation = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_VisualStyles; - public bool RemoteDesktop_VisualStyles + private bool _remoteDesktop_VisualStyles; + public bool RemoteDesktop_VisualStyles + { + get => _remoteDesktop_VisualStyles; + set { - get => _remoteDesktop_VisualStyles; - set - { - if (value == _remoteDesktop_VisualStyles) - return; + if (value == _remoteDesktop_VisualStyles) + return; - _remoteDesktop_VisualStyles = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_VisualStyles = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _remoteDesktop_ExpandProfileView = true; - public bool RemoteDesktop_ExpandProfileView + private bool _remoteDesktop_ExpandProfileView = true; + public bool RemoteDesktop_ExpandProfileView + { + get => _remoteDesktop_ExpandProfileView; + set { - get => _remoteDesktop_ExpandProfileView; - set - { - if (value == _remoteDesktop_ExpandProfileView) - return; + if (value == _remoteDesktop_ExpandProfileView) + return; - _remoteDesktop_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _remoteDesktop_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double RemoteDesktop_ProfileWidth + private double _remoteDesktop_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double RemoteDesktop_ProfileWidth + { + get => _remoteDesktop_ProfileWidth; + set { - get => _remoteDesktop_ProfileWidth; - set - { - if (Math.Abs(value - _remoteDesktop_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _remoteDesktop_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _remoteDesktop_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _remoteDesktop_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region PowerShell - private ObservableCollection _powerShell_HostHistory = new(); - public ObservableCollection PowerShell_HostHistory + #region PowerShell + private ObservableCollection _powerShell_HostHistory = new(); + public ObservableCollection PowerShell_HostHistory + { + get => _powerShell_HostHistory; + set { - get => _powerShell_HostHistory; - set - { - if (value == _powerShell_HostHistory) - return; + if (value == _powerShell_HostHistory) + return; - _powerShell_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _powerShell_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _powerShell_ApplicationFilePath; - public string PowerShell_ApplicationFilePath + private string _powerShell_ApplicationFilePath; + public string PowerShell_ApplicationFilePath + { + get => _powerShell_ApplicationFilePath; + set { - get => _powerShell_ApplicationFilePath; - set - { - if (value == _powerShell_ApplicationFilePath) - return; + if (value == _powerShell_ApplicationFilePath) + return; - _powerShell_ApplicationFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _powerShell_ApplicationFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _powerShell_Command = GlobalStaticConfiguration.PowerShell_Command; - public string PowerShell_Command + private string _powerShell_Command = GlobalStaticConfiguration.PowerShell_Command; + public string PowerShell_Command + { + get => _powerShell_Command; + set { - get => _powerShell_Command; - set - { - if (value == _powerShell_Command) - return; + if (value == _powerShell_Command) + return; - _powerShell_Command = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _powerShell_Command = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _powerShell_AdditionalCommandLine; - public string PowerShell_AdditionalCommandLine + private string _powerShell_AdditionalCommandLine; + public string PowerShell_AdditionalCommandLine + { + get => _powerShell_AdditionalCommandLine; + set { - get => _powerShell_AdditionalCommandLine; - set - { - if (value == _powerShell_AdditionalCommandLine) - return; + if (value == _powerShell_AdditionalCommandLine) + return; - _powerShell_AdditionalCommandLine = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _powerShell_AdditionalCommandLine = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private Models.PowerShell.PowerShell.ExecutionPolicy _powerShell_ExecutionPolicy = GlobalStaticConfiguration.PowerShell_ExecutionPolicy; - public Models.PowerShell.PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy + private Models.PowerShell.PowerShell.ExecutionPolicy _powerShell_ExecutionPolicy = GlobalStaticConfiguration.PowerShell_ExecutionPolicy; + public Models.PowerShell.PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy + { + get => _powerShell_ExecutionPolicy; + set { - get => _powerShell_ExecutionPolicy; - set - { - if (value == _powerShell_ExecutionPolicy) - return; + if (value == _powerShell_ExecutionPolicy) + return; - _powerShell_ExecutionPolicy = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _powerShell_ExecutionPolicy = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _powerShell_ExpandProfileView = true; - public bool PowerShell_ExpandProfileView + private bool _powerShell_ExpandProfileView = true; + public bool PowerShell_ExpandProfileView + { + get => _powerShell_ExpandProfileView; + set { - get => _powerShell_ExpandProfileView; - set - { - if (value == _powerShell_ExpandProfileView) - return; + if (value == _powerShell_ExpandProfileView) + return; - _powerShell_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _powerShell_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _powerShell_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double PowerShell_ProfileWidth + private double _powerShell_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double PowerShell_ProfileWidth + { + get => _powerShell_ProfileWidth; + set { - get => _powerShell_ProfileWidth; - set - { - if (Math.Abs(value - _powerShell_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _powerShell_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _powerShell_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _powerShell_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region PuTTY - private ObservableCollection _puTTY_HostHistory = new(); - public ObservableCollection PuTTY_HostHistory + #region PuTTY + private ObservableCollection _puTTY_HostHistory = new(); + public ObservableCollection PuTTY_HostHistory + { + get => _puTTY_HostHistory; + set { - get => _puTTY_HostHistory; - set - { - if (value == _puTTY_HostHistory) - return; + if (value == _puTTY_HostHistory) + return; - _puTTY_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ConnectionMode _puTTY_DefaultConnectionMode = GlobalStaticConfiguration.PuTTY_DefaultConnectionMode; - public ConnectionMode PuTTY_DefaultConnectionMode + private ConnectionMode _puTTY_DefaultConnectionMode = GlobalStaticConfiguration.PuTTY_DefaultConnectionMode; + public ConnectionMode PuTTY_DefaultConnectionMode + { + get => _puTTY_DefaultConnectionMode; + set { - get => _puTTY_DefaultConnectionMode; - set - { - if (value == _puTTY_DefaultConnectionMode) - return; + if (value == _puTTY_DefaultConnectionMode) + return; - _puTTY_DefaultConnectionMode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_DefaultConnectionMode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_Username; - public string PuTTY_Username + private string _puTTY_Username; + public string PuTTY_Username + { + get => _puTTY_Username; + set { - get => _puTTY_Username; - set - { - if (value == _puTTY_Username) - return; + if (value == _puTTY_Username) + return; - _puTTY_Username = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_Username = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_PrivateKeyFile; - public string PuTTY_PrivateKeyFile + private string _puTTY_PrivateKeyFile; + public string PuTTY_PrivateKeyFile + { + get => _puTTY_PrivateKeyFile; + set { - get => _puTTY_PrivateKeyFile; - set - { - if (value == _puTTY_PrivateKeyFile) - return; + if (value == _puTTY_PrivateKeyFile) + return; - _puTTY_PrivateKeyFile = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_PrivateKeyFile = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_Profile = GlobalStaticConfiguration.PuTTY_DefaultProfile; - public string PuTTY_Profile + private string _puTTY_Profile = GlobalStaticConfiguration.PuTTY_DefaultProfile; + public string PuTTY_Profile + { + get => _puTTY_Profile; + set { - get => _puTTY_Profile; - set - { - if (value == _puTTY_Profile) - return; + if (value == _puTTY_Profile) + return; - _puTTY_Profile = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_Profile = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _puTTY_EnableSessionLog; - public bool PuTTY_EnableSessionLog + private bool _puTTY_EnableSessionLog; + public bool PuTTY_EnableSessionLog + { + get => _puTTY_EnableSessionLog; + set { - get => _puTTY_EnableSessionLog; - set - { - if (value == _puTTY_EnableSessionLog) - return; + if (value == _puTTY_EnableSessionLog) + return; - _puTTY_EnableSessionLog = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_EnableSessionLog = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private LogMode _puTTY_LogMode = GlobalStaticConfiguration.PuTTY_LogMode; - public LogMode PuTTY_LogMode + private LogMode _puTTY_LogMode = GlobalStaticConfiguration.PuTTY_LogMode; + public LogMode PuTTY_LogMode + { + get => _puTTY_LogMode; + set { - get => _puTTY_LogMode; - set - { - if (value == _puTTY_LogMode) - return; + if (value == _puTTY_LogMode) + return; - _puTTY_LogMode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_LogMode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_LogPath = GlobalStaticConfiguration.PuTTY_LogPath; - public string PuTTY_LogPath + private string _puTTY_LogPath = GlobalStaticConfiguration.PuTTY_LogPath; + public string PuTTY_LogPath + { + get => _puTTY_LogPath; + set { - get => _puTTY_LogPath; - set - { - if (value == _puTTY_LogPath) - return; + if (value == _puTTY_LogPath) + return; - _puTTY_LogPath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_LogPath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_LogFileName = GlobalStaticConfiguration.PuTTY_LogFileName; - public string PuTTY_LogFileName + private string _puTTY_LogFileName = GlobalStaticConfiguration.PuTTY_LogFileName; + public string PuTTY_LogFileName + { + get => _puTTY_LogFileName; + set { - get => _puTTY_LogFileName; - set - { - if (value == _puTTY_LogFileName) - return; + if (value == _puTTY_LogFileName) + return; - _puTTY_LogFileName = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_LogFileName = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_AdditionalCommandLine; - public string PuTTY_AdditionalCommandLine + private string _puTTY_AdditionalCommandLine; + public string PuTTY_AdditionalCommandLine + { + get => _puTTY_AdditionalCommandLine; + set { - get => _puTTY_AdditionalCommandLine; - set - { - if (value == _puTTY_AdditionalCommandLine) - return; + if (value == _puTTY_AdditionalCommandLine) + return; - _puTTY_AdditionalCommandLine = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_AdditionalCommandLine = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _puTTY_SerialLineHistory = new(); - public ObservableCollection PuTTY_SerialLineHistory + private ObservableCollection _puTTY_SerialLineHistory = new(); + public ObservableCollection PuTTY_SerialLineHistory + { + get => _puTTY_SerialLineHistory; + set { - get => _puTTY_SerialLineHistory; - set - { - if (value == _puTTY_SerialLineHistory) - return; + if (value == _puTTY_SerialLineHistory) + return; - _puTTY_SerialLineHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_SerialLineHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _puTTY_PortHistory = new(); - public ObservableCollection PuTTY_PortHistory + private ObservableCollection _puTTY_PortHistory = new(); + public ObservableCollection PuTTY_PortHistory + { + get => _puTTY_PortHistory; + set { - get => _puTTY_PortHistory; - set - { - if (value == _puTTY_PortHistory) - return; + if (value == _puTTY_PortHistory) + return; - _puTTY_PortHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_PortHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _puTTY_BaudHistory = new(); - public ObservableCollection PuTTY_BaudHistory + private ObservableCollection _puTTY_BaudHistory = new(); + public ObservableCollection PuTTY_BaudHistory + { + get => _puTTY_BaudHistory; + set { - get => _puTTY_BaudHistory; - set - { - if (value == _puTTY_BaudHistory) - return; + if (value == _puTTY_BaudHistory) + return; - _puTTY_BaudHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_BaudHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _puTTY_UsernameHistory = new(); - public ObservableCollection PuTTY_UsernameHistory + private ObservableCollection _puTTY_UsernameHistory = new(); + public ObservableCollection PuTTY_UsernameHistory + { + get => _puTTY_UsernameHistory; + set { - get => _puTTY_UsernameHistory; - set - { - if (value == _puTTY_UsernameHistory) - return; + if (value == _puTTY_UsernameHistory) + return; - _puTTY_UsernameHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_UsernameHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _puTTY_PrivateKeyFileHistory = new(); - public ObservableCollection PuTTY_PrivateKeyFileHistory + private ObservableCollection _puTTY_PrivateKeyFileHistory = new(); + public ObservableCollection PuTTY_PrivateKeyFileHistory + { + get => _puTTY_PrivateKeyFileHistory; + set { - get => _puTTY_PrivateKeyFileHistory; - set - { - if (value == _puTTY_PrivateKeyFileHistory) - return; + if (value == _puTTY_PrivateKeyFileHistory) + return; - _puTTY_PrivateKeyFileHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_PrivateKeyFileHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _puTTY_ProfileHistory = new(); - public ObservableCollection PuTTY_ProfileHistory + private ObservableCollection _puTTY_ProfileHistory = new(); + public ObservableCollection PuTTY_ProfileHistory + { + get => _puTTY_ProfileHistory; + set { - get => _puTTY_ProfileHistory; - set - { - if (value == _puTTY_ProfileHistory) - return; + if (value == _puTTY_ProfileHistory) + return; - _puTTY_ProfileHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_ProfileHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _puTTY_ExpandProfileView = true; - public bool PuTTY_ExpandProfileView + private bool _puTTY_ExpandProfileView = true; + public bool PuTTY_ExpandProfileView + { + get => _puTTY_ExpandProfileView; + set { - get => _puTTY_ExpandProfileView; - set - { - if (value == _puTTY_ExpandProfileView) - return; + if (value == _puTTY_ExpandProfileView) + return; - _puTTY_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _puTTY_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double PuTTY_ProfileWidth + private double _puTTY_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double PuTTY_ProfileWidth + { + get => _puTTY_ProfileWidth; + set { - get => _puTTY_ProfileWidth; - set - { - if (Math.Abs(value - _puTTY_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _puTTY_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _puTTY_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_ApplicationFilePath; - public string PuTTY_ApplicationFilePath + private string _puTTY_ApplicationFilePath; + public string PuTTY_ApplicationFilePath + { + get => _puTTY_ApplicationFilePath; + set { - get => _puTTY_ApplicationFilePath; - set - { - if (value == _puTTY_ApplicationFilePath) - return; + if (value == _puTTY_ApplicationFilePath) + return; - _puTTY_ApplicationFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_ApplicationFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _puTTY_SerialLine = GlobalStaticConfiguration.PuTTY_SerialLine; - public string PuTTY_SerialLine + private string _puTTY_SerialLine = GlobalStaticConfiguration.PuTTY_SerialLine; + public string PuTTY_SerialLine + { + get => _puTTY_SerialLine; + set { - get => _puTTY_SerialLine; - set - { - if (value == _puTTY_SerialLine) - return; + if (value == _puTTY_SerialLine) + return; - _puTTY_SerialLine = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_SerialLine = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _puTTY_SSHPort = GlobalStaticConfiguration.PuTTY_SSHPort; - public int PuTTY_SSHPort + private int _puTTY_SSHPort = GlobalStaticConfiguration.PuTTY_SSHPort; + public int PuTTY_SSHPort + { + get => _puTTY_SSHPort; + set { - get => _puTTY_SSHPort; - set - { - if (value == _puTTY_SSHPort) - return; + if (value == _puTTY_SSHPort) + return; - _puTTY_SSHPort = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_SSHPort = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _puTTY_TelnetPort = GlobalStaticConfiguration.PuTTY_TelnetPort; - public int PuTTY_TelnetPort + private int _puTTY_TelnetPort = GlobalStaticConfiguration.PuTTY_TelnetPort; + public int PuTTY_TelnetPort + { + get => _puTTY_TelnetPort; + set { - get => _puTTY_TelnetPort; - set - { - if (value == _puTTY_TelnetPort) - return; + if (value == _puTTY_TelnetPort) + return; - _puTTY_TelnetPort = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_TelnetPort = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _puTTY_RloginPort = GlobalStaticConfiguration.PuTTY_RloginPort; - public int PuTTY_RloginPort + private int _puTTY_RloginPort = GlobalStaticConfiguration.PuTTY_RloginPort; + public int PuTTY_RloginPort + { + get => _puTTY_RloginPort; + set { - get => _puTTY_RloginPort; - set - { - if (value == _puTTY_RloginPort) - return; + if (value == _puTTY_RloginPort) + return; - _puTTY_RloginPort = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_RloginPort = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _puTTY_BaudRate = GlobalStaticConfiguration.PuTTY_BaudRate; - public int PuTTY_BaudRate + private int _puTTY_BaudRate = GlobalStaticConfiguration.PuTTY_BaudRate; + public int PuTTY_BaudRate + { + get => _puTTY_BaudRate; + set { - get => _puTTY_BaudRate; - set - { - if (value == _puTTY_BaudRate) - return; + if (value == _puTTY_BaudRate) + return; - _puTTY_BaudRate = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_BaudRate = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _puTTY_DefaultRaw = GlobalStaticConfiguration.PuTTY_Raw; - public int PuTTY_DefaultRaw + private int _puTTY_DefaultRaw = GlobalStaticConfiguration.PuTTY_Raw; + public int PuTTY_DefaultRaw + { + get => _puTTY_DefaultRaw; + set { - get => _puTTY_DefaultRaw; - set - { - if (value == _puTTY_DefaultRaw) - return; + if (value == _puTTY_DefaultRaw) + return; - _puTTY_DefaultRaw = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _puTTY_DefaultRaw = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region AWS Session Manager - private bool _awsSessionManager_EnableSyncInstanceIDsFromAWS = GlobalStaticConfiguration.AWSSessionManager_EnableSyncInstanceIDsFromAWS; - public bool AWSSessionManager_EnableSyncInstanceIDsFromAWS + #region AWS Session Manager + private bool _awsSessionManager_EnableSyncInstanceIDsFromAWS = GlobalStaticConfiguration.AWSSessionManager_EnableSyncInstanceIDsFromAWS; + public bool AWSSessionManager_EnableSyncInstanceIDsFromAWS + { + get => _awsSessionManager_EnableSyncInstanceIDsFromAWS; + set { - get => _awsSessionManager_EnableSyncInstanceIDsFromAWS; - set - { - if (value == _awsSessionManager_EnableSyncInstanceIDsFromAWS) - return; + if (value == _awsSessionManager_EnableSyncInstanceIDsFromAWS) + return; - _awsSessionManager_EnableSyncInstanceIDsFromAWS = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_EnableSyncInstanceIDsFromAWS = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _awsSessionManager_AWSProfiles = new(); - public ObservableCollection AWSSessionManager_AWSProfiles + private ObservableCollection _awsSessionManager_AWSProfiles = new(); + public ObservableCollection AWSSessionManager_AWSProfiles + { + get => _awsSessionManager_AWSProfiles; + set { - get => _awsSessionManager_AWSProfiles; - set - { - if (value == _awsSessionManager_AWSProfiles) - return; + if (value == _awsSessionManager_AWSProfiles) + return; - _awsSessionManager_AWSProfiles = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_AWSProfiles = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool awsSessionManager_SyncOnlyRunningInstancesFromAWS = GlobalStaticConfiguration.AWSSessionManager_SyncOnlyRunningInstancesFromAWS; - public bool AWSSessionManager_SyncOnlyRunningInstancesFromAWS + private bool awsSessionManager_SyncOnlyRunningInstancesFromAWS = GlobalStaticConfiguration.AWSSessionManager_SyncOnlyRunningInstancesFromAWS; + public bool AWSSessionManager_SyncOnlyRunningInstancesFromAWS + { + get => awsSessionManager_SyncOnlyRunningInstancesFromAWS; + set { - get => awsSessionManager_SyncOnlyRunningInstancesFromAWS; - set - { - if (value == awsSessionManager_SyncOnlyRunningInstancesFromAWS) - return; + if (value == awsSessionManager_SyncOnlyRunningInstancesFromAWS) + return; - awsSessionManager_SyncOnlyRunningInstancesFromAWS = value; - OnPropertyChanged(); - SettingsChanged = true; - } + awsSessionManager_SyncOnlyRunningInstancesFromAWS = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _awsSessionManager_DefaultProfile; - public string AWSSessionManager_DefaultProfile + private string _awsSessionManager_DefaultProfile; + public string AWSSessionManager_DefaultProfile + { + get => _awsSessionManager_DefaultProfile; + set { - get => _awsSessionManager_DefaultProfile; - set - { - if (value == _awsSessionManager_DefaultProfile) - return; + if (value == _awsSessionManager_DefaultProfile) + return; - _awsSessionManager_DefaultProfile = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_DefaultProfile = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _awsSessionManager_DefaultRegion; - public string AWSSessionManager_DefaultRegion + private string _awsSessionManager_DefaultRegion; + public string AWSSessionManager_DefaultRegion + { + get => _awsSessionManager_DefaultRegion; + set { - get => _awsSessionManager_DefaultRegion; - set - { - if (value == _awsSessionManager_DefaultRegion) - return; + if (value == _awsSessionManager_DefaultRegion) + return; - _awsSessionManager_DefaultRegion = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_DefaultRegion = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _awsSessionManager_ApplicationFilePath; - public string AWSSessionManager_ApplicationFilePath + private string _awsSessionManager_ApplicationFilePath; + public string AWSSessionManager_ApplicationFilePath + { + get => _awsSessionManager_ApplicationFilePath; + set { - get => _awsSessionManager_ApplicationFilePath; - set - { - if (value == _awsSessionManager_ApplicationFilePath) - return; + if (value == _awsSessionManager_ApplicationFilePath) + return; - _awsSessionManager_ApplicationFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_ApplicationFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _awsSessionManager_InstanceIDHistory = new(); - public ObservableCollection AWSSessionManager_InstanceIDHistory + private ObservableCollection _awsSessionManager_InstanceIDHistory = new(); + public ObservableCollection AWSSessionManager_InstanceIDHistory + { + get => _awsSessionManager_InstanceIDHistory; + set { - get => _awsSessionManager_InstanceIDHistory; - set - { - if (value == _awsSessionManager_InstanceIDHistory) - return; + if (value == _awsSessionManager_InstanceIDHistory) + return; - _awsSessionManager_InstanceIDHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_InstanceIDHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _awsSessionManager_ProfileHistory = new(); - public ObservableCollection AWSSessionManager_ProfileHistory + private ObservableCollection _awsSessionManager_ProfileHistory = new(); + public ObservableCollection AWSSessionManager_ProfileHistory + { + get => _awsSessionManager_ProfileHistory; + set { - get => _awsSessionManager_ProfileHistory; - set - { - if (value == _awsSessionManager_ProfileHistory) - return; + if (value == _awsSessionManager_ProfileHistory) + return; - _awsSessionManager_ProfileHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_ProfileHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _awsSessionManager_RegionHistory = new(); - public ObservableCollection AWSSessionManager_RegionHistory + private ObservableCollection _awsSessionManager_RegionHistory = new(); + public ObservableCollection AWSSessionManager_RegionHistory + { + get => _awsSessionManager_RegionHistory; + set { - get => _awsSessionManager_RegionHistory; - set - { - if (value == _awsSessionManager_RegionHistory) - return; + if (value == _awsSessionManager_RegionHistory) + return; - _awsSessionManager_RegionHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_RegionHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _awsSessionManager_ExpandProfileView = true; - public bool AWSSessionManager_ExpandProfileView + private bool _awsSessionManager_ExpandProfileView = true; + public bool AWSSessionManager_ExpandProfileView + { + get => _awsSessionManager_ExpandProfileView; + set { - get => _awsSessionManager_ExpandProfileView; - set - { - if (value == _awsSessionManager_ExpandProfileView) - return; + if (value == _awsSessionManager_ExpandProfileView) + return; - _awsSessionManager_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _awsSessionManager_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double AWSSessionManager_ProfileWidth + private double _awsSessionManager_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double AWSSessionManager_ProfileWidth + { + get => _awsSessionManager_ProfileWidth; + set { - get => _awsSessionManager_ProfileWidth; - set - { - if (Math.Abs(value - _awsSessionManager_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _awsSessionManager_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _awsSessionManager_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _awsSessionManager_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region TigerVNC - private ObservableCollection _tigerVNC_HostHistory = new(); - public ObservableCollection TigerVNC_HostHistory + #region TigerVNC + private ObservableCollection _tigerVNC_HostHistory = new(); + public ObservableCollection TigerVNC_HostHistory + { + get => _tigerVNC_HostHistory; + set { - get => _tigerVNC_HostHistory; - set - { - if (value == _tigerVNC_HostHistory) - return; + if (value == _tigerVNC_HostHistory) + return; - _tigerVNC_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _tigerVNC_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _tigerVNC_PortHistory = new(); - public ObservableCollection TigerVNC_PortHistory + private ObservableCollection _tigerVNC_PortHistory = new(); + public ObservableCollection TigerVNC_PortHistory + { + get => _tigerVNC_PortHistory; + set { - get => _tigerVNC_PortHistory; - set - { - if (value == _tigerVNC_PortHistory) - return; + if (value == _tigerVNC_PortHistory) + return; - _tigerVNC_PortHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _tigerVNC_PortHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _tigerVNC_ExpandProfileView = true; - public bool TigerVNC_ExpandProfileView + private bool _tigerVNC_ExpandProfileView = true; + public bool TigerVNC_ExpandProfileView + { + get => _tigerVNC_ExpandProfileView; + set { - get => _tigerVNC_ExpandProfileView; - set - { - if (value == _tigerVNC_ExpandProfileView) - return; + if (value == _tigerVNC_ExpandProfileView) + return; - _tigerVNC_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _tigerVNC_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _tigerVNC_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double TigerVNC_ProfileWidth + private double _tigerVNC_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double TigerVNC_ProfileWidth + { + get => _tigerVNC_ProfileWidth; + set { - get => _tigerVNC_ProfileWidth; - set - { - if (Math.Abs(value - _tigerVNC_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _tigerVNC_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _tigerVNC_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _tigerVNC_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _tigerVNC_ApplicationFilePath; - public string TigerVNC_ApplicationFilePath + private string _tigerVNC_ApplicationFilePath; + public string TigerVNC_ApplicationFilePath + { + get => _tigerVNC_ApplicationFilePath; + set { - get => _tigerVNC_ApplicationFilePath; - set - { - if (value == _tigerVNC_ApplicationFilePath) - return; + if (value == _tigerVNC_ApplicationFilePath) + return; - _tigerVNC_ApplicationFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _tigerVNC_ApplicationFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _tigerVNC_Port = GlobalStaticConfiguration.TigerVNC_DefaultVNCPort; - public int TigerVNC_Port + private int _tigerVNC_Port = GlobalStaticConfiguration.TigerVNC_DefaultVNCPort; + public int TigerVNC_Port + { + get => _tigerVNC_Port; + set { - get => _tigerVNC_Port; - set - { - if (value == _tigerVNC_Port) - return; + if (value == _tigerVNC_Port) + return; - _tigerVNC_Port = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _tigerVNC_Port = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region WebConsole - private ObservableCollection _webConsole_UrlHistory = new(); - public ObservableCollection WebConsole_UrlHistory + #region WebConsole + private ObservableCollection _webConsole_UrlHistory = new(); + public ObservableCollection WebConsole_UrlHistory + { + get => _webConsole_UrlHistory; + set { - get => _webConsole_UrlHistory; - set - { - if (value == _webConsole_UrlHistory) - return; + if (value == _webConsole_UrlHistory) + return; - _webConsole_UrlHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _webConsole_UrlHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _webConsole_ExpandProfileView = true; - public bool WebConsole_ExpandProfileView + private bool _webConsole_ExpandProfileView = true; + public bool WebConsole_ExpandProfileView + { + get => _webConsole_ExpandProfileView; + set { - get => _webConsole_ExpandProfileView; - set - { - if (value == _webConsole_ExpandProfileView) - return; + if (value == _webConsole_ExpandProfileView) + return; - _webConsole_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _webConsole_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _webConsole_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double WebConsole_ProfileWidth + private double _webConsole_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double WebConsole_ProfileWidth + { + get => _webConsole_ProfileWidth; + set { - get => _webConsole_ProfileWidth; - set - { - if (Math.Abs(value - _webConsole_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _webConsole_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _webConsole_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _webConsole_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region SNMP - private WalkMode _snmp_WalkMode = GlobalStaticConfiguration.SNMP_WalkMode; - public WalkMode SNMP_WalkMode + #region SNMP + private WalkMode _snmp_WalkMode = GlobalStaticConfiguration.SNMP_WalkMode; + public WalkMode SNMP_WalkMode + { + get => _snmp_WalkMode; + set { - get => _snmp_WalkMode; - set - { - if (value == _snmp_WalkMode) - return; + if (value == _snmp_WalkMode) + return; - _snmp_WalkMode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_WalkMode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _snmp_Timeout = GlobalStaticConfiguration.SNMP_Timeout; - public int SNMP_Timeout + private int _snmp_Timeout = GlobalStaticConfiguration.SNMP_Timeout; + public int SNMP_Timeout + { + get => _snmp_Timeout; + set { - get => _snmp_Timeout; - set - { - if (value == _snmp_Timeout) - return; + if (value == _snmp_Timeout) + return; - _snmp_Timeout = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_Timeout = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _snmp_port = 161; - public int SNMP_Port + private int _snmp_port = 161; + public int SNMP_Port + { + get => _snmp_port; + set { - get => _snmp_port; - set - { - if (value == _snmp_port) - return; + if (value == _snmp_port) + return; - _snmp_port = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_port = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _snmp_HostHistory = new(); - public ObservableCollection SNMP_HostHistory + private ObservableCollection _snmp_HostHistory = new(); + public ObservableCollection SNMP_HostHistory + { + get => _snmp_HostHistory; + set { - get => _snmp_HostHistory; - set - { - if (value == _snmp_HostHistory) - return; + if (value == _snmp_HostHistory) + return; - _snmp_HostHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_HostHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _snmp_OIDHistory = new(); - public ObservableCollection SNMP_OIDHistory + private ObservableCollection _snmp_OIDHistory = new(); + public ObservableCollection SNMP_OIDHistory + { + get => _snmp_OIDHistory; + set { - get => _snmp_OIDHistory; - set - { - if (value == _snmp_OIDHistory) - return; + if (value == _snmp_OIDHistory) + return; - _snmp_OIDHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_OIDHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private SNMPMode _snmp_Mode = GlobalStaticConfiguration.SNMP_Mode; - public SNMPMode SNMP_Mode + private SNMPMode _snmp_Mode = GlobalStaticConfiguration.SNMP_Mode; + public SNMPMode SNMP_Mode + { + get => _snmp_Mode; + set { - get => _snmp_Mode; - set - { - if (value == _snmp_Mode) - return; + if (value == _snmp_Mode) + return; - _snmp_Mode = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_Mode = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private SNMPVersion _snmp_Version = GlobalStaticConfiguration.SNMP_Version; - public SNMPVersion SNMP_Version + private SNMPVersion _snmp_Version = GlobalStaticConfiguration.SNMP_Version; + public SNMPVersion SNMP_Version + { + get => _snmp_Version; + set { - get => _snmp_Version; - set - { - if (value == _snmp_Version) - return; + if (value == _snmp_Version) + return; - _snmp_Version = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_Version = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private SNMPV3Security _snmp_Security = GlobalStaticConfiguration.SNMP_Security; - public SNMPV3Security SNMP_Security + private SNMPV3Security _snmp_Security = GlobalStaticConfiguration.SNMP_Security; + public SNMPV3Security SNMP_Security + { + get => _snmp_Security; + set { - get => _snmp_Security; - set - { - if (value == _snmp_Security) - return; + if (value == _snmp_Security) + return; - _snmp_Security = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_Security = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private SNMPV3AuthenticationProvider _snmp_AuthenticationProvider = GlobalStaticConfiguration.SNMP_AuthenticationProvider; - public SNMPV3AuthenticationProvider SNMP_AuthenticationProvider + private SNMPV3AuthenticationProvider _snmp_AuthenticationProvider = GlobalStaticConfiguration.SNMP_AuthenticationProvider; + public SNMPV3AuthenticationProvider SNMP_AuthenticationProvider + { + get => _snmp_AuthenticationProvider; + set { - get => _snmp_AuthenticationProvider; - set - { - if (value == _snmp_AuthenticationProvider) - return; + if (value == _snmp_AuthenticationProvider) + return; - _snmp_AuthenticationProvider = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_AuthenticationProvider = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private SNMPV3PrivacyProvider _snmp_PrivacyProvider = GlobalStaticConfiguration.SNMP_PrivacyProvider; - public SNMPV3PrivacyProvider SNMP_PrivacyProvider + private SNMPV3PrivacyProvider _snmp_PrivacyProvider = GlobalStaticConfiguration.SNMP_PrivacyProvider; + public SNMPV3PrivacyProvider SNMP_PrivacyProvider + { + get => _snmp_PrivacyProvider; + set { - get => _snmp_PrivacyProvider; - set - { - if (value == _snmp_PrivacyProvider) - return; + if (value == _snmp_PrivacyProvider) + return; - _snmp_PrivacyProvider = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_PrivacyProvider = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _snmp_ExportFilePath; - public string SNMP_ExportFilePath + private string _snmp_ExportFilePath; + public string SNMP_ExportFilePath + { + get => _snmp_ExportFilePath; + set { - get => _snmp_ExportFilePath; - set - { - if (value == _snmp_ExportFilePath) - return; + if (value == _snmp_ExportFilePath) + return; - _snmp_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _snmp_ExportFileType = GlobalStaticConfiguration.SNMP_ExportFileType; - public ExportManager.ExportFileType SNMP_ExportFileType + private ExportManager.ExportFileType _snmp_ExportFileType = GlobalStaticConfiguration.SNMP_ExportFileType; + public ExportManager.ExportFileType SNMP_ExportFileType + { + get => _snmp_ExportFileType; + set { - get => _snmp_ExportFileType; - set - { - if (value == _snmp_ExportFileType) - return; + if (value == _snmp_ExportFileType) + return; - _snmp_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _snmp_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region SNTP Lookup - private ObservableCollection _sntpLookup_SNTPServers = new(); - public ObservableCollection SNTPLookup_SNTPServers + #region SNTP Lookup + private ObservableCollection _sntpLookup_SNTPServers = new(); + public ObservableCollection SNTPLookup_SNTPServers + { + get => _sntpLookup_SNTPServers; + set { - get => _sntpLookup_SNTPServers; - set - { - if (value == _sntpLookup_SNTPServers) - return; + if (value == _sntpLookup_SNTPServers) + return; - _sntpLookup_SNTPServers = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _sntpLookup_SNTPServers = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ServerConnectionInfoProfile _sntpLookup_SelectedSNTPServer = new(); - public ServerConnectionInfoProfile SNTPLookup_SelectedSNTPServer + private ServerConnectionInfoProfile _sntpLookup_SelectedSNTPServer = new(); + public ServerConnectionInfoProfile SNTPLookup_SelectedSNTPServer + { + get => _sntpLookup_SelectedSNTPServer; + set { - get => _sntpLookup_SelectedSNTPServer; - set - { - if (value == _sntpLookup_SelectedSNTPServer) - return; + if (value == _sntpLookup_SelectedSNTPServer) + return; - _sntpLookup_SelectedSNTPServer = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _sntpLookup_SelectedSNTPServer = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _sntpLookup_Timeout = GlobalStaticConfiguration.SNTPLookup_Timeout; - public int SNTPLookup_Timeout + private int _sntpLookup_Timeout = GlobalStaticConfiguration.SNTPLookup_Timeout; + public int SNTPLookup_Timeout + { + get => _sntpLookup_Timeout; + set { - get => _sntpLookup_Timeout; - set - { - if (value == _sntpLookup_Timeout) - return; + if (value == _sntpLookup_Timeout) + return; - _sntpLookup_Timeout = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _sntpLookup_Timeout = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _sntpLookup_ExportFilePath; - public string SNTPLookup_ExportFilePath + private string _sntpLookup_ExportFilePath; + public string SNTPLookup_ExportFilePath + { + get => _sntpLookup_ExportFilePath; + set { - get => _sntpLookup_ExportFilePath; - set - { - if (value == _sntpLookup_ExportFilePath) - return; + if (value == _sntpLookup_ExportFilePath) + return; - _sntpLookup_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _sntpLookup_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _sntpLookup_ExportFileType = GlobalStaticConfiguration.SNTPLookup_ExportFileType; - public ExportManager.ExportFileType SNTPLookup_ExportFileType + private ExportManager.ExportFileType _sntpLookup_ExportFileType = GlobalStaticConfiguration.SNTPLookup_ExportFileType; + public ExportManager.ExportFileType SNTPLookup_ExportFileType + { + get => _sntpLookup_ExportFileType; + set { - get => _sntpLookup_ExportFileType; - set - { - if (value == _sntpLookup_ExportFileType) - return; + if (value == _sntpLookup_ExportFileType) + return; - _sntpLookup_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _sntpLookup_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Discovery Protocol - private string _discoveryProtocol_SelectedInterfaceId; - public string DiscoveryProtocol_InterfaceId + #region Discovery Protocol + private string _discoveryProtocol_SelectedInterfaceId; + public string DiscoveryProtocol_InterfaceId + { + get => _discoveryProtocol_SelectedInterfaceId; + set { - get => _discoveryProtocol_SelectedInterfaceId; - set - { - if (value == _discoveryProtocol_SelectedInterfaceId) - return; + if (value == _discoveryProtocol_SelectedInterfaceId) + return; - _discoveryProtocol_SelectedInterfaceId = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _discoveryProtocol_SelectedInterfaceId = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private DiscoveryProtocol.Protocol _discoveryProtocol_Protocol = GlobalStaticConfiguration.DiscoveryProtocol_Protocol; - public DiscoveryProtocol.Protocol DiscoveryProtocol_Protocol + private DiscoveryProtocol.Protocol _discoveryProtocol_Protocol = GlobalStaticConfiguration.DiscoveryProtocol_Protocol; + public DiscoveryProtocol.Protocol DiscoveryProtocol_Protocol + { + get => _discoveryProtocol_Protocol; + set { - get => _discoveryProtocol_Protocol; - set - { - if (value == _discoveryProtocol_Protocol) - return; + if (value == _discoveryProtocol_Protocol) + return; - _discoveryProtocol_Protocol = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _discoveryProtocol_Protocol = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private int _discoveryProtocol_Duration = GlobalStaticConfiguration.DiscoveryProtocol_Duration; - public int DiscoveryProtocol_Duration + private int _discoveryProtocol_Duration = GlobalStaticConfiguration.DiscoveryProtocol_Duration; + public int DiscoveryProtocol_Duration + { + get => _discoveryProtocol_Duration; + set { - get => _discoveryProtocol_Duration; - set - { - if (value == _discoveryProtocol_Duration) - return; + if (value == _discoveryProtocol_Duration) + return; - _discoveryProtocol_Duration = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _discoveryProtocol_Duration = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region WakeOnLAN - private int _wakeOnLAN_Port = GlobalStaticConfiguration.WakeOnLAN_Port; - public int WakeOnLAN_Port + #region WakeOnLAN + private int _wakeOnLAN_Port = GlobalStaticConfiguration.WakeOnLAN_Port; + public int WakeOnLAN_Port + { + get => _wakeOnLAN_Port; + set { - get => _wakeOnLAN_Port; - set - { - if (value == _wakeOnLAN_Port) - return; + if (value == _wakeOnLAN_Port) + return; - _wakeOnLAN_Port = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wakeOnLAN_Port = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _wakeOnLan_MACAddressHistory = new(); - public ObservableCollection WakeOnLan_MACAddressHistory + private ObservableCollection _wakeOnLan_MACAddressHistory = new(); + public ObservableCollection WakeOnLan_MACAddressHistory + { + get => _wakeOnLan_MACAddressHistory; + set { - get => _wakeOnLan_MACAddressHistory; - set - { - if (value == _wakeOnLan_MACAddressHistory) - return; + if (value == _wakeOnLan_MACAddressHistory) + return; - _wakeOnLan_MACAddressHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wakeOnLan_MACAddressHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _wakeOnLan_BroadcastHistory = new(); - public ObservableCollection WakeOnLan_BroadcastHistory + private ObservableCollection _wakeOnLan_BroadcastHistory = new(); + public ObservableCollection WakeOnLan_BroadcastHistory + { + get => _wakeOnLan_BroadcastHistory; + set { - get => _wakeOnLan_BroadcastHistory; - set - { - if (value == _wakeOnLan_BroadcastHistory) - return; + if (value == _wakeOnLan_BroadcastHistory) + return; - _wakeOnLan_BroadcastHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wakeOnLan_BroadcastHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _wakeOnLAN_ExpandProfileView = true; - public bool WakeOnLAN_ExpandProfileView + private bool _wakeOnLAN_ExpandProfileView = true; + public bool WakeOnLAN_ExpandProfileView + { + get => _wakeOnLAN_ExpandProfileView; + set { - get => _wakeOnLAN_ExpandProfileView; - set - { - if (value == _wakeOnLAN_ExpandProfileView) - return; + if (value == _wakeOnLAN_ExpandProfileView) + return; - _wakeOnLAN_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wakeOnLAN_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _wakeOnLAN_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double WakeOnLAN_ProfileWidth + private double _wakeOnLAN_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double WakeOnLAN_ProfileWidth + { + get => _wakeOnLAN_ProfileWidth; + set { - get => _wakeOnLAN_ProfileWidth; - set - { - if (Math.Abs(value - _wakeOnLAN_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _wakeOnLAN_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _wakeOnLAN_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _wakeOnLAN_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Subnet Calculator + #region Subnet Calculator - #region Calculator - private ObservableCollection _subnetCalculator_Calculator_SubnetHistory = new(); - public ObservableCollection SubnetCalculator_Calculator_SubnetHistory + #region Calculator + private ObservableCollection _subnetCalculator_Calculator_SubnetHistory = new(); + public ObservableCollection SubnetCalculator_Calculator_SubnetHistory + { + get => _subnetCalculator_Calculator_SubnetHistory; + set { - get => _subnetCalculator_Calculator_SubnetHistory; - set - { - if (value == _subnetCalculator_Calculator_SubnetHistory) - return; + if (value == _subnetCalculator_Calculator_SubnetHistory) + return; - _subnetCalculator_Calculator_SubnetHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _subnetCalculator_Calculator_SubnetHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Subnetting - private ObservableCollection _subnetCalculator_Subnetting_SubnetHistory = new(); - public ObservableCollection SubnetCalculator_Subnetting_SubnetHistory + #region Subnetting + private ObservableCollection _subnetCalculator_Subnetting_SubnetHistory = new(); + public ObservableCollection SubnetCalculator_Subnetting_SubnetHistory + { + get => _subnetCalculator_Subnetting_SubnetHistory; + set { - get => _subnetCalculator_Subnetting_SubnetHistory; - set - { - if (value == _subnetCalculator_Subnetting_SubnetHistory) - return; + if (value == _subnetCalculator_Subnetting_SubnetHistory) + return; - _subnetCalculator_Subnetting_SubnetHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _subnetCalculator_Subnetting_SubnetHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory = new(); - public ObservableCollection SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory + private ObservableCollection _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory = new(); + public ObservableCollection SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory + { + get => _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory; + set { - get => _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory; - set - { - if (value == _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory) - return; + if (value == _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory) + return; - _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _subnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _subnetCalculator_Subnetting_ExportFilePath; - public string SubnetCalculator_Subnetting_ExportFilePath + private string _subnetCalculator_Subnetting_ExportFilePath; + public string SubnetCalculator_Subnetting_ExportFilePath + { + get => _subnetCalculator_Subnetting_ExportFilePath; + set { - get => _subnetCalculator_Subnetting_ExportFilePath; - set - { - if (value == _subnetCalculator_Subnetting_ExportFilePath) - return; + if (value == _subnetCalculator_Subnetting_ExportFilePath) + return; - _subnetCalculator_Subnetting_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _subnetCalculator_Subnetting_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _subnetCalculator_Subnetting_ExportFileType = GlobalStaticConfiguration.SubnetCalculator_Subnetting_ExportFileType; - public ExportManager.ExportFileType SubnetCalculator_Subnetting_ExportFileType + private ExportManager.ExportFileType _subnetCalculator_Subnetting_ExportFileType = GlobalStaticConfiguration.SubnetCalculator_Subnetting_ExportFileType; + public ExportManager.ExportFileType SubnetCalculator_Subnetting_ExportFileType + { + get => _subnetCalculator_Subnetting_ExportFileType; + set { - get => _subnetCalculator_Subnetting_ExportFileType; - set - { - if (value == _subnetCalculator_Subnetting_ExportFileType) - return; + if (value == _subnetCalculator_Subnetting_ExportFileType) + return; - _subnetCalculator_Subnetting_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _subnetCalculator_Subnetting_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region WideSubnet - private ObservableCollection _subnetCalculator_WideSubnet_Subnet1 = new(); - public ObservableCollection SubnetCalculator_WideSubnet_Subnet1 + #region WideSubnet + private ObservableCollection _subnetCalculator_WideSubnet_Subnet1 = new(); + public ObservableCollection SubnetCalculator_WideSubnet_Subnet1 + { + get => _subnetCalculator_WideSubnet_Subnet1; + set { - get => _subnetCalculator_WideSubnet_Subnet1; - set - { - if (value == _subnetCalculator_WideSubnet_Subnet1) - return; + if (value == _subnetCalculator_WideSubnet_Subnet1) + return; - _subnetCalculator_WideSubnet_Subnet1 = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _subnetCalculator_WideSubnet_Subnet1 = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _subnetCalculator_WideSubnet_Subnet2 = new(); - public ObservableCollection SubnetCalculator_WideSubnet_Subnet2 + private ObservableCollection _subnetCalculator_WideSubnet_Subnet2 = new(); + public ObservableCollection SubnetCalculator_WideSubnet_Subnet2 + { + get => _subnetCalculator_WideSubnet_Subnet2; + set { - get => _subnetCalculator_WideSubnet_Subnet2; - set - { - if (value == _subnetCalculator_WideSubnet_Subnet2) - return; + if (value == _subnetCalculator_WideSubnet_Subnet2) + return; - _subnetCalculator_WideSubnet_Subnet2 = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _subnetCalculator_WideSubnet_Subnet2 = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #endregion + #endregion - #region Bit Calculator - private ObservableCollection _bitCalculator_InputHistory = new(); - public ObservableCollection BitCalculator_InputHistory + #region Bit Calculator + private ObservableCollection _bitCalculator_InputHistory = new(); + public ObservableCollection BitCalculator_InputHistory + { + get => _bitCalculator_InputHistory; + set { - get => _bitCalculator_InputHistory; - set - { - if (value == _bitCalculator_InputHistory) - return; + if (value == _bitCalculator_InputHistory) + return; - _bitCalculator_InputHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _bitCalculator_InputHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private BitCaluclatorUnit _bitCalculator_Unit = GlobalStaticConfiguration.BitCalculator_Unit; - public BitCaluclatorUnit BitCalculator_Unit + private BitCaluclatorUnit _bitCalculator_Unit = GlobalStaticConfiguration.BitCalculator_Unit; + public BitCaluclatorUnit BitCalculator_Unit + { + get => _bitCalculator_Unit; + set { - get => _bitCalculator_Unit; - set - { - if (value == _bitCalculator_Unit) - return; + if (value == _bitCalculator_Unit) + return; - _bitCalculator_Unit = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _bitCalculator_Unit = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private BitCaluclatorNotation _bitCalculator_Notation = GlobalStaticConfiguration.BitCalculator_Notation; - public BitCaluclatorNotation BitCalculator_Notation + private BitCaluclatorNotation _bitCalculator_Notation = GlobalStaticConfiguration.BitCalculator_Notation; + public BitCaluclatorNotation BitCalculator_Notation + { + get => _bitCalculator_Notation; + set { - get => _bitCalculator_Notation; - set - { - if (value == _bitCalculator_Notation) - return; + if (value == _bitCalculator_Notation) + return; - _bitCalculator_Notation = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _bitCalculator_Notation = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Lookup - private ObservableCollection _lookup_OUI_MACAddressOrVendorHistory = new(); - public ObservableCollection Lookup_OUI_MACAddressOrVendorHistory + #region Lookup + private ObservableCollection _lookup_OUI_MACAddressOrVendorHistory = new(); + public ObservableCollection Lookup_OUI_MACAddressOrVendorHistory + { + get => _lookup_OUI_MACAddressOrVendorHistory; + set { - get => _lookup_OUI_MACAddressOrVendorHistory; - set - { - if (value == _lookup_OUI_MACAddressOrVendorHistory) - return; + if (value == _lookup_OUI_MACAddressOrVendorHistory) + return; - _lookup_OUI_MACAddressOrVendorHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _lookup_OUI_MACAddressOrVendorHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _lookup_OUI_ExportFilePath; - public string Lookup_OUI_ExportFilePath + private string _lookup_OUI_ExportFilePath; + public string Lookup_OUI_ExportFilePath + { + get => _lookup_OUI_ExportFilePath; + set { - get => _lookup_OUI_ExportFilePath; - set - { - if (value == _lookup_OUI_ExportFilePath) - return; + if (value == _lookup_OUI_ExportFilePath) + return; - _lookup_OUI_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _lookup_OUI_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _lookup_OUI_ExportFileType = GlobalStaticConfiguration.Lookup_OUI_ExportFileType; - public ExportManager.ExportFileType Lookup_OUI_ExportFileType + private ExportManager.ExportFileType _lookup_OUI_ExportFileType = GlobalStaticConfiguration.Lookup_OUI_ExportFileType; + public ExportManager.ExportFileType Lookup_OUI_ExportFileType + { + get => _lookup_OUI_ExportFileType; + set { - get => _lookup_OUI_ExportFileType; - set - { - if (value == _lookup_OUI_ExportFileType) - return; + if (value == _lookup_OUI_ExportFileType) + return; - _lookup_OUI_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _lookup_OUI_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ObservableCollection _lookup_Port_PortsHistory = new(); - public ObservableCollection Lookup_Port_PortsHistory + private ObservableCollection _lookup_Port_PortsHistory = new(); + public ObservableCollection Lookup_Port_PortsHistory + { + get => _lookup_Port_PortsHistory; + set { - get => _lookup_Port_PortsHistory; - set - { - if (value == _lookup_Port_PortsHistory) - return; + if (value == _lookup_Port_PortsHistory) + return; - _lookup_Port_PortsHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _lookup_Port_PortsHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _lookup_Port_ExportFilePath; - public string Lookup_Port_ExportFilePath + private string _lookup_Port_ExportFilePath; + public string Lookup_Port_ExportFilePath + { + get => _lookup_Port_ExportFilePath; + set { - get => _lookup_Port_ExportFilePath; - set - { - if (value == _lookup_Port_ExportFilePath) - return; + if (value == _lookup_Port_ExportFilePath) + return; - _lookup_Port_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _lookup_Port_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _lookup_Port_ExportFileType = GlobalStaticConfiguration.Lookup_Port_ExportFileType; - public ExportManager.ExportFileType Lookup_Port_ExportFileType + private ExportManager.ExportFileType _lookup_Port_ExportFileType = GlobalStaticConfiguration.Lookup_Port_ExportFileType; + public ExportManager.ExportFileType Lookup_Port_ExportFileType + { + get => _lookup_Port_ExportFileType; + set { - get => _lookup_Port_ExportFileType; - set - { - if (value == _lookup_Port_ExportFileType) - return; + if (value == _lookup_Port_ExportFileType) + return; - _lookup_Port_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _lookup_Port_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Whois - private ObservableCollection _whois_DomainHistory = new(); - public ObservableCollection Whois_DomainHistory + #region Whois + private ObservableCollection _whois_DomainHistory = new(); + public ObservableCollection Whois_DomainHistory + { + get => _whois_DomainHistory; + set { - get => _whois_DomainHistory; - set - { - if (value == _whois_DomainHistory) - return; + if (value == _whois_DomainHistory) + return; - _whois_DomainHistory = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _whois_DomainHistory = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private bool _whois_ExpandProfileView = true; - public bool Whois_ExpandProfileView + private bool _whois_ExpandProfileView = true; + public bool Whois_ExpandProfileView + { + get => _whois_ExpandProfileView; + set { - get => _whois_ExpandProfileView; - set - { - if (value == _whois_ExpandProfileView) - return; + if (value == _whois_ExpandProfileView) + return; - _whois_ExpandProfileView = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _whois_ExpandProfileView = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private double _whois_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; - public double Whois_ProfileWidth + private double _whois_ProfileWidth = GlobalStaticConfiguration.Profile_DefaultWidthExpanded; + public double Whois_ProfileWidth + { + get => _whois_ProfileWidth; + set { - get => _whois_ProfileWidth; - set - { - if (Math.Abs(value - _whois_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) - return; + if (Math.Abs(value - _whois_ProfileWidth) < GlobalStaticConfiguration.FloatPointFix) + return; - _whois_ProfileWidth = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _whois_ProfileWidth = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _whois_ExportFilePath; - public string Whois_ExportFilePath + private string _whois_ExportFilePath; + public string Whois_ExportFilePath + { + get => _whois_ExportFilePath; + set { - get => _whois_ExportFilePath; - set - { - if (value == _whois_ExportFilePath) - return; + if (value == _whois_ExportFilePath) + return; - _whois_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _whois_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _whois_ExportFileType = GlobalStaticConfiguration.Whois_ExportFileType; - public ExportManager.ExportFileType Whois_ExportFileType + private ExportManager.ExportFileType _whois_ExportFileType = GlobalStaticConfiguration.Whois_ExportFileType; + public ExportManager.ExportFileType Whois_ExportFileType + { + get => _whois_ExportFileType; + set { - get => _whois_ExportFileType; - set - { - if (value == _whois_ExportFileType) - return; + if (value == _whois_ExportFileType) + return; - _whois_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _whois_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Connections - private bool _connections_AutoRefresh; - public bool Connections_AutoRefresh + #region Connections + private bool _connections_AutoRefresh; + public bool Connections_AutoRefresh + { + get => _connections_AutoRefresh; + set { - get => _connections_AutoRefresh; - set - { - if (value == _connections_AutoRefresh) - return; + if (value == _connections_AutoRefresh) + return; - _connections_AutoRefresh = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _connections_AutoRefresh = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private AutoRefreshTimeInfo _connections_AutoRefreshTime = GlobalStaticConfiguration.Connections_AutoRefreshTime; - public AutoRefreshTimeInfo Connections_AutoRefreshTime + private AutoRefreshTimeInfo _connections_AutoRefreshTime = GlobalStaticConfiguration.Connections_AutoRefreshTime; + public AutoRefreshTimeInfo Connections_AutoRefreshTime + { + get => _connections_AutoRefreshTime; + set { - get => _connections_AutoRefreshTime; - set - { - if (value == _connections_AutoRefreshTime) - return; + if (value == _connections_AutoRefreshTime) + return; - _connections_AutoRefreshTime = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _connections_AutoRefreshTime = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _connections_ExportFilePath; - public string Connections_ExportFilePath + private string _connections_ExportFilePath; + public string Connections_ExportFilePath + { + get => _connections_ExportFilePath; + set { - get => _connections_ExportFilePath; - set - { - if (value == _connections_ExportFilePath) - return; + if (value == _connections_ExportFilePath) + return; - _connections_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _connections_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _connections_ExportFileType = GlobalStaticConfiguration.Connections_ExportFileType; - public ExportManager.ExportFileType Connections_ExportFileType + private ExportManager.ExportFileType _connections_ExportFileType = GlobalStaticConfiguration.Connections_ExportFileType; + public ExportManager.ExportFileType Connections_ExportFileType + { + get => _connections_ExportFileType; + set { - get => _connections_ExportFileType; - set - { - if (value == _connections_ExportFileType) - return; + if (value == _connections_ExportFileType) + return; - _connections_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _connections_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region Listeners - private bool _listeners_AutoRefresh; - public bool Listeners_AutoRefresh + #region Listeners + private bool _listeners_AutoRefresh; + public bool Listeners_AutoRefresh + { + get => _listeners_AutoRefresh; + set { - get => _listeners_AutoRefresh; - set - { - if (value == _listeners_AutoRefresh) - return; + if (value == _listeners_AutoRefresh) + return; - _listeners_AutoRefresh = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _listeners_AutoRefresh = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private AutoRefreshTimeInfo _listeners_AutoRefreshTime = GlobalStaticConfiguration.Listeners_AutoRefreshTime; - public AutoRefreshTimeInfo Listeners_AutoRefreshTime + private AutoRefreshTimeInfo _listeners_AutoRefreshTime = GlobalStaticConfiguration.Listeners_AutoRefreshTime; + public AutoRefreshTimeInfo Listeners_AutoRefreshTime + { + get => _listeners_AutoRefreshTime; + set { - get => _listeners_AutoRefreshTime; - set - { - if (value == _listeners_AutoRefreshTime) - return; + if (value == _listeners_AutoRefreshTime) + return; - _listeners_AutoRefreshTime = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _listeners_AutoRefreshTime = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _listeners_ExportFilePath; - public string Listeners_ExportFilePath + private string _listeners_ExportFilePath; + public string Listeners_ExportFilePath + { + get => _listeners_ExportFilePath; + set { - get => _listeners_ExportFilePath; - set - { - if (value == _listeners_ExportFilePath) - return; + if (value == _listeners_ExportFilePath) + return; - _listeners_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _listeners_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _listeners_ExportFileType = GlobalStaticConfiguration.Listeners_ExportFileType; - public ExportManager.ExportFileType Listeners_ExportFileType + private ExportManager.ExportFileType _listeners_ExportFileType = GlobalStaticConfiguration.Listeners_ExportFileType; + public ExportManager.ExportFileType Listeners_ExportFileType + { + get => _listeners_ExportFileType; + set { - get => _listeners_ExportFileType; - set - { - if (value == _listeners_ExportFileType) - return; + if (value == _listeners_ExportFileType) + return; - _listeners_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _listeners_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #region ARPTable - private bool _arpTable_AutoRefresh; - public bool ARPTable_AutoRefresh + #region ARPTable + private bool _arpTable_AutoRefresh; + public bool ARPTable_AutoRefresh + { + get => _arpTable_AutoRefresh; + set { - get => _arpTable_AutoRefresh; - set - { - if (value == _arpTable_AutoRefresh) - return; + if (value == _arpTable_AutoRefresh) + return; - _arpTable_AutoRefresh = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _arpTable_AutoRefresh = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private AutoRefreshTimeInfo _arpTable_AutoRefreshTime = GlobalStaticConfiguration.ARPTable_AutoRefreshTime; - public AutoRefreshTimeInfo ARPTable_AutoRefreshTime + private AutoRefreshTimeInfo _arpTable_AutoRefreshTime = GlobalStaticConfiguration.ARPTable_AutoRefreshTime; + public AutoRefreshTimeInfo ARPTable_AutoRefreshTime + { + get => _arpTable_AutoRefreshTime; + set { - get => _arpTable_AutoRefreshTime; - set - { - if (value == _arpTable_AutoRefreshTime) - return; + if (value == _arpTable_AutoRefreshTime) + return; - _arpTable_AutoRefreshTime = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _arpTable_AutoRefreshTime = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private string _arpTable_ExportFilePath; - public string ARPTable_ExportFilePath + private string _arpTable_ExportFilePath; + public string ARPTable_ExportFilePath + { + get => _arpTable_ExportFilePath; + set { - get => _arpTable_ExportFilePath; - set - { - if (value == _arpTable_ExportFilePath) - return; + if (value == _arpTable_ExportFilePath) + return; - _arpTable_ExportFilePath = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _arpTable_ExportFilePath = value; + OnPropertyChanged(); + SettingsChanged = true; } + } - private ExportManager.ExportFileType _arpTable_ExportFileType = GlobalStaticConfiguration.ARPTable_ExportFileType; - public ExportManager.ExportFileType ARPTable_ExportFileType + private ExportManager.ExportFileType _arpTable_ExportFileType = GlobalStaticConfiguration.ARPTable_ExportFileType; + public ExportManager.ExportFileType ARPTable_ExportFileType + { + get => _arpTable_ExportFileType; + set { - get => _arpTable_ExportFileType; - set - { - if (value == _arpTable_ExportFileType) - return; + if (value == _arpTable_ExportFileType) + return; - _arpTable_ExportFileType = value; - OnPropertyChanged(); - SettingsChanged = true; - } + _arpTable_ExportFileType = value; + OnPropertyChanged(); + SettingsChanged = true; } - #endregion + } + #endregion - #endregion + #endregion - #region Constructor - public SettingsInfo() - { - // General - General_ApplicationList.CollectionChanged += CollectionChanged; + #region Constructor + public SettingsInfo() + { + // General + General_ApplicationList.CollectionChanged += CollectionChanged; - // IP Scanner - IPScanner_HostsHistory.CollectionChanged += CollectionChanged; - IPScanner_CustomCommands.CollectionChanged += CollectionChanged; + // IP Scanner + IPScanner_HostsHistory.CollectionChanged += CollectionChanged; + IPScanner_CustomCommands.CollectionChanged += CollectionChanged; - // Port Scanner - PortScanner_HostsHistory.CollectionChanged += CollectionChanged; - PortScanner_PortsHistory.CollectionChanged += CollectionChanged; - PortScanner_PortProfiles.CollectionChanged += CollectionChanged; + // Port Scanner + PortScanner_HostsHistory.CollectionChanged += CollectionChanged; + PortScanner_PortsHistory.CollectionChanged += CollectionChanged; + PortScanner_PortProfiles.CollectionChanged += CollectionChanged; - // Ping Monitor - PingMonitor_HostHistory.CollectionChanged += CollectionChanged; + // Ping Monitor + PingMonitor_HostHistory.CollectionChanged += CollectionChanged; - // Traceroute - Traceroute_HostHistory.CollectionChanged += CollectionChanged; + // Traceroute + Traceroute_HostHistory.CollectionChanged += CollectionChanged; - // DNS Lookup - DNSLookup_HostHistory.CollectionChanged += CollectionChanged; - DNSLookup_DNSServers_v2.CollectionChanged += CollectionChanged; + // DNS Lookup + DNSLookup_HostHistory.CollectionChanged += CollectionChanged; + DNSLookup_DNSServers_v2.CollectionChanged += CollectionChanged; - // Remote Desktop - RemoteDesktop_HostHistory.CollectionChanged += CollectionChanged; + // Remote Desktop + RemoteDesktop_HostHistory.CollectionChanged += CollectionChanged; - // PowerShell - PowerShell_HostHistory.CollectionChanged += CollectionChanged; + // PowerShell + PowerShell_HostHistory.CollectionChanged += CollectionChanged; - // PuTTY - PuTTY_HostHistory.CollectionChanged += CollectionChanged; - PuTTY_SerialLineHistory.CollectionChanged += CollectionChanged; - PuTTY_PortHistory.CollectionChanged += CollectionChanged; - PuTTY_BaudHistory.CollectionChanged += CollectionChanged; - PuTTY_UsernameHistory.CollectionChanged += CollectionChanged; - PuTTY_PrivateKeyFileHistory.CollectionChanged += CollectionChanged; - PuTTY_ProfileHistory.CollectionChanged += CollectionChanged; + // PuTTY + PuTTY_HostHistory.CollectionChanged += CollectionChanged; + PuTTY_SerialLineHistory.CollectionChanged += CollectionChanged; + PuTTY_PortHistory.CollectionChanged += CollectionChanged; + PuTTY_BaudHistory.CollectionChanged += CollectionChanged; + PuTTY_UsernameHistory.CollectionChanged += CollectionChanged; + PuTTY_PrivateKeyFileHistory.CollectionChanged += CollectionChanged; + PuTTY_ProfileHistory.CollectionChanged += CollectionChanged; - // AWSSessionManager - AWSSessionManager_InstanceIDHistory.CollectionChanged += CollectionChanged; - AWSSessionManager_AWSProfiles.CollectionChanged += CollectionChanged; + // AWSSessionManager + AWSSessionManager_InstanceIDHistory.CollectionChanged += CollectionChanged; + AWSSessionManager_AWSProfiles.CollectionChanged += CollectionChanged; - // TigerVNC - TigerVNC_HostHistory.CollectionChanged += CollectionChanged; - TigerVNC_PortHistory.CollectionChanged += CollectionChanged; + // TigerVNC + TigerVNC_HostHistory.CollectionChanged += CollectionChanged; + TigerVNC_PortHistory.CollectionChanged += CollectionChanged; - // WebConsole - WebConsole_UrlHistory.CollectionChanged += CollectionChanged; + // WebConsole + WebConsole_UrlHistory.CollectionChanged += CollectionChanged; - // SNMP - SNMP_HostHistory.CollectionChanged += CollectionChanged; - SNMP_OIDHistory.CollectionChanged += CollectionChanged; + // SNMP + SNMP_HostHistory.CollectionChanged += CollectionChanged; + SNMP_OIDHistory.CollectionChanged += CollectionChanged; - // SNTP Lookup - SNTPLookup_SNTPServers.CollectionChanged += CollectionChanged; + // SNTP Lookup + SNTPLookup_SNTPServers.CollectionChanged += CollectionChanged; - // Wake on LAN - WakeOnLan_MACAddressHistory.CollectionChanged += CollectionChanged; - WakeOnLan_BroadcastHistory.CollectionChanged += CollectionChanged; + // Wake on LAN + WakeOnLan_MACAddressHistory.CollectionChanged += CollectionChanged; + WakeOnLan_BroadcastHistory.CollectionChanged += CollectionChanged; - // Subnet Calculator / Calculator - SubnetCalculator_Calculator_SubnetHistory.CollectionChanged += CollectionChanged; + // Subnet Calculator / Calculator + SubnetCalculator_Calculator_SubnetHistory.CollectionChanged += CollectionChanged; - // Subnet Calculator / Subnetting - SubnetCalculator_Subnetting_SubnetHistory.CollectionChanged += CollectionChanged; - SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.CollectionChanged += CollectionChanged; + // Subnet Calculator / Subnetting + SubnetCalculator_Subnetting_SubnetHistory.CollectionChanged += CollectionChanged; + SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.CollectionChanged += CollectionChanged; - // Subnet Calculator / Supernetting - SubnetCalculator_WideSubnet_Subnet1.CollectionChanged += CollectionChanged; - SubnetCalculator_WideSubnet_Subnet2.CollectionChanged += CollectionChanged; + // Subnet Calculator / Supernetting + SubnetCalculator_WideSubnet_Subnet1.CollectionChanged += CollectionChanged; + SubnetCalculator_WideSubnet_Subnet2.CollectionChanged += CollectionChanged; - // Lookup / OUI - Lookup_OUI_MACAddressOrVendorHistory.CollectionChanged += CollectionChanged; + // Lookup / OUI + Lookup_OUI_MACAddressOrVendorHistory.CollectionChanged += CollectionChanged; - // Lookup / Port - Lookup_Port_PortsHistory.CollectionChanged += CollectionChanged; + // Lookup / Port + Lookup_Port_PortsHistory.CollectionChanged += CollectionChanged; - // Whois - Whois_DomainHistory.CollectionChanged += CollectionChanged; - } + // Whois + Whois_DomainHistory.CollectionChanged += CollectionChanged; + } - private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) - { - SettingsChanged = true; - } - #endregion + private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + { + SettingsChanged = true; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager.Settings/SettingsViewGroup.cs b/Source/NETworkManager.Settings/SettingsViewGroup.cs index 3219f1401e..7ae31cf0b9 100644 --- a/Source/NETworkManager.Settings/SettingsViewGroup.cs +++ b/Source/NETworkManager.Settings/SettingsViewGroup.cs @@ -1,8 +1,7 @@ -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public enum SettingsViewGroup { - public enum SettingsViewGroup - { - General, - Applications - } + General, + Applications } diff --git a/Source/NETworkManager.Settings/SettingsViewInfo.cs b/Source/NETworkManager.Settings/SettingsViewInfo.cs index 98bec38395..8cafb14200 100644 --- a/Source/NETworkManager.Settings/SettingsViewInfo.cs +++ b/Source/NETworkManager.Settings/SettingsViewInfo.cs @@ -1,32 +1,31 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public class SettingsViewInfo { - public class SettingsViewInfo - { - public SettingsViewName Name { get; set; } - public Canvas Icon { get; set; } - public SettingsViewGroup Group { get; set; } + public SettingsViewName Name { get; set; } + public Canvas Icon { get; set; } + public SettingsViewGroup Group { get; set; } - public SettingsViewInfo() - { - } + public SettingsViewInfo() + { + } - public SettingsViewInfo(SettingsViewName name, Canvas icon, SettingsViewGroup group) - { - Name = name; - Icon = icon; - Group = group; - } + public SettingsViewInfo(SettingsViewName name, Canvas icon, SettingsViewGroup group) + { + Name = name; + Icon = icon; + Group = group; + } - public SettingsViewInfo(SettingsViewName name, UIElement uiElement, SettingsViewGroup group) - { - Name = name; - var canvas = new Canvas(); - canvas.Children.Add(uiElement); - Icon = canvas; - Group = group; - } + public SettingsViewInfo(SettingsViewName name, UIElement uiElement, SettingsViewGroup group) + { + Name = name; + var canvas = new Canvas(); + canvas.Children.Add(uiElement); + Icon = canvas; + Group = group; } } \ No newline at end of file diff --git a/Source/NETworkManager.Settings/SettingsViewManager.cs b/Source/NETworkManager.Settings/SettingsViewManager.cs index add5459cd8..efb84b223f 100644 --- a/Source/NETworkManager.Settings/SettingsViewManager.cs +++ b/Source/NETworkManager.Settings/SettingsViewManager.cs @@ -2,44 +2,43 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public static class SettingsViewManager { - public static class SettingsViewManager + // List of all applications + public static List List => new() { - // List of all applications - public static List List => new() - { - // General - new SettingsViewInfo(SettingsViewName.General, new PackIconModern{ Kind = PackIconModernKind.Layer }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Window, new PackIconOcticons { Kind = PackIconOcticonsKind.Browser }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Appearance, new PackIconMaterial { Kind = PackIconMaterialKind.Palette }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Language, new PackIconMaterial { Kind = PackIconMaterialKind.Translate }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Network, new PackIconModern { Kind = PackIconModernKind.Network }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Status, new PackIconMaterial { Kind = PackIconMaterialKind.Pulse }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.HotKeys, new PackIconOcticons { Kind = PackIconOcticonsKind.Keyboard }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Autostart, new PackIconMaterial { Kind = PackIconMaterialKind.Power }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Update, new PackIconMaterial { Kind = PackIconMaterialKind.RocketLaunchOutline }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Profiles, new PackIconFontAwesome { Kind = PackIconFontAwesomeKind.ServerSolid }, SettingsViewGroup.General), - new SettingsViewInfo(SettingsViewName.Settings, new PackIconMaterialLight { Kind = PackIconMaterialLightKind.Cog }, SettingsViewGroup.General), - - // Applications - new SettingsViewInfo(SettingsViewName.Dashboard, ApplicationManager.GetIcon(ApplicationName.Dashboard), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.IPScanner, ApplicationManager.GetIcon(ApplicationName.IPScanner), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.PortScanner, ApplicationManager.GetIcon(ApplicationName.PortScanner), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.PingMonitor, ApplicationManager.GetIcon(ApplicationName.PingMonitor), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.Traceroute, ApplicationManager.GetIcon(ApplicationName.Traceroute), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.DNSLookup, ApplicationManager.GetIcon(ApplicationName.DNSLookup), SettingsViewGroup.Applications ), - new SettingsViewInfo(SettingsViewName.RemoteDesktop, ApplicationManager.GetIcon(ApplicationName.RemoteDesktop), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.PowerShell, ApplicationManager.GetIcon(ApplicationName.PowerShell), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.PuTTY, ApplicationManager.GetIcon(ApplicationName.PuTTY), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.AWSSessionManager, ApplicationManager.GetIcon(ApplicationName.AWSSessionManager), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.TigerVNC, ApplicationManager.GetIcon(ApplicationName.TigerVNC), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.SNMP, ApplicationManager.GetIcon(ApplicationName.SNMP), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.SNTPLookup, ApplicationManager.GetIcon(ApplicationName.SNTPLookup), SettingsViewGroup.Applications), - new SettingsViewInfo(SettingsViewName.WakeOnLAN, ApplicationManager.GetIcon(ApplicationName.WakeOnLAN), SettingsViewGroup.Applications), - // new SettingsViewInfo(SettingsViewName.Whois, ApplicationManager.GetIcon(ApplicationName.Whois), SettingsViewGroup.Applications) - new SettingsViewInfo(SettingsViewName.BitCalculator, ApplicationManager.GetIcon(ApplicationName.BitCalculator), SettingsViewGroup.Applications), - }; - } + // General + new SettingsViewInfo(SettingsViewName.General, new PackIconModern{ Kind = PackIconModernKind.Layer }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Window, new PackIconOcticons { Kind = PackIconOcticonsKind.Browser }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Appearance, new PackIconMaterial { Kind = PackIconMaterialKind.Palette }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Language, new PackIconMaterial { Kind = PackIconMaterialKind.Translate }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Network, new PackIconModern { Kind = PackIconModernKind.Network }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Status, new PackIconMaterial { Kind = PackIconMaterialKind.Pulse }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.HotKeys, new PackIconOcticons { Kind = PackIconOcticonsKind.Keyboard }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Autostart, new PackIconMaterial { Kind = PackIconMaterialKind.Power }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Update, new PackIconMaterial { Kind = PackIconMaterialKind.RocketLaunchOutline }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Profiles, new PackIconFontAwesome { Kind = PackIconFontAwesomeKind.ServerSolid }, SettingsViewGroup.General), + new SettingsViewInfo(SettingsViewName.Settings, new PackIconMaterialLight { Kind = PackIconMaterialLightKind.Cog }, SettingsViewGroup.General), + + // Applications + new SettingsViewInfo(SettingsViewName.Dashboard, ApplicationManager.GetIcon(ApplicationName.Dashboard), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.IPScanner, ApplicationManager.GetIcon(ApplicationName.IPScanner), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.PortScanner, ApplicationManager.GetIcon(ApplicationName.PortScanner), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.PingMonitor, ApplicationManager.GetIcon(ApplicationName.PingMonitor), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.Traceroute, ApplicationManager.GetIcon(ApplicationName.Traceroute), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.DNSLookup, ApplicationManager.GetIcon(ApplicationName.DNSLookup), SettingsViewGroup.Applications ), + new SettingsViewInfo(SettingsViewName.RemoteDesktop, ApplicationManager.GetIcon(ApplicationName.RemoteDesktop), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.PowerShell, ApplicationManager.GetIcon(ApplicationName.PowerShell), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.PuTTY, ApplicationManager.GetIcon(ApplicationName.PuTTY), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.AWSSessionManager, ApplicationManager.GetIcon(ApplicationName.AWSSessionManager), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.TigerVNC, ApplicationManager.GetIcon(ApplicationName.TigerVNC), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.SNMP, ApplicationManager.GetIcon(ApplicationName.SNMP), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.SNTPLookup, ApplicationManager.GetIcon(ApplicationName.SNTPLookup), SettingsViewGroup.Applications), + new SettingsViewInfo(SettingsViewName.WakeOnLAN, ApplicationManager.GetIcon(ApplicationName.WakeOnLAN), SettingsViewGroup.Applications), + // new SettingsViewInfo(SettingsViewName.Whois, ApplicationManager.GetIcon(ApplicationName.Whois), SettingsViewGroup.Applications) + new SettingsViewInfo(SettingsViewName.BitCalculator, ApplicationManager.GetIcon(ApplicationName.BitCalculator), SettingsViewGroup.Applications), + }; } diff --git a/Source/NETworkManager.Settings/SettingsViewName.cs b/Source/NETworkManager.Settings/SettingsViewName.cs index dd926bdbf2..732a8b09ae 100644 --- a/Source/NETworkManager.Settings/SettingsViewName.cs +++ b/Source/NETworkManager.Settings/SettingsViewName.cs @@ -1,33 +1,32 @@ -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +public enum SettingsViewName { - public enum SettingsViewName - { - General, - Window, - Appearance, - Language, - Network, - Status, - HotKeys, - Autostart, - Update, - Profiles, - Settings, - Dashboard, - IPScanner, - PortScanner, - PingMonitor, - Traceroute, - DNSLookup, - RemoteDesktop, - PowerShell, - PuTTY, - AWSSessionManager, - TigerVNC, - SNMP, - SNTPLookup, - WakeOnLAN, - //Whois, - BitCalculator - } + General, + Window, + Appearance, + Language, + Network, + Status, + HotKeys, + Autostart, + Update, + Profiles, + Settings, + Dashboard, + IPScanner, + PortScanner, + PingMonitor, + Traceroute, + DNSLookup, + RemoteDesktop, + PowerShell, + PuTTY, + AWSSessionManager, + TigerVNC, + SNMP, + SNTPLookup, + WakeOnLAN, + //Whois, + BitCalculator } diff --git a/Source/NETworkManager.Settings/ThemeColorInfo.cs b/Source/NETworkManager.Settings/ThemeColorInfo.cs index 639a5295bf..2eea958064 100644 --- a/Source/NETworkManager.Settings/ThemeColorInfo.cs +++ b/Source/NETworkManager.Settings/ThemeColorInfo.cs @@ -1,9 +1,9 @@ -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +/// +/// Class contains informations about MahApps.Metro themes. +/// +public class ThemeColorInfo : BaseColorInfo { - /// - /// Class contains informations about MahApps.Metro themes. - /// - public class ThemeColorInfo : BaseColorInfo - { - } + } diff --git a/Source/NETworkManager.Settings/ThemeInfo.cs b/Source/NETworkManager.Settings/ThemeInfo.cs index 6d9b3f1d04..9f0654f7f7 100644 --- a/Source/NETworkManager.Settings/ThemeInfo.cs +++ b/Source/NETworkManager.Settings/ThemeInfo.cs @@ -1,30 +1,29 @@  -namespace NETworkManager.Settings +namespace NETworkManager.Settings; + +/// +/// Class contains informations about MahApps.Metro custom themes. +/// +public class ThemeInfo { /// - /// Class contains informations about MahApps.Metro custom themes. + /// Name of the MahApps.Metro custom theme. /// - public class ThemeInfo - { - /// - /// Name of the MahApps.Metro custom theme. - /// - public string Name { get; set; } + public string Name { get; set; } - /// - /// Display name of the MahApps.Metro custom theme. - /// - public string DisplayName { get; set; } + /// + /// Display name of the MahApps.Metro custom theme. + /// + public string DisplayName { get; set; } - /// - /// Initializes a new instance of the class with properties. - /// - /// Name of of the MahApps.Metro custom theme. - /// Display name of the MahApps.Metro custom theme. - public ThemeInfo(string name, string displayName) - { - Name = name; - DisplayName = displayName; - } + /// + /// Initializes a new instance of the class with properties. + /// + /// Name of of the MahApps.Metro custom theme. + /// Display name of the MahApps.Metro custom theme. + public ThemeInfo(string name, string displayName) + { + Name = name; + DisplayName = displayName; } } diff --git a/Source/NETworkManager.Update/UpdateAvailableArgs.cs b/Source/NETworkManager.Update/UpdateAvailableArgs.cs index 7e0996556b..e4144b59ae 100644 --- a/Source/NETworkManager.Update/UpdateAvailableArgs.cs +++ b/Source/NETworkManager.Update/UpdateAvailableArgs.cs @@ -1,25 +1,24 @@ using Octokit; using System; -namespace NETworkManager.Update +namespace NETworkManager.Update; + +/// +/// Contains informations about a program update. +/// +public class UpdateAvailableArgs : EventArgs { /// - /// Contains informations about a program update. + /// Release of the program update. /// - public class UpdateAvailableArgs : EventArgs - { - /// - /// Release of the program update. - /// - public Release Release { get; private set; } + public Release Release { get; private set; } - /// - /// Initializes a new instance of the class and passes the as paramter. - /// - /// Release of the program update. - public UpdateAvailableArgs(Release release) - { - Release = release; - } + /// + /// Initializes a new instance of the class and passes the as paramter. + /// + /// Release of the program update. + public UpdateAvailableArgs(Release release) + { + Release = release; } } From 66839acab3a3a492ede96e638f25a40896c5b5c8 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:25:57 +0100 Subject: [PATCH 05/11] Chore: Use .NET 7 syntax --- .../Application/AWSSessionManager.cs | 29 +- .../Application/PowerShell.cs | 35 +- .../Application/PuTTY.cs | 43 +- .../Application/RemoteDesktop.cs | 385 +++++---- .../Application/TigerVNC.cs | 23 +- .../Application/WakeOnLan.cs | 21 +- .../Application/WebConsole.cs | 21 +- .../NETworkManager.Profiles/GroupEditMode.cs | 11 +- Source/NETworkManager.Profiles/GroupInfo.cs | 443 ++++++----- .../GroupInfoSerializable.cs | 33 +- .../NETworkManager.Profiles/GroupViewInfo.cs | 39 +- .../GroupViewManager.cs | 29 +- .../NETworkManager.Profiles/GroupViewName.cs | 19 +- .../IProfileManager.cs | 19 +- .../IProfileManagerMinimal.cs | 27 +- .../ProfileEditMode.cs | 13 +- .../ProfileFileInfo.cs | 120 ++- .../ProfileFileInfoArgs.cs | 15 +- Source/NETworkManager.Profiles/ProfileInfo.cs | 739 +++++++++--------- .../ProfileInfoSerializable.cs | 27 +- .../ProfileViewInfo.cs | 39 +- .../ProfileViewName.cs | 37 +- 22 files changed, 1072 insertions(+), 1095 deletions(-) diff --git a/Source/NETworkManager.Profiles/Application/AWSSessionManager.cs b/Source/NETworkManager.Profiles/Application/AWSSessionManager.cs index 4d31a61999..8f24c162aa 100644 --- a/Source/NETworkManager.Profiles/Application/AWSSessionManager.cs +++ b/Source/NETworkManager.Profiles/Application/AWSSessionManager.cs @@ -1,21 +1,20 @@ using NETworkManager.Models.AWS; using NETworkManager.Settings; -namespace NETworkManager.Profiles.Application -{ - public class AWSSessionManager - { - public static AWSSessionManagerSessionInfo CreateSessionInfo(ProfileInfo profile) - { - // Get group info - GroupInfo group = ProfileManager.GetGroup(profile.Group); +namespace NETworkManager.Profiles.Application; - return new AWSSessionManagerSessionInfo - { - InstanceID = profile.AWSSessionManager_InstanceID, - Profile = profile.AWSSessionManager_OverrideProfile ? profile.AWSSessionManager_Profile : (group.AWSSessionManager_OverrideProfile ? group.AWSSessionManager_Profile : SettingsManager.Current.AWSSessionManager_DefaultProfile), - Region = profile.AWSSessionManager_OverrideRegion ? profile.AWSSessionManager_Region : (group.AWSSessionManager_OverrideRegion ? group.AWSSessionManager_Region : SettingsManager.Current.AWSSessionManager_DefaultRegion) - }; - } +public class AWSSessionManager +{ + public static AWSSessionManagerSessionInfo CreateSessionInfo(ProfileInfo profile) + { + // Get group info + GroupInfo group = ProfileManager.GetGroup(profile.Group); + + return new AWSSessionManagerSessionInfo + { + InstanceID = profile.AWSSessionManager_InstanceID, + Profile = profile.AWSSessionManager_OverrideProfile ? profile.AWSSessionManager_Profile : (group.AWSSessionManager_OverrideProfile ? group.AWSSessionManager_Profile : SettingsManager.Current.AWSSessionManager_DefaultProfile), + Region = profile.AWSSessionManager_OverrideRegion ? profile.AWSSessionManager_Region : (group.AWSSessionManager_OverrideRegion ? group.AWSSessionManager_Region : SettingsManager.Current.AWSSessionManager_DefaultRegion) + }; } } diff --git a/Source/NETworkManager.Profiles/Application/PowerShell.cs b/Source/NETworkManager.Profiles/Application/PowerShell.cs index 501f0f27a0..89c6f7828c 100644 --- a/Source/NETworkManager.Profiles/Application/PowerShell.cs +++ b/Source/NETworkManager.Profiles/Application/PowerShell.cs @@ -1,24 +1,23 @@ using NETworkManager.Models.PowerShell; using NETworkManager.Settings; -namespace NETworkManager.Profiles.Application -{ - public class PowerShell - { - public static PowerShellSessionInfo CreateSessionInfo(ProfileInfo profile) - { - // Get group info - GroupInfo group = ProfileManager.GetGroup(profile.Group); +namespace NETworkManager.Profiles.Application; - return new PowerShellSessionInfo - { - EnableRemoteConsole = profile.PowerShell_EnableRemoteConsole, - Host = profile.PowerShell_Host, - - Command = profile.PowerShell_OverrideCommand ? profile.PowerShell_Command : (group.PowerShell_OverrideCommand ? group.PowerShell_Command : SettingsManager.Current.PowerShell_Command), - AdditionalCommandLine = profile.PowerShell_OverrideAdditionalCommandLine ? profile.PowerShell_AdditionalCommandLine : (group.PowerShell_OverrideAdditionalCommandLine ? group.PowerShell_AdditionalCommandLine : SettingsManager.Current.PowerShell_AdditionalCommandLine), - ExecutionPolicy = profile.PowerShell_OverrideExecutionPolicy ? profile.PowerShell_ExecutionPolicy : (group.PowerShell_OverrideExecutionPolicy ? group.PowerShell_ExecutionPolicy : SettingsManager.Current.PowerShell_ExecutionPolicy) - }; - } +public class PowerShell +{ + public static PowerShellSessionInfo CreateSessionInfo(ProfileInfo profile) + { + // Get group info + GroupInfo group = ProfileManager.GetGroup(profile.Group); + + return new PowerShellSessionInfo + { + EnableRemoteConsole = profile.PowerShell_EnableRemoteConsole, + Host = profile.PowerShell_Host, + + Command = profile.PowerShell_OverrideCommand ? profile.PowerShell_Command : (group.PowerShell_OverrideCommand ? group.PowerShell_Command : SettingsManager.Current.PowerShell_Command), + AdditionalCommandLine = profile.PowerShell_OverrideAdditionalCommandLine ? profile.PowerShell_AdditionalCommandLine : (group.PowerShell_OverrideAdditionalCommandLine ? group.PowerShell_AdditionalCommandLine : SettingsManager.Current.PowerShell_AdditionalCommandLine), + ExecutionPolicy = profile.PowerShell_OverrideExecutionPolicy ? profile.PowerShell_ExecutionPolicy : (group.PowerShell_OverrideExecutionPolicy ? group.PowerShell_ExecutionPolicy : SettingsManager.Current.PowerShell_ExecutionPolicy) + }; } } diff --git a/Source/NETworkManager.Profiles/Application/PuTTY.cs b/Source/NETworkManager.Profiles/Application/PuTTY.cs index 76e7a8ef47..c623393cc7 100644 --- a/Source/NETworkManager.Profiles/Application/PuTTY.cs +++ b/Source/NETworkManager.Profiles/Application/PuTTY.cs @@ -1,32 +1,31 @@ using NETworkManager.Models.PuTTY; using NETworkManager.Settings; -namespace NETworkManager.Profiles.Application +namespace NETworkManager.Profiles.Application; + +public static class PuTTY { - public static class PuTTY + public static PuTTYSessionInfo CreateSessionInfo(ProfileInfo profile) { - public static PuTTYSessionInfo CreateSessionInfo(ProfileInfo profile) - { - // Get group info - GroupInfo group = ProfileManager.GetGroup(profile.Group); + // Get group info + GroupInfo group = ProfileManager.GetGroup(profile.Group); - return new PuTTYSessionInfo - { - Mode = profile.PuTTY_ConnectionMode, - HostOrSerialLine = profile.PuTTY_HostOrSerialLine, + return new PuTTYSessionInfo + { + Mode = profile.PuTTY_ConnectionMode, + HostOrSerialLine = profile.PuTTY_HostOrSerialLine, - PortOrBaud = profile.PuTTY_OverridePortOrBaud ? profile.PuTTY_PortOrBaud : Settings.Application.PuTTY.GetPortOrBaudByConnectionMode(profile.PuTTY_ConnectionMode), + PortOrBaud = profile.PuTTY_OverridePortOrBaud ? profile.PuTTY_PortOrBaud : Settings.Application.PuTTY.GetPortOrBaudByConnectionMode(profile.PuTTY_ConnectionMode), - Username = profile.PuTTY_OverrideUsername ? profile.PuTTY_Username : (group.PuTTY_OverrideUsername ? group.PuTTY_Username : SettingsManager.Current.PuTTY_Username), - PrivateKey = profile.PuTTY_OverridePrivateKeyFile ? profile.PuTTY_PrivateKeyFile : (group.PuTTY_OverridePrivateKeyFile ? group.PuTTY_PrivateKeyFile : SettingsManager.Current.PuTTY_PrivateKeyFile), - Profile = profile.PuTTY_OverrideProfile ? profile.PuTTY_Profile : (group.PuTTY_OverrideProfile ? group.PuTTY_Profile : SettingsManager.Current.PuTTY_Profile), - Hostkey = profile.PuTTY_OverrideHostkey ? profile.PuTTY_Hostkey : "", - EnableLog = profile.PuTTY_OverrideEnableLog ? profile.PuTTY_EnableLog : (group.PuTTY_OverrideEnableLog ? group.PuTTY_EnableLog : SettingsManager.Current.PuTTY_EnableSessionLog), - LogMode = profile.PuTTY_OverrideLogMode ? profile.PuTTY_LogMode : (group.PuTTY_OverrideLogMode ? group.PuTTY_LogMode : SettingsManager.Current.PuTTY_LogMode), - LogPath = profile.PuTTY_OverrideLogPath ? profile.PuTTY_LogPath : (group.PuTTY_OverrideLogPath ? group.PuTTY_LogPath : Settings.Application.PuTTY.LogPath), - LogFileName = profile.PuTTY_OverrideLogFileName ? profile.PuTTY_LogFileName : (group.PuTTY_OverrideLogFileName ? group.PuTTY_LogFileName : SettingsManager.Current.PuTTY_LogFileName), - AdditionalCommandLine = profile.PuTTY_OverrideAdditionalCommandLine ? profile.PuTTY_AdditionalCommandLine : (group.PuTTY_OverrideAdditionalCommandLine ? group.PuTTY_AdditionalCommandLine : SettingsManager.Current.PuTTY_AdditionalCommandLine) - }; - } + Username = profile.PuTTY_OverrideUsername ? profile.PuTTY_Username : (group.PuTTY_OverrideUsername ? group.PuTTY_Username : SettingsManager.Current.PuTTY_Username), + PrivateKey = profile.PuTTY_OverridePrivateKeyFile ? profile.PuTTY_PrivateKeyFile : (group.PuTTY_OverridePrivateKeyFile ? group.PuTTY_PrivateKeyFile : SettingsManager.Current.PuTTY_PrivateKeyFile), + Profile = profile.PuTTY_OverrideProfile ? profile.PuTTY_Profile : (group.PuTTY_OverrideProfile ? group.PuTTY_Profile : SettingsManager.Current.PuTTY_Profile), + Hostkey = profile.PuTTY_OverrideHostkey ? profile.PuTTY_Hostkey : "", + EnableLog = profile.PuTTY_OverrideEnableLog ? profile.PuTTY_EnableLog : (group.PuTTY_OverrideEnableLog ? group.PuTTY_EnableLog : SettingsManager.Current.PuTTY_EnableSessionLog), + LogMode = profile.PuTTY_OverrideLogMode ? profile.PuTTY_LogMode : (group.PuTTY_OverrideLogMode ? group.PuTTY_LogMode : SettingsManager.Current.PuTTY_LogMode), + LogPath = profile.PuTTY_OverrideLogPath ? profile.PuTTY_LogPath : (group.PuTTY_OverrideLogPath ? group.PuTTY_LogPath : Settings.Application.PuTTY.LogPath), + LogFileName = profile.PuTTY_OverrideLogFileName ? profile.PuTTY_LogFileName : (group.PuTTY_OverrideLogFileName ? group.PuTTY_LogFileName : SettingsManager.Current.PuTTY_LogFileName), + AdditionalCommandLine = profile.PuTTY_OverrideAdditionalCommandLine ? profile.PuTTY_AdditionalCommandLine : (group.PuTTY_OverrideAdditionalCommandLine ? group.PuTTY_AdditionalCommandLine : SettingsManager.Current.PuTTY_AdditionalCommandLine) + }; } } diff --git a/Source/NETworkManager.Profiles/Application/RemoteDesktop.cs b/Source/NETworkManager.Profiles/Application/RemoteDesktop.cs index 5934392926..1ae47b8cfd 100644 --- a/Source/NETworkManager.Profiles/Application/RemoteDesktop.cs +++ b/Source/NETworkManager.Profiles/Application/RemoteDesktop.cs @@ -1,218 +1,217 @@ using NETworkManager.Models.RemoteDesktop; using NETworkManager.Settings; -namespace NETworkManager.Profiles.Application +namespace NETworkManager.Profiles.Application; + +public static class RemoteDesktop { - public static class RemoteDesktop + public static RemoteDesktopSessionInfo CreateSessionInfo() { - public static RemoteDesktopSessionInfo CreateSessionInfo() - { - return new RemoteDesktopSessionInfo - { - // Hostname - Hostname = string.Empty, - - // Network - Port = SettingsManager.Current.RemoteDesktop_Port, - - // Display - AdjustScreenAutomatically = SettingsManager.Current.RemoteDesktop_AdjustScreenAutomatically, - UseCurrentViewSize = SettingsManager.Current.RemoteDesktop_UseCurrentViewSize, - DesktopWidth = SettingsManager.Current.RemoteDesktop_UseCustomScreenSize ? SettingsManager.Current.RemoteDesktop_CustomScreenWidth : SettingsManager.Current.RemoteDesktop_ScreenWidth, - DesktopHeight = SettingsManager.Current.RemoteDesktop_UseCustomScreenSize ? SettingsManager.Current.RemoteDesktop_CustomScreenHeight : SettingsManager.Current.RemoteDesktop_ScreenHeight, - ColorDepth = SettingsManager.Current.RemoteDesktop_ColorDepth, - - // Authentication - EnableCredSspSupport = SettingsManager.Current.RemoteDesktop_EnableCredSspSupport, - AuthenticationLevel = SettingsManager.Current.RemoteDesktop_AuthenticationLevel, - - // Remote audio - AudioRedirectionMode = SettingsManager.Current.RemoteDesktop_AudioRedirectionMode, - AudioCaptureRedirectionMode = SettingsManager.Current.RemoteDesktop_AudioCaptureRedirectionMode, - - // Keyboard - KeyboardHookMode = SettingsManager.Current.RemoteDesktop_KeyboardHookMode, - - // Local devices and resources - RedirectClipboard = SettingsManager.Current.RemoteDesktop_RedirectClipboard, - RedirectDevices = SettingsManager.Current.RemoteDesktop_RedirectDevices, - RedirectDrives = SettingsManager.Current.RemoteDesktop_RedirectDrives, - RedirectPorts = SettingsManager.Current.RemoteDesktop_RedirectPorts, - RedirectSmartCards = SettingsManager.Current.RemoteDesktop_RedirectSmartCards, - RedirectPrinters = SettingsManager.Current.RemoteDesktop_RedirectPrinters, - - // Experience - PersistentBitmapCaching = SettingsManager.Current.RemoteDesktop_PersistentBitmapCaching, - ReconnectIfTheConnectionIsDropped = SettingsManager.Current.RemoteDesktop_ReconnectIfTheConnectionIsDropped, - - // Performance - NetworkConnectionType = SettingsManager.Current.RemoteDesktop_NetworkConnectionType, - DesktopBackground = SettingsManager.Current.RemoteDesktop_DesktopBackground, - FontSmoothing = SettingsManager.Current.RemoteDesktop_FontSmoothing, - DesktopComposition = SettingsManager.Current.RemoteDesktop_DesktopComposition, - ShowWindowContentsWhileDragging = SettingsManager.Current.RemoteDesktop_ShowWindowContentsWhileDragging, - MenuAndWindowAnimation = SettingsManager.Current.RemoteDesktop_MenuAndWindowAnimation, - VisualStyles = SettingsManager.Current.RemoteDesktop_VisualStyles - }; - } - - public static RemoteDesktopSessionInfo CreateSessionInfo(ProfileInfo profile) + return new RemoteDesktopSessionInfo { - var info = CreateSessionInfo(); - - // Get group info - GroupInfo group = ProfileManager.GetGroup(profile.Group); - - // Override hostname - info.Hostname = profile.RemoteDesktop_Host; + // Hostname + Hostname = string.Empty, // Network - if (profile.RemoteDesktop_OverridePort) - info.Port = profile.RemoteDesktop_Port; - else if (group.RemoteDesktop_OverridePort) - info.Port = group.RemoteDesktop_Port; + Port = SettingsManager.Current.RemoteDesktop_Port, // Display - if (profile.RemoteDesktop_OverrideDisplay) - { - info.AdjustScreenAutomatically = profile.RemoteDesktop_AdjustScreenAutomatically; - info.UseCurrentViewSize = profile.RemoteDesktop_UseCurrentViewSize; - info.DesktopWidth = profile.RemoteDesktop_UseCustomScreenSize ? profile.RemoteDesktop_CustomScreenWidth : profile.RemoteDesktop_ScreenWidth; - info.DesktopHeight = profile.RemoteDesktop_UseCustomScreenSize ? profile.RemoteDesktop_CustomScreenHeight : profile.RemoteDesktop_ScreenHeight; - info.ColorDepth = profile.RemoteDesktop_ColorDepth; - } - else if (group.RemoteDesktop_OverrideDisplay) - { - info.AdjustScreenAutomatically = group.RemoteDesktop_AdjustScreenAutomatically; - info.UseCurrentViewSize = group.RemoteDesktop_UseCurrentViewSize; - info.DesktopWidth = group.RemoteDesktop_UseCustomScreenSize ? group.RemoteDesktop_CustomScreenWidth : group.RemoteDesktop_ScreenWidth; - info.DesktopHeight = group.RemoteDesktop_UseCustomScreenSize ? group.RemoteDesktop_CustomScreenHeight : group.RemoteDesktop_ScreenHeight; - info.ColorDepth = group.RemoteDesktop_ColorDepth; - } + AdjustScreenAutomatically = SettingsManager.Current.RemoteDesktop_AdjustScreenAutomatically, + UseCurrentViewSize = SettingsManager.Current.RemoteDesktop_UseCurrentViewSize, + DesktopWidth = SettingsManager.Current.RemoteDesktop_UseCustomScreenSize ? SettingsManager.Current.RemoteDesktop_CustomScreenWidth : SettingsManager.Current.RemoteDesktop_ScreenWidth, + DesktopHeight = SettingsManager.Current.RemoteDesktop_UseCustomScreenSize ? SettingsManager.Current.RemoteDesktop_CustomScreenHeight : SettingsManager.Current.RemoteDesktop_ScreenHeight, + ColorDepth = SettingsManager.Current.RemoteDesktop_ColorDepth, // Authentication - if (profile.RemoteDesktop_OverrideCredSspSupport) - info.EnableCredSspSupport = profile.RemoteDesktop_EnableCredSspSupport; - else if (group.RemoteDesktop_OverrideCredSspSupport) - info.EnableCredSspSupport = group.RemoteDesktop_EnableCredSspSupport; - - if (profile.RemoteDesktop_OverrideAuthenticationLevel) - info.AuthenticationLevel = profile.RemoteDesktop_AuthenticationLevel; - else if (group.RemoteDesktop_OverrideAuthenticationLevel) - info.AuthenticationLevel = group.RemoteDesktop_AuthenticationLevel; + EnableCredSspSupport = SettingsManager.Current.RemoteDesktop_EnableCredSspSupport, + AuthenticationLevel = SettingsManager.Current.RemoteDesktop_AuthenticationLevel, // Remote audio - if (profile.RemoteDesktop_OverrideAudioRedirectionMode) - info.AudioRedirectionMode = profile.RemoteDesktop_AudioRedirectionMode; - else if (group.RemoteDesktop_OverrideAudioRedirectionMode) - info.AudioRedirectionMode = group.RemoteDesktop_AudioRedirectionMode; - - if (profile.RemoteDesktop_OverrideAudioCaptureRedirectionMode) - info.AudioCaptureRedirectionMode = profile.RemoteDesktop_AudioCaptureRedirectionMode; - else if (group.RemoteDesktop_OverrideAudioCaptureRedirectionMode) - info.AudioCaptureRedirectionMode = group.RemoteDesktop_AudioCaptureRedirectionMode; + AudioRedirectionMode = SettingsManager.Current.RemoteDesktop_AudioRedirectionMode, + AudioCaptureRedirectionMode = SettingsManager.Current.RemoteDesktop_AudioCaptureRedirectionMode, // Keyboard - if (profile.RemoteDesktop_OverrideApplyWindowsKeyCombinations) - info.KeyboardHookMode = profile.RemoteDesktop_KeyboardHookMode; - else if (group.RemoteDesktop_OverrideApplyWindowsKeyCombinations) - info.KeyboardHookMode = group.RemoteDesktop_KeyboardHookMode; + KeyboardHookMode = SettingsManager.Current.RemoteDesktop_KeyboardHookMode, // Local devices and resources - if (profile.RemoteDesktop_OverrideRedirectClipboard) - info.RedirectClipboard = profile.RemoteDesktop_RedirectClipboard; - else if (group.RemoteDesktop_OverrideRedirectClipboard) - info.RedirectClipboard = group.RemoteDesktop_RedirectClipboard; - - if (profile.RemoteDesktop_OverrideRedirectDevices) - info.RedirectDevices = profile.RemoteDesktop_RedirectDevices; - else if (group.RemoteDesktop_OverrideRedirectDevices) - info.RedirectDevices = group.RemoteDesktop_RedirectDevices; - - if (profile.RemoteDesktop_OverrideRedirectDrives) - info.RedirectDrives = profile.RemoteDesktop_RedirectDrives; - else if (group.RemoteDesktop_OverrideRedirectDrives) - info.RedirectDrives = group.RemoteDesktop_RedirectDrives; - - if (profile.RemoteDesktop_OverrideRedirectPorts) - info.RedirectPorts = profile.RemoteDesktop_RedirectPorts; - else if (group.RemoteDesktop_OverrideRedirectPorts) - info.RedirectPorts = group.RemoteDesktop_RedirectPorts; - - if (profile.RemoteDesktop_OverrideRedirectSmartcards) - info.RedirectSmartCards = profile.RemoteDesktop_RedirectSmartCards; - else if (group.RemoteDesktop_OverrideRedirectSmartcards) - info.RedirectSmartCards = group.RemoteDesktop_RedirectSmartCards; - - if (profile.RemoteDesktop_OverrideRedirectPrinters) - info.RedirectPrinters = profile.RemoteDesktop_RedirectPrinters; - else if (group.RemoteDesktop_OverrideRedirectPrinters) - info.RedirectPrinters = group.RemoteDesktop_RedirectPrinters; + RedirectClipboard = SettingsManager.Current.RemoteDesktop_RedirectClipboard, + RedirectDevices = SettingsManager.Current.RemoteDesktop_RedirectDevices, + RedirectDrives = SettingsManager.Current.RemoteDesktop_RedirectDrives, + RedirectPorts = SettingsManager.Current.RemoteDesktop_RedirectPorts, + RedirectSmartCards = SettingsManager.Current.RemoteDesktop_RedirectSmartCards, + RedirectPrinters = SettingsManager.Current.RemoteDesktop_RedirectPrinters, // Experience - if (profile.RemoteDesktop_OverridePersistentBitmapCaching) - info.PersistentBitmapCaching = profile.RemoteDesktop_PersistentBitmapCaching; - else if (group.RemoteDesktop_OverridePersistentBitmapCaching) - info.PersistentBitmapCaching = group.RemoteDesktop_PersistentBitmapCaching; - - if (profile.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped) - info.ReconnectIfTheConnectionIsDropped = profile.RemoteDesktop_ReconnectIfTheConnectionIsDropped; - else if (group.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped) - info.ReconnectIfTheConnectionIsDropped = group.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + PersistentBitmapCaching = SettingsManager.Current.RemoteDesktop_PersistentBitmapCaching, + ReconnectIfTheConnectionIsDropped = SettingsManager.Current.RemoteDesktop_ReconnectIfTheConnectionIsDropped, // Performance - if (profile.RemoteDesktop_OverrideNetworkConnectionType) - info.NetworkConnectionType = profile.RemoteDesktop_NetworkConnectionType; - else if (group.RemoteDesktop_OverrideNetworkConnectionType) - info.NetworkConnectionType = group.RemoteDesktop_NetworkConnectionType; - - if (profile.RemoteDesktop_OverrideDesktopBackground) - info.DesktopBackground = profile.RemoteDesktop_DesktopBackground; - else if (group.RemoteDesktop_OverrideDesktopBackground) - info.DesktopBackground = group.RemoteDesktop_DesktopBackground; - - if (profile.RemoteDesktop_OverrideFontSmoothing) - info.FontSmoothing = profile.RemoteDesktop_FontSmoothing; - else if (group.RemoteDesktop_OverrideFontSmoothing) - info.FontSmoothing = group.RemoteDesktop_FontSmoothing; - - if (profile.RemoteDesktop_OverrideDesktopComposition) - info.DesktopComposition = profile.RemoteDesktop_DesktopComposition; - else if (group.RemoteDesktop_OverrideDesktopComposition) - info.DesktopComposition = group.RemoteDesktop_DesktopComposition; - - if (profile.RemoteDesktop_OverrideShowWindowContentsWhileDragging) - info.ShowWindowContentsWhileDragging = profile.RemoteDesktop_ShowWindowContentsWhileDragging; - else if (group.RemoteDesktop_OverrideShowWindowContentsWhileDragging) - info.ShowWindowContentsWhileDragging = group.RemoteDesktop_ShowWindowContentsWhileDragging; - - if (profile.RemoteDesktop_OverrideMenuAndWindowAnimation) - info.MenuAndWindowAnimation = profile.RemoteDesktop_MenuAndWindowAnimation; - else if (group.RemoteDesktop_OverrideMenuAndWindowAnimation) - info.MenuAndWindowAnimation = group.RemoteDesktop_MenuAndWindowAnimation; - - if (profile.RemoteDesktop_OverrideVisualStyles) - info.VisualStyles = profile.RemoteDesktop_VisualStyles; - else if (group.RemoteDesktop_OverrideVisualStyles) - info.VisualStyles = group.RemoteDesktop_VisualStyles; - - // Set credentials - if (profile.RemoteDesktop_UseCredentials) - { - info.CustomCredentials = true; - - info.Username = profile.RemoteDesktop_Username; - info.Password = profile.RemoteDesktop_Password; - } - else if (group.RemoteDesktop_UseCredentials) - { - info.CustomCredentials = true; - - info.Username = group.RemoteDesktop_Username; - info.Password = group.RemoteDesktop_Password; - } - - return info; + NetworkConnectionType = SettingsManager.Current.RemoteDesktop_NetworkConnectionType, + DesktopBackground = SettingsManager.Current.RemoteDesktop_DesktopBackground, + FontSmoothing = SettingsManager.Current.RemoteDesktop_FontSmoothing, + DesktopComposition = SettingsManager.Current.RemoteDesktop_DesktopComposition, + ShowWindowContentsWhileDragging = SettingsManager.Current.RemoteDesktop_ShowWindowContentsWhileDragging, + MenuAndWindowAnimation = SettingsManager.Current.RemoteDesktop_MenuAndWindowAnimation, + VisualStyles = SettingsManager.Current.RemoteDesktop_VisualStyles + }; + } + + public static RemoteDesktopSessionInfo CreateSessionInfo(ProfileInfo profile) + { + var info = CreateSessionInfo(); + + // Get group info + GroupInfo group = ProfileManager.GetGroup(profile.Group); + + // Override hostname + info.Hostname = profile.RemoteDesktop_Host; + + // Network + if (profile.RemoteDesktop_OverridePort) + info.Port = profile.RemoteDesktop_Port; + else if (group.RemoteDesktop_OverridePort) + info.Port = group.RemoteDesktop_Port; + + // Display + if (profile.RemoteDesktop_OverrideDisplay) + { + info.AdjustScreenAutomatically = profile.RemoteDesktop_AdjustScreenAutomatically; + info.UseCurrentViewSize = profile.RemoteDesktop_UseCurrentViewSize; + info.DesktopWidth = profile.RemoteDesktop_UseCustomScreenSize ? profile.RemoteDesktop_CustomScreenWidth : profile.RemoteDesktop_ScreenWidth; + info.DesktopHeight = profile.RemoteDesktop_UseCustomScreenSize ? profile.RemoteDesktop_CustomScreenHeight : profile.RemoteDesktop_ScreenHeight; + info.ColorDepth = profile.RemoteDesktop_ColorDepth; } + else if (group.RemoteDesktop_OverrideDisplay) + { + info.AdjustScreenAutomatically = group.RemoteDesktop_AdjustScreenAutomatically; + info.UseCurrentViewSize = group.RemoteDesktop_UseCurrentViewSize; + info.DesktopWidth = group.RemoteDesktop_UseCustomScreenSize ? group.RemoteDesktop_CustomScreenWidth : group.RemoteDesktop_ScreenWidth; + info.DesktopHeight = group.RemoteDesktop_UseCustomScreenSize ? group.RemoteDesktop_CustomScreenHeight : group.RemoteDesktop_ScreenHeight; + info.ColorDepth = group.RemoteDesktop_ColorDepth; + } + + // Authentication + if (profile.RemoteDesktop_OverrideCredSspSupport) + info.EnableCredSspSupport = profile.RemoteDesktop_EnableCredSspSupport; + else if (group.RemoteDesktop_OverrideCredSspSupport) + info.EnableCredSspSupport = group.RemoteDesktop_EnableCredSspSupport; + + if (profile.RemoteDesktop_OverrideAuthenticationLevel) + info.AuthenticationLevel = profile.RemoteDesktop_AuthenticationLevel; + else if (group.RemoteDesktop_OverrideAuthenticationLevel) + info.AuthenticationLevel = group.RemoteDesktop_AuthenticationLevel; + + // Remote audio + if (profile.RemoteDesktop_OverrideAudioRedirectionMode) + info.AudioRedirectionMode = profile.RemoteDesktop_AudioRedirectionMode; + else if (group.RemoteDesktop_OverrideAudioRedirectionMode) + info.AudioRedirectionMode = group.RemoteDesktop_AudioRedirectionMode; + + if (profile.RemoteDesktop_OverrideAudioCaptureRedirectionMode) + info.AudioCaptureRedirectionMode = profile.RemoteDesktop_AudioCaptureRedirectionMode; + else if (group.RemoteDesktop_OverrideAudioCaptureRedirectionMode) + info.AudioCaptureRedirectionMode = group.RemoteDesktop_AudioCaptureRedirectionMode; + + // Keyboard + if (profile.RemoteDesktop_OverrideApplyWindowsKeyCombinations) + info.KeyboardHookMode = profile.RemoteDesktop_KeyboardHookMode; + else if (group.RemoteDesktop_OverrideApplyWindowsKeyCombinations) + info.KeyboardHookMode = group.RemoteDesktop_KeyboardHookMode; + + // Local devices and resources + if (profile.RemoteDesktop_OverrideRedirectClipboard) + info.RedirectClipboard = profile.RemoteDesktop_RedirectClipboard; + else if (group.RemoteDesktop_OverrideRedirectClipboard) + info.RedirectClipboard = group.RemoteDesktop_RedirectClipboard; + + if (profile.RemoteDesktop_OverrideRedirectDevices) + info.RedirectDevices = profile.RemoteDesktop_RedirectDevices; + else if (group.RemoteDesktop_OverrideRedirectDevices) + info.RedirectDevices = group.RemoteDesktop_RedirectDevices; + + if (profile.RemoteDesktop_OverrideRedirectDrives) + info.RedirectDrives = profile.RemoteDesktop_RedirectDrives; + else if (group.RemoteDesktop_OverrideRedirectDrives) + info.RedirectDrives = group.RemoteDesktop_RedirectDrives; + + if (profile.RemoteDesktop_OverrideRedirectPorts) + info.RedirectPorts = profile.RemoteDesktop_RedirectPorts; + else if (group.RemoteDesktop_OverrideRedirectPorts) + info.RedirectPorts = group.RemoteDesktop_RedirectPorts; + + if (profile.RemoteDesktop_OverrideRedirectSmartcards) + info.RedirectSmartCards = profile.RemoteDesktop_RedirectSmartCards; + else if (group.RemoteDesktop_OverrideRedirectSmartcards) + info.RedirectSmartCards = group.RemoteDesktop_RedirectSmartCards; + + if (profile.RemoteDesktop_OverrideRedirectPrinters) + info.RedirectPrinters = profile.RemoteDesktop_RedirectPrinters; + else if (group.RemoteDesktop_OverrideRedirectPrinters) + info.RedirectPrinters = group.RemoteDesktop_RedirectPrinters; + + // Experience + if (profile.RemoteDesktop_OverridePersistentBitmapCaching) + info.PersistentBitmapCaching = profile.RemoteDesktop_PersistentBitmapCaching; + else if (group.RemoteDesktop_OverridePersistentBitmapCaching) + info.PersistentBitmapCaching = group.RemoteDesktop_PersistentBitmapCaching; + + if (profile.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped) + info.ReconnectIfTheConnectionIsDropped = profile.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + else if (group.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped) + info.ReconnectIfTheConnectionIsDropped = group.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + + // Performance + if (profile.RemoteDesktop_OverrideNetworkConnectionType) + info.NetworkConnectionType = profile.RemoteDesktop_NetworkConnectionType; + else if (group.RemoteDesktop_OverrideNetworkConnectionType) + info.NetworkConnectionType = group.RemoteDesktop_NetworkConnectionType; + + if (profile.RemoteDesktop_OverrideDesktopBackground) + info.DesktopBackground = profile.RemoteDesktop_DesktopBackground; + else if (group.RemoteDesktop_OverrideDesktopBackground) + info.DesktopBackground = group.RemoteDesktop_DesktopBackground; + + if (profile.RemoteDesktop_OverrideFontSmoothing) + info.FontSmoothing = profile.RemoteDesktop_FontSmoothing; + else if (group.RemoteDesktop_OverrideFontSmoothing) + info.FontSmoothing = group.RemoteDesktop_FontSmoothing; + + if (profile.RemoteDesktop_OverrideDesktopComposition) + info.DesktopComposition = profile.RemoteDesktop_DesktopComposition; + else if (group.RemoteDesktop_OverrideDesktopComposition) + info.DesktopComposition = group.RemoteDesktop_DesktopComposition; + + if (profile.RemoteDesktop_OverrideShowWindowContentsWhileDragging) + info.ShowWindowContentsWhileDragging = profile.RemoteDesktop_ShowWindowContentsWhileDragging; + else if (group.RemoteDesktop_OverrideShowWindowContentsWhileDragging) + info.ShowWindowContentsWhileDragging = group.RemoteDesktop_ShowWindowContentsWhileDragging; + + if (profile.RemoteDesktop_OverrideMenuAndWindowAnimation) + info.MenuAndWindowAnimation = profile.RemoteDesktop_MenuAndWindowAnimation; + else if (group.RemoteDesktop_OverrideMenuAndWindowAnimation) + info.MenuAndWindowAnimation = group.RemoteDesktop_MenuAndWindowAnimation; + + if (profile.RemoteDesktop_OverrideVisualStyles) + info.VisualStyles = profile.RemoteDesktop_VisualStyles; + else if (group.RemoteDesktop_OverrideVisualStyles) + info.VisualStyles = group.RemoteDesktop_VisualStyles; + + // Set credentials + if (profile.RemoteDesktop_UseCredentials) + { + info.CustomCredentials = true; + + info.Username = profile.RemoteDesktop_Username; + info.Password = profile.RemoteDesktop_Password; + } + else if (group.RemoteDesktop_UseCredentials) + { + info.CustomCredentials = true; + + info.Username = group.RemoteDesktop_Username; + info.Password = group.RemoteDesktop_Password; + } + + return info; } } diff --git a/Source/NETworkManager.Profiles/Application/TigerVNC.cs b/Source/NETworkManager.Profiles/Application/TigerVNC.cs index 15b1bcc980..f3cbb03309 100644 --- a/Source/NETworkManager.Profiles/Application/TigerVNC.cs +++ b/Source/NETworkManager.Profiles/Application/TigerVNC.cs @@ -2,21 +2,20 @@ using NETworkManager.Models.TigerVNC; using NETworkManager.Settings; -namespace NETworkManager.Profiles.Application +namespace NETworkManager.Profiles.Application; + +public static class TigerVNC { - public static class TigerVNC + public static TigerVNCSessionInfo CreateSessionInfo(ProfileInfo profile) { - public static TigerVNCSessionInfo CreateSessionInfo(ProfileInfo profile) - { - // Get group info - GroupInfo group = ProfileManager.GetGroup(profile.Group); + // Get group info + GroupInfo group = ProfileManager.GetGroup(profile.Group); - return new TigerVNCSessionInfo - { - Host = profile.TigerVNC_Host, + return new TigerVNCSessionInfo + { + Host = profile.TigerVNC_Host, - Port = profile.TigerVNC_OverridePort ? profile.TigerVNC_Port : (group.TigerVNC_OverridePort ? group.TigerVNC_Port : SettingsManager.Current.TigerVNC_Port) - }; - } + Port = profile.TigerVNC_OverridePort ? profile.TigerVNC_Port : (group.TigerVNC_OverridePort ? group.TigerVNC_Port : SettingsManager.Current.TigerVNC_Port) + }; } } diff --git a/Source/NETworkManager.Profiles/Application/WakeOnLan.cs b/Source/NETworkManager.Profiles/Application/WakeOnLan.cs index 1da3791597..7d683d6b4a 100644 --- a/Source/NETworkManager.Profiles/Application/WakeOnLan.cs +++ b/Source/NETworkManager.Profiles/Application/WakeOnLan.cs @@ -2,20 +2,19 @@ using NETworkManager.Settings; using System.Net; -namespace NETworkManager.Profiles.Application +namespace NETworkManager.Profiles.Application; + +public static class WakeOnLAN { - public static class WakeOnLAN + public static WakeOnLANInfo CreateInfo(ProfileInfo profileInfo) { - public static WakeOnLANInfo CreateInfo(ProfileInfo profileInfo) + var info = new WakeOnLANInfo { - var info = new WakeOnLANInfo - { - MagicPacket = Models.Network.WakeOnLAN.CreateMagicPacket(profileInfo.WakeOnLAN_MACAddress), - Broadcast = IPAddress.Parse(profileInfo.WakeOnLAN_Broadcast), - Port = profileInfo.WakeOnLAN_OverridePort ? profileInfo.WakeOnLAN_Port : SettingsManager.Current.WakeOnLAN_Port - }; + MagicPacket = Models.Network.WakeOnLAN.CreateMagicPacket(profileInfo.WakeOnLAN_MACAddress), + Broadcast = IPAddress.Parse(profileInfo.WakeOnLAN_Broadcast), + Port = profileInfo.WakeOnLAN_OverridePort ? profileInfo.WakeOnLAN_Port : SettingsManager.Current.WakeOnLAN_Port + }; - return info; - } + return info; } } diff --git a/Source/NETworkManager.Profiles/Application/WebConsole.cs b/Source/NETworkManager.Profiles/Application/WebConsole.cs index 34ae3fc1fe..da59427140 100644 --- a/Source/NETworkManager.Profiles/Application/WebConsole.cs +++ b/Source/NETworkManager.Profiles/Application/WebConsole.cs @@ -1,17 +1,16 @@ using NETworkManager.Models.WebConsole; -namespace NETworkManager.Profiles.Application -{ - public class WebConsole - { - public static WebConsoleSessionInfo CreateSessionInfo(ProfileInfo profileInfo) +namespace NETworkManager.Profiles.Application; + +public class WebConsole +{ + public static WebConsoleSessionInfo CreateSessionInfo(ProfileInfo profileInfo) + { + var info = new WebConsoleSessionInfo { - var info = new WebConsoleSessionInfo - { - Url = profileInfo.WebConsole_Url - }; + Url = profileInfo.WebConsole_Url + }; - return info; - } + return info; } } diff --git a/Source/NETworkManager.Profiles/GroupEditMode.cs b/Source/NETworkManager.Profiles/GroupEditMode.cs index 99da6314af..e0007ae666 100644 --- a/Source/NETworkManager.Profiles/GroupEditMode.cs +++ b/Source/NETworkManager.Profiles/GroupEditMode.cs @@ -1,8 +1,7 @@ -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public enum GroupEditMode { - public enum GroupEditMode - { - Add, - Edit - } + Add, + Edit } diff --git a/Source/NETworkManager.Profiles/GroupInfo.cs b/Source/NETworkManager.Profiles/GroupInfo.cs index 35a82fb7b6..57367484f8 100644 --- a/Source/NETworkManager.Profiles/GroupInfo.cs +++ b/Source/NETworkManager.Profiles/GroupInfo.cs @@ -6,231 +6,230 @@ using System.Security; using System.Xml.Serialization; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +/// +/// Class represents a group. +/// +public class GroupInfo { /// - /// Class represents a group. + /// Name of the group. + /// + public string Name { get; set; } + + public bool IsDynamic { get; set; } + + [XmlIgnore] + public List Profiles { get; set; } + + public bool RemoteDesktop_UseCredentials { get; set; } + public string RemoteDesktop_Username { get; set; } + + [XmlIgnore] + public SecureString RemoteDesktop_Password { get; set; } + public bool RemoteDesktop_OverrideDisplay { get; set; } + public bool RemoteDesktop_AdjustScreenAutomatically { get; set; } + public bool RemoteDesktop_UseCurrentViewSize { get; set; } + public bool RemoteDesktop_UseFixedScreenSize { get; set; } = true; + public int RemoteDesktop_ScreenWidth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenWidth; + public int RemoteDesktop_ScreenHeight { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenHeight; + public bool RemoteDesktop_UseCustomScreenSize { get; set; } + public int RemoteDesktop_CustomScreenWidth { get; set; } + public int RemoteDesktop_CustomScreenHeight { get; set; } + public bool RemoteDesktop_OverrideColorDepth { get; set; } + public int RemoteDesktop_ColorDepth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ColorDepth; + public bool RemoteDesktop_OverridePort { get; set; } + public int RemoteDesktop_Port { get; set; } = GlobalStaticConfiguration.RemoteDesktop_Port; + public bool RemoteDesktop_OverrideCredSspSupport { get; set; } + public bool RemoteDesktop_EnableCredSspSupport { get; set; } + public bool RemoteDesktop_OverrideAuthenticationLevel { get; set; } + public uint RemoteDesktop_AuthenticationLevel { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AuthenticationLevel; + public bool RemoteDesktop_OverrideAudioRedirectionMode { get; set; } + public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioRedirectionMode; + public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode { get; set; } + public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioCaptureRedirectionMode; + public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations { get; set; } + public KeyboardHookMode RemoteDesktop_KeyboardHookMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_KeyboardHookMode; + public bool RemoteDesktop_OverrideRedirectClipboard { get; set; } + public bool RemoteDesktop_RedirectClipboard { get; set; } = true; + public bool RemoteDesktop_OverrideRedirectDevices { get; set; } + public bool RemoteDesktop_RedirectDevices { get; set; } + public bool RemoteDesktop_OverrideRedirectDrives { get; set; } + public bool RemoteDesktop_RedirectDrives { get; set; } + public bool RemoteDesktop_OverrideRedirectPorts { get; set; } + public bool RemoteDesktop_RedirectPorts { get; set; } + public bool RemoteDesktop_OverrideRedirectSmartcards { get; set; } + public bool RemoteDesktop_RedirectSmartCards { get; set; } + public bool RemoteDesktop_OverrideRedirectPrinters { get; set; } + public bool RemoteDesktop_RedirectPrinters { get; set; } + public bool RemoteDesktop_OverridePersistentBitmapCaching { get; set; } + public bool RemoteDesktop_PersistentBitmapCaching { get; set; } + public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped { get; set; } + public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped { get; set; } + public bool RemoteDesktop_OverrideNetworkConnectionType { get; set; } + public NetworkConnectionType RemoteDesktop_NetworkConnectionType { get; set; } + public bool RemoteDesktop_OverrideDesktopBackground { get; set; } + public bool RemoteDesktop_DesktopBackground { get; set; } + public bool RemoteDesktop_OverrideFontSmoothing { get; set; } + public bool RemoteDesktop_FontSmoothing { get; set; } + public bool RemoteDesktop_OverrideDesktopComposition { get; set; } + public bool RemoteDesktop_DesktopComposition { get; set; } + public bool RemoteDesktop_OverrideShowWindowContentsWhileDragging { get; set; } + public bool RemoteDesktop_ShowWindowContentsWhileDragging { get; set; } + public bool RemoteDesktop_OverrideMenuAndWindowAnimation { get; set; } + public bool RemoteDesktop_MenuAndWindowAnimation { get; set; } + public bool RemoteDesktop_OverrideVisualStyles { get; set; } + public bool RemoteDesktop_VisualStyles { get; set; } + + public bool PowerShell_OverrideCommand { get; set; } + public string PowerShell_Command { get; set; } + public bool PowerShell_OverrideAdditionalCommandLine { get; set; } + public string PowerShell_AdditionalCommandLine { get; set; } + public bool PowerShell_OverrideExecutionPolicy { get; set; } + public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy { get; set; } + + public bool PuTTY_OverrideUsername { get; set; } + public string PuTTY_Username { get; set; } + public bool PuTTY_OverridePrivateKeyFile { get; set; } + public string PuTTY_PrivateKeyFile { get; set; } + public bool PuTTY_OverrideProfile { get; set; } + public string PuTTY_Profile { get; set; } + public bool PuTTY_OverrideEnableLog { get; set; } + public bool PuTTY_EnableLog { get; set; } + public bool PuTTY_OverrideLogMode { get; set; } + public LogMode PuTTY_LogMode { get; set; } = GlobalStaticConfiguration.PuTTY_LogMode; + public bool PuTTY_OverrideLogPath { get; set; } + public string PuTTY_LogPath { get; set; } = GlobalStaticConfiguration.PuTTY_LogPath; + public bool PuTTY_OverrideLogFileName { get; set; } + public string PuTTY_LogFileName { get; set; } = GlobalStaticConfiguration.PuTTY_LogFileName; + public bool PuTTY_OverrideAdditionalCommandLine { get; set; } + public string PuTTY_AdditionalCommandLine { get; set; } + + public bool AWSSessionManager_OverrideProfile { get; set; } + public string AWSSessionManager_Profile { get; set; } + public bool AWSSessionManager_OverrideRegion { get; set; } + public string AWSSessionManager_Region { get; set; } + + public bool TigerVNC_OverridePort { get; set; } + public int TigerVNC_Port { get; set; } + + + /// + /// Initializes a new instance of the class. + /// + public GroupInfo() + { + Profiles = new List(); + } + + /// + /// Initializes a new instance of the class with name. + /// + public GroupInfo(string name) : this() + { + Name = name; + } + + /// + /// Initializes a new instance of the class with properties. /// - public class GroupInfo + public GroupInfo(GroupInfo group) : this(group.Name) { - /// - /// Name of the group. - /// - public string Name { get; set; } - - public bool IsDynamic { get; set; } - - [XmlIgnore] - public List Profiles { get; set; } - - public bool RemoteDesktop_UseCredentials { get; set; } - public string RemoteDesktop_Username { get; set; } - - [XmlIgnore] - public SecureString RemoteDesktop_Password { get; set; } - public bool RemoteDesktop_OverrideDisplay { get; set; } - public bool RemoteDesktop_AdjustScreenAutomatically { get; set; } - public bool RemoteDesktop_UseCurrentViewSize { get; set; } - public bool RemoteDesktop_UseFixedScreenSize { get; set; } = true; - public int RemoteDesktop_ScreenWidth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenWidth; - public int RemoteDesktop_ScreenHeight { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenHeight; - public bool RemoteDesktop_UseCustomScreenSize { get; set; } - public int RemoteDesktop_CustomScreenWidth { get; set; } - public int RemoteDesktop_CustomScreenHeight { get; set; } - public bool RemoteDesktop_OverrideColorDepth { get; set; } - public int RemoteDesktop_ColorDepth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ColorDepth; - public bool RemoteDesktop_OverridePort { get; set; } - public int RemoteDesktop_Port { get; set; } = GlobalStaticConfiguration.RemoteDesktop_Port; - public bool RemoteDesktop_OverrideCredSspSupport { get; set; } - public bool RemoteDesktop_EnableCredSspSupport { get; set; } - public bool RemoteDesktop_OverrideAuthenticationLevel { get; set; } - public uint RemoteDesktop_AuthenticationLevel { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AuthenticationLevel; - public bool RemoteDesktop_OverrideAudioRedirectionMode { get; set; } - public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioRedirectionMode; - public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode { get; set; } - public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioCaptureRedirectionMode; - public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations { get; set; } - public KeyboardHookMode RemoteDesktop_KeyboardHookMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_KeyboardHookMode; - public bool RemoteDesktop_OverrideRedirectClipboard { get; set; } - public bool RemoteDesktop_RedirectClipboard { get; set; } = true; - public bool RemoteDesktop_OverrideRedirectDevices { get; set; } - public bool RemoteDesktop_RedirectDevices { get; set; } - public bool RemoteDesktop_OverrideRedirectDrives { get; set; } - public bool RemoteDesktop_RedirectDrives { get; set; } - public bool RemoteDesktop_OverrideRedirectPorts { get; set; } - public bool RemoteDesktop_RedirectPorts { get; set; } - public bool RemoteDesktop_OverrideRedirectSmartcards { get; set; } - public bool RemoteDesktop_RedirectSmartCards { get; set; } - public bool RemoteDesktop_OverrideRedirectPrinters { get; set; } - public bool RemoteDesktop_RedirectPrinters { get; set; } - public bool RemoteDesktop_OverridePersistentBitmapCaching { get; set; } - public bool RemoteDesktop_PersistentBitmapCaching { get; set; } - public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped { get; set; } - public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped { get; set; } - public bool RemoteDesktop_OverrideNetworkConnectionType { get; set; } - public NetworkConnectionType RemoteDesktop_NetworkConnectionType { get; set; } - public bool RemoteDesktop_OverrideDesktopBackground { get; set; } - public bool RemoteDesktop_DesktopBackground { get; set; } - public bool RemoteDesktop_OverrideFontSmoothing { get; set; } - public bool RemoteDesktop_FontSmoothing { get; set; } - public bool RemoteDesktop_OverrideDesktopComposition { get; set; } - public bool RemoteDesktop_DesktopComposition { get; set; } - public bool RemoteDesktop_OverrideShowWindowContentsWhileDragging { get; set; } - public bool RemoteDesktop_ShowWindowContentsWhileDragging { get; set; } - public bool RemoteDesktop_OverrideMenuAndWindowAnimation { get; set; } - public bool RemoteDesktop_MenuAndWindowAnimation { get; set; } - public bool RemoteDesktop_OverrideVisualStyles { get; set; } - public bool RemoteDesktop_VisualStyles { get; set; } - - public bool PowerShell_OverrideCommand { get; set; } - public string PowerShell_Command { get; set; } - public bool PowerShell_OverrideAdditionalCommandLine { get; set; } - public string PowerShell_AdditionalCommandLine { get; set; } - public bool PowerShell_OverrideExecutionPolicy { get; set; } - public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy { get; set; } - - public bool PuTTY_OverrideUsername { get; set; } - public string PuTTY_Username { get; set; } - public bool PuTTY_OverridePrivateKeyFile { get; set; } - public string PuTTY_PrivateKeyFile { get; set; } - public bool PuTTY_OverrideProfile { get; set; } - public string PuTTY_Profile { get; set; } - public bool PuTTY_OverrideEnableLog { get; set; } - public bool PuTTY_EnableLog { get; set; } - public bool PuTTY_OverrideLogMode { get; set; } - public LogMode PuTTY_LogMode { get; set; } = GlobalStaticConfiguration.PuTTY_LogMode; - public bool PuTTY_OverrideLogPath { get; set; } - public string PuTTY_LogPath { get; set; } = GlobalStaticConfiguration.PuTTY_LogPath; - public bool PuTTY_OverrideLogFileName { get; set; } - public string PuTTY_LogFileName { get; set; } = GlobalStaticConfiguration.PuTTY_LogFileName; - public bool PuTTY_OverrideAdditionalCommandLine { get; set; } - public string PuTTY_AdditionalCommandLine { get; set; } - - public bool AWSSessionManager_OverrideProfile { get; set; } - public string AWSSessionManager_Profile { get; set; } - public bool AWSSessionManager_OverrideRegion { get; set; } - public string AWSSessionManager_Region { get; set; } - - public bool TigerVNC_OverridePort { get; set; } - public int TigerVNC_Port { get; set; } - - - /// - /// Initializes a new instance of the class. - /// - public GroupInfo() - { - Profiles = new List(); - } - - /// - /// Initializes a new instance of the class with name. - /// - public GroupInfo(string name) : this() - { - Name = name; - } - - /// - /// Initializes a new instance of the class with properties. - /// - public GroupInfo(GroupInfo group) : this(group.Name) - { - Profiles = group.Profiles; - - // Remote Desktop - RemoteDesktop_UseCredentials = group.RemoteDesktop_UseCredentials; - RemoteDesktop_Username = group.RemoteDesktop_Username; - RemoteDesktop_Password = group.RemoteDesktop_Password; - RemoteDesktop_OverrideDisplay = group.RemoteDesktop_OverrideDisplay; - RemoteDesktop_AdjustScreenAutomatically = group.RemoteDesktop_AdjustScreenAutomatically; - RemoteDesktop_UseCurrentViewSize = group.RemoteDesktop_UseCurrentViewSize; - RemoteDesktop_UseFixedScreenSize = group.RemoteDesktop_UseFixedScreenSize; - RemoteDesktop_ScreenWidth = group.RemoteDesktop_ScreenWidth; - RemoteDesktop_ScreenHeight = group.RemoteDesktop_ScreenHeight; - RemoteDesktop_UseCustomScreenSize = group.RemoteDesktop_UseCustomScreenSize; - RemoteDesktop_CustomScreenWidth = group.RemoteDesktop_CustomScreenWidth; - RemoteDesktop_CustomScreenHeight = group.RemoteDesktop_CustomScreenHeight; - RemoteDesktop_OverrideColorDepth = group.RemoteDesktop_OverrideColorDepth; - RemoteDesktop_ColorDepth = group.RemoteDesktop_ColorDepth; - RemoteDesktop_OverridePort = group.RemoteDesktop_OverridePort; - RemoteDesktop_Port = group.RemoteDesktop_Port; - RemoteDesktop_OverrideCredSspSupport = group.RemoteDesktop_OverrideCredSspSupport; - RemoteDesktop_EnableCredSspSupport = group.RemoteDesktop_EnableCredSspSupport; - RemoteDesktop_OverrideAuthenticationLevel = group.RemoteDesktop_OverrideAuthenticationLevel; - RemoteDesktop_AuthenticationLevel = group.RemoteDesktop_AuthenticationLevel; - RemoteDesktop_OverrideAudioRedirectionMode = group.RemoteDesktop_OverrideAudioRedirectionMode; - RemoteDesktop_AudioRedirectionMode = group.RemoteDesktop_AudioRedirectionMode; - RemoteDesktop_OverrideAudioCaptureRedirectionMode = group.RemoteDesktop_OverrideAudioCaptureRedirectionMode; - RemoteDesktop_AudioCaptureRedirectionMode = group.RemoteDesktop_AudioCaptureRedirectionMode; - RemoteDesktop_OverrideApplyWindowsKeyCombinations = group.RemoteDesktop_OverrideApplyWindowsKeyCombinations; - RemoteDesktop_KeyboardHookMode = group.RemoteDesktop_KeyboardHookMode; - RemoteDesktop_OverrideRedirectClipboard = group.RemoteDesktop_OverrideRedirectClipboard; - RemoteDesktop_RedirectClipboard = group.RemoteDesktop_RedirectClipboard; - RemoteDesktop_OverrideRedirectDevices = group.RemoteDesktop_OverrideRedirectDevices; - RemoteDesktop_RedirectDevices = group.RemoteDesktop_RedirectDevices; - RemoteDesktop_OverrideRedirectDrives = group.RemoteDesktop_OverrideRedirectDrives; - RemoteDesktop_RedirectDrives = group.RemoteDesktop_RedirectDrives; - RemoteDesktop_OverrideRedirectPorts = group.RemoteDesktop_OverrideRedirectPorts; - RemoteDesktop_RedirectPorts = group.RemoteDesktop_RedirectPorts; - RemoteDesktop_OverrideRedirectSmartcards = group.RemoteDesktop_OverrideRedirectSmartcards; - RemoteDesktop_RedirectSmartCards = group.RemoteDesktop_RedirectSmartCards; - RemoteDesktop_OverrideRedirectPrinters = group.RemoteDesktop_OverrideRedirectPrinters; - RemoteDesktop_RedirectPrinters = group.RemoteDesktop_RedirectPrinters; - RemoteDesktop_OverridePersistentBitmapCaching = group.RemoteDesktop_OverridePersistentBitmapCaching; - RemoteDesktop_PersistentBitmapCaching = group.RemoteDesktop_PersistentBitmapCaching; - RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = group.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - RemoteDesktop_ReconnectIfTheConnectionIsDropped = group.RemoteDesktop_ReconnectIfTheConnectionIsDropped; - RemoteDesktop_OverrideNetworkConnectionType = group.RemoteDesktop_OverrideNetworkConnectionType; - RemoteDesktop_NetworkConnectionType = group.RemoteDesktop_NetworkConnectionType; - RemoteDesktop_OverrideDesktopBackground = group.RemoteDesktop_OverrideDesktopBackground; - RemoteDesktop_DesktopBackground = group.RemoteDesktop_DesktopBackground; - RemoteDesktop_OverrideFontSmoothing = group.RemoteDesktop_OverrideFontSmoothing; - RemoteDesktop_FontSmoothing = group.RemoteDesktop_FontSmoothing; - RemoteDesktop_OverrideDesktopComposition = group.RemoteDesktop_OverrideDesktopComposition; - RemoteDesktop_DesktopComposition = group.RemoteDesktop_DesktopComposition; - RemoteDesktop_OverrideShowWindowContentsWhileDragging = group.RemoteDesktop_OverrideShowWindowContentsWhileDragging; - RemoteDesktop_ShowWindowContentsWhileDragging = group.RemoteDesktop_ShowWindowContentsWhileDragging; - RemoteDesktop_OverrideMenuAndWindowAnimation = group.RemoteDesktop_OverrideMenuAndWindowAnimation; - RemoteDesktop_MenuAndWindowAnimation = group.RemoteDesktop_MenuAndWindowAnimation; - RemoteDesktop_OverrideVisualStyles = group.RemoteDesktop_OverrideVisualStyles; - RemoteDesktop_VisualStyles = group.RemoteDesktop_VisualStyles; - - // PowerShell - PowerShell_OverrideCommand = group.PowerShell_OverrideCommand; - PowerShell_Command = group.PowerShell_Command; - PowerShell_OverrideAdditionalCommandLine = group.PowerShell_OverrideAdditionalCommandLine; - PowerShell_AdditionalCommandLine = group.PowerShell_AdditionalCommandLine; - PowerShell_OverrideExecutionPolicy = group.PowerShell_OverrideExecutionPolicy; - PowerShell_ExecutionPolicy = group.PowerShell_ExecutionPolicy; - - // PuTTY - PuTTY_OverrideUsername = group.PuTTY_OverrideUsername; - PuTTY_Username = group.PuTTY_Username; - PuTTY_OverridePrivateKeyFile = group.PuTTY_OverridePrivateKeyFile; - PuTTY_PrivateKeyFile = group.PuTTY_PrivateKeyFile; - PuTTY_OverrideProfile = group.PuTTY_OverrideProfile; - PuTTY_Profile = group.PuTTY_Profile; - PuTTY_OverrideEnableLog = group.PuTTY_OverrideEnableLog; - PuTTY_EnableLog = group.PuTTY_EnableLog; - PuTTY_OverrideLogMode = group.PuTTY_OverrideLogMode; - PuTTY_LogMode = group.PuTTY_LogMode; - PuTTY_OverrideLogPath = group.PuTTY_OverrideLogPath; - PuTTY_LogPath = group.PuTTY_LogPath; - PuTTY_OverrideLogFileName = group.PuTTY_OverrideLogFileName; - PuTTY_LogFileName = group.PuTTY_LogFileName; - PuTTY_OverrideAdditionalCommandLine = group.PuTTY_OverrideAdditionalCommandLine; - PuTTY_AdditionalCommandLine = group.PuTTY_AdditionalCommandLine; - - // AWS Session Manager - AWSSessionManager_OverrideProfile = group.AWSSessionManager_OverrideProfile; - AWSSessionManager_Profile = group.AWSSessionManager_Profile; - AWSSessionManager_OverrideRegion = group.AWSSessionManager_OverrideRegion; - AWSSessionManager_Region = group.AWSSessionManager_Region; - - // TigerVNC - TigerVNC_OverridePort = group.TigerVNC_OverridePort; - TigerVNC_Port = group.TigerVNC_Port; - } + Profiles = group.Profiles; + + // Remote Desktop + RemoteDesktop_UseCredentials = group.RemoteDesktop_UseCredentials; + RemoteDesktop_Username = group.RemoteDesktop_Username; + RemoteDesktop_Password = group.RemoteDesktop_Password; + RemoteDesktop_OverrideDisplay = group.RemoteDesktop_OverrideDisplay; + RemoteDesktop_AdjustScreenAutomatically = group.RemoteDesktop_AdjustScreenAutomatically; + RemoteDesktop_UseCurrentViewSize = group.RemoteDesktop_UseCurrentViewSize; + RemoteDesktop_UseFixedScreenSize = group.RemoteDesktop_UseFixedScreenSize; + RemoteDesktop_ScreenWidth = group.RemoteDesktop_ScreenWidth; + RemoteDesktop_ScreenHeight = group.RemoteDesktop_ScreenHeight; + RemoteDesktop_UseCustomScreenSize = group.RemoteDesktop_UseCustomScreenSize; + RemoteDesktop_CustomScreenWidth = group.RemoteDesktop_CustomScreenWidth; + RemoteDesktop_CustomScreenHeight = group.RemoteDesktop_CustomScreenHeight; + RemoteDesktop_OverrideColorDepth = group.RemoteDesktop_OverrideColorDepth; + RemoteDesktop_ColorDepth = group.RemoteDesktop_ColorDepth; + RemoteDesktop_OverridePort = group.RemoteDesktop_OverridePort; + RemoteDesktop_Port = group.RemoteDesktop_Port; + RemoteDesktop_OverrideCredSspSupport = group.RemoteDesktop_OverrideCredSspSupport; + RemoteDesktop_EnableCredSspSupport = group.RemoteDesktop_EnableCredSspSupport; + RemoteDesktop_OverrideAuthenticationLevel = group.RemoteDesktop_OverrideAuthenticationLevel; + RemoteDesktop_AuthenticationLevel = group.RemoteDesktop_AuthenticationLevel; + RemoteDesktop_OverrideAudioRedirectionMode = group.RemoteDesktop_OverrideAudioRedirectionMode; + RemoteDesktop_AudioRedirectionMode = group.RemoteDesktop_AudioRedirectionMode; + RemoteDesktop_OverrideAudioCaptureRedirectionMode = group.RemoteDesktop_OverrideAudioCaptureRedirectionMode; + RemoteDesktop_AudioCaptureRedirectionMode = group.RemoteDesktop_AudioCaptureRedirectionMode; + RemoteDesktop_OverrideApplyWindowsKeyCombinations = group.RemoteDesktop_OverrideApplyWindowsKeyCombinations; + RemoteDesktop_KeyboardHookMode = group.RemoteDesktop_KeyboardHookMode; + RemoteDesktop_OverrideRedirectClipboard = group.RemoteDesktop_OverrideRedirectClipboard; + RemoteDesktop_RedirectClipboard = group.RemoteDesktop_RedirectClipboard; + RemoteDesktop_OverrideRedirectDevices = group.RemoteDesktop_OverrideRedirectDevices; + RemoteDesktop_RedirectDevices = group.RemoteDesktop_RedirectDevices; + RemoteDesktop_OverrideRedirectDrives = group.RemoteDesktop_OverrideRedirectDrives; + RemoteDesktop_RedirectDrives = group.RemoteDesktop_RedirectDrives; + RemoteDesktop_OverrideRedirectPorts = group.RemoteDesktop_OverrideRedirectPorts; + RemoteDesktop_RedirectPorts = group.RemoteDesktop_RedirectPorts; + RemoteDesktop_OverrideRedirectSmartcards = group.RemoteDesktop_OverrideRedirectSmartcards; + RemoteDesktop_RedirectSmartCards = group.RemoteDesktop_RedirectSmartCards; + RemoteDesktop_OverrideRedirectPrinters = group.RemoteDesktop_OverrideRedirectPrinters; + RemoteDesktop_RedirectPrinters = group.RemoteDesktop_RedirectPrinters; + RemoteDesktop_OverridePersistentBitmapCaching = group.RemoteDesktop_OverridePersistentBitmapCaching; + RemoteDesktop_PersistentBitmapCaching = group.RemoteDesktop_PersistentBitmapCaching; + RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = group.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + RemoteDesktop_ReconnectIfTheConnectionIsDropped = group.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + RemoteDesktop_OverrideNetworkConnectionType = group.RemoteDesktop_OverrideNetworkConnectionType; + RemoteDesktop_NetworkConnectionType = group.RemoteDesktop_NetworkConnectionType; + RemoteDesktop_OverrideDesktopBackground = group.RemoteDesktop_OverrideDesktopBackground; + RemoteDesktop_DesktopBackground = group.RemoteDesktop_DesktopBackground; + RemoteDesktop_OverrideFontSmoothing = group.RemoteDesktop_OverrideFontSmoothing; + RemoteDesktop_FontSmoothing = group.RemoteDesktop_FontSmoothing; + RemoteDesktop_OverrideDesktopComposition = group.RemoteDesktop_OverrideDesktopComposition; + RemoteDesktop_DesktopComposition = group.RemoteDesktop_DesktopComposition; + RemoteDesktop_OverrideShowWindowContentsWhileDragging = group.RemoteDesktop_OverrideShowWindowContentsWhileDragging; + RemoteDesktop_ShowWindowContentsWhileDragging = group.RemoteDesktop_ShowWindowContentsWhileDragging; + RemoteDesktop_OverrideMenuAndWindowAnimation = group.RemoteDesktop_OverrideMenuAndWindowAnimation; + RemoteDesktop_MenuAndWindowAnimation = group.RemoteDesktop_MenuAndWindowAnimation; + RemoteDesktop_OverrideVisualStyles = group.RemoteDesktop_OverrideVisualStyles; + RemoteDesktop_VisualStyles = group.RemoteDesktop_VisualStyles; + + // PowerShell + PowerShell_OverrideCommand = group.PowerShell_OverrideCommand; + PowerShell_Command = group.PowerShell_Command; + PowerShell_OverrideAdditionalCommandLine = group.PowerShell_OverrideAdditionalCommandLine; + PowerShell_AdditionalCommandLine = group.PowerShell_AdditionalCommandLine; + PowerShell_OverrideExecutionPolicy = group.PowerShell_OverrideExecutionPolicy; + PowerShell_ExecutionPolicy = group.PowerShell_ExecutionPolicy; + + // PuTTY + PuTTY_OverrideUsername = group.PuTTY_OverrideUsername; + PuTTY_Username = group.PuTTY_Username; + PuTTY_OverridePrivateKeyFile = group.PuTTY_OverridePrivateKeyFile; + PuTTY_PrivateKeyFile = group.PuTTY_PrivateKeyFile; + PuTTY_OverrideProfile = group.PuTTY_OverrideProfile; + PuTTY_Profile = group.PuTTY_Profile; + PuTTY_OverrideEnableLog = group.PuTTY_OverrideEnableLog; + PuTTY_EnableLog = group.PuTTY_EnableLog; + PuTTY_OverrideLogMode = group.PuTTY_OverrideLogMode; + PuTTY_LogMode = group.PuTTY_LogMode; + PuTTY_OverrideLogPath = group.PuTTY_OverrideLogPath; + PuTTY_LogPath = group.PuTTY_LogPath; + PuTTY_OverrideLogFileName = group.PuTTY_OverrideLogFileName; + PuTTY_LogFileName = group.PuTTY_LogFileName; + PuTTY_OverrideAdditionalCommandLine = group.PuTTY_OverrideAdditionalCommandLine; + PuTTY_AdditionalCommandLine = group.PuTTY_AdditionalCommandLine; + + // AWS Session Manager + AWSSessionManager_OverrideProfile = group.AWSSessionManager_OverrideProfile; + AWSSessionManager_Profile = group.AWSSessionManager_Profile; + AWSSessionManager_OverrideRegion = group.AWSSessionManager_OverrideRegion; + AWSSessionManager_Region = group.AWSSessionManager_Region; + + // TigerVNC + TigerVNC_OverridePort = group.TigerVNC_OverridePort; + TigerVNC_Port = group.TigerVNC_Port; } } diff --git a/Source/NETworkManager.Profiles/GroupInfoSerializable.cs b/Source/NETworkManager.Profiles/GroupInfoSerializable.cs index c9e384098d..0b86dfcab4 100644 --- a/Source/NETworkManager.Profiles/GroupInfoSerializable.cs +++ b/Source/NETworkManager.Profiles/GroupInfoSerializable.cs @@ -1,27 +1,26 @@ using System.Collections.Generic; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public class GroupInfoSerializable : GroupInfo { - public class GroupInfoSerializable : GroupInfo - { - /// - /// Override the default profiles to make it serializable. - /// - public new List Profiles { get; set; } + /// + /// Override the default profiles to make it serializable. + /// + public new List Profiles { get; set; } - /// - /// Override the default remote desktop password to make it serializable. - /// - public new string RemoteDesktop_Password { get; set; } + /// + /// Override the default remote desktop password to make it serializable. + /// + public new string RemoteDesktop_Password { get; set; } - public GroupInfoSerializable() - { + public GroupInfoSerializable() + { - } + } - public GroupInfoSerializable(GroupInfo profileGroup) : base(profileGroup) - { + public GroupInfoSerializable(GroupInfo profileGroup) : base(profileGroup) + { - } } } diff --git a/Source/NETworkManager.Profiles/GroupViewInfo.cs b/Source/NETworkManager.Profiles/GroupViewInfo.cs index 49918729d7..a249cb537b 100644 --- a/Source/NETworkManager.Profiles/GroupViewInfo.cs +++ b/Source/NETworkManager.Profiles/GroupViewInfo.cs @@ -1,30 +1,29 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public class GroupViewInfo { - public class GroupViewInfo - { - public GroupViewName Name { get; set; } + public GroupViewName Name { get; set; } - public Canvas Icon { get; set; } + public Canvas Icon { get; set; } - public GroupViewInfo() - { - } + public GroupViewInfo() + { + } - public GroupViewInfo(GroupViewName name, Canvas icon) - { - Name = name; - Icon = icon; - } + public GroupViewInfo(GroupViewName name, Canvas icon) + { + Name = name; + Icon = icon; + } - public GroupViewInfo(GroupViewName name, UIElement uiElement) - { - Name = name; - var canvas = new Canvas(); - canvas.Children.Add(uiElement); - Icon = canvas; - } + public GroupViewInfo(GroupViewName name, UIElement uiElement) + { + Name = name; + var canvas = new Canvas(); + canvas.Children.Add(uiElement); + Icon = canvas; } } diff --git a/Source/NETworkManager.Profiles/GroupViewManager.cs b/Source/NETworkManager.Profiles/GroupViewManager.cs index 2f43c9907b..60da42d883 100644 --- a/Source/NETworkManager.Profiles/GroupViewManager.cs +++ b/Source/NETworkManager.Profiles/GroupViewManager.cs @@ -2,22 +2,21 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public static class GroupViewManager { - public static class GroupViewManager + // List of all applications + public static List List => new() { - // List of all applications - public static List List => new() - { - // General - new GroupViewInfo(GroupViewName.General, new PackIconModern{ Kind = PackIconModernKind.Box }), + // General + new GroupViewInfo(GroupViewName.General, new PackIconModern{ Kind = PackIconModernKind.Box }), - // Applications - new GroupViewInfo(GroupViewName.RemoteDesktop, ApplicationManager.GetIcon(ApplicationName.RemoteDesktop)), - new GroupViewInfo(GroupViewName.PowerShell, ApplicationManager.GetIcon(ApplicationName.PowerShell)), - new GroupViewInfo(GroupViewName.PuTTY, ApplicationManager.GetIcon(ApplicationName.PuTTY)), - new GroupViewInfo(GroupViewName.AWSSessionManager, ApplicationManager.GetIcon(ApplicationName.AWSSessionManager)), - new GroupViewInfo(GroupViewName.TigerVNC, ApplicationManager.GetIcon(ApplicationName.TigerVNC)) - }; - } + // Applications + new GroupViewInfo(GroupViewName.RemoteDesktop, ApplicationManager.GetIcon(ApplicationName.RemoteDesktop)), + new GroupViewInfo(GroupViewName.PowerShell, ApplicationManager.GetIcon(ApplicationName.PowerShell)), + new GroupViewInfo(GroupViewName.PuTTY, ApplicationManager.GetIcon(ApplicationName.PuTTY)), + new GroupViewInfo(GroupViewName.AWSSessionManager, ApplicationManager.GetIcon(ApplicationName.AWSSessionManager)), + new GroupViewInfo(GroupViewName.TigerVNC, ApplicationManager.GetIcon(ApplicationName.TigerVNC)) + }; } diff --git a/Source/NETworkManager.Profiles/GroupViewName.cs b/Source/NETworkManager.Profiles/GroupViewName.cs index c389e1aec5..79420f747e 100644 --- a/Source/NETworkManager.Profiles/GroupViewName.cs +++ b/Source/NETworkManager.Profiles/GroupViewName.cs @@ -1,12 +1,11 @@ -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public enum GroupViewName { - public enum GroupViewName - { - General, - RemoteDesktop, - PowerShell, - PuTTY, - AWSSessionManager, - TigerVNC - } + General, + RemoteDesktop, + PowerShell, + PuTTY, + AWSSessionManager, + TigerVNC } diff --git a/Source/NETworkManager.Profiles/IProfileManager.cs b/Source/NETworkManager.Profiles/IProfileManager.cs index e3966d05d1..415f6af60b 100644 --- a/Source/NETworkManager.Profiles/IProfileManager.cs +++ b/Source/NETworkManager.Profiles/IProfileManager.cs @@ -1,15 +1,14 @@ using System.ComponentModel; using System.Windows.Input; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public interface IProfileManager : IProfileManagerMinimal { - public interface IProfileManager : IProfileManagerMinimal - { - ICollectionView Profiles { get; } - ICommand AddProfileCommand { get; } - ICommand EditProfileCommand { get; } - ICommand CopyAsProfileCommand { get; } - ICommand DeleteProfileCommand { get; } - ICommand EditGroupCommand { get; } - } + ICollectionView Profiles { get; } + ICommand AddProfileCommand { get; } + ICommand EditProfileCommand { get; } + ICommand CopyAsProfileCommand { get; } + ICommand DeleteProfileCommand { get; } + ICommand EditGroupCommand { get; } } diff --git a/Source/NETworkManager.Profiles/IProfileManagerMinimal.cs b/Source/NETworkManager.Profiles/IProfileManagerMinimal.cs index 9485dc9f42..9de4bb5cb0 100644 --- a/Source/NETworkManager.Profiles/IProfileManagerMinimal.cs +++ b/Source/NETworkManager.Profiles/IProfileManagerMinimal.cs @@ -1,19 +1,18 @@ -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +/// +/// Interface for the profile manager. +/// Minimal implementation to get the view model. +/// +public interface IProfileManagerMinimal { /// - /// Interface for the profile manager. - /// Minimal implementation to get the view model. + /// Event is fired when the profile dialog is opened. /// - public interface IProfileManagerMinimal - { - /// - /// Event is fired when the profile dialog is opened. - /// - void OnProfileDialogOpen(); + void OnProfileDialogOpen(); - /// - /// Event is fired when the profile dialog is closed. - /// - void OnProfileDialogClose(); - } + /// + /// Event is fired when the profile dialog is closed. + /// + void OnProfileDialogClose(); } diff --git a/Source/NETworkManager.Profiles/ProfileEditMode.cs b/Source/NETworkManager.Profiles/ProfileEditMode.cs index a2f1fdf8b3..f07a3b03cc 100644 --- a/Source/NETworkManager.Profiles/ProfileEditMode.cs +++ b/Source/NETworkManager.Profiles/ProfileEditMode.cs @@ -1,9 +1,8 @@ -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public enum ProfileEditMode { - public enum ProfileEditMode - { - Add, - Edit, - Copy - } + Add, + Edit, + Copy } diff --git a/Source/NETworkManager.Profiles/ProfileFileInfo.cs b/Source/NETworkManager.Profiles/ProfileFileInfo.cs index 7d81e3f00f..1bd411a1a0 100644 --- a/Source/NETworkManager.Profiles/ProfileFileInfo.cs +++ b/Source/NETworkManager.Profiles/ProfileFileInfo.cs @@ -1,75 +1,73 @@ -using NETworkManager.Utilities; -using System; +using System; using System.Security; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public class ProfileFileInfo { - public class ProfileFileInfo - { - /// - /// Make object unique. - /// - private Guid ID { get; } + /// + /// Make object unique. + /// + private Guid ID { get; } - /// - /// Name of the profile. This is the filename without extension. - /// - public string Name { get; set; } + /// + /// Name of the profile. This is the filename without extension. + /// + public string Name { get; set; } - /// - /// Full path of the profile file. - /// - public string Path { get; set; } + /// + /// Full path of the profile file. + /// + public string Path { get; set; } - /// - /// Indicates if the profile file is encrypted. - /// - public bool IsEncrypted { get; set; } + /// + /// Indicates if the profile file is encrypted. + /// + public bool IsEncrypted { get; set; } - /// - /// Password to encrypt and decrypt the profile file. - /// - public SecureString Password { get; set; } + /// + /// Password to encrypt and decrypt the profile file. + /// + public SecureString Password { get; set; } - /// - /// Indicates if the password is valid and can be used for encryption or decryption. - /// - public bool IsPasswordValid { get; set; } + /// + /// Indicates if the password is valid and can be used for encryption or decryption. + /// + public bool IsPasswordValid { get; set; } - /// - /// Profile file info contains all necessary informations about the profile file and location. - /// - /// of the profile file. - /// of the profile file. - /// indicates if the file is encrypted. - public ProfileFileInfo(string name, string path, bool isEncrypted = false) - { - ID = Guid.NewGuid(); - Name = name; - Path = path; - IsEncrypted = isEncrypted; - } + /// + /// Profile file info contains all necessary informations about the profile file and location. + /// + /// of the profile file. + /// of the profile file. + /// indicates if the file is encrypted. + public ProfileFileInfo(string name, string path, bool isEncrypted = false) + { + ID = Guid.NewGuid(); + Name = name; + Path = path; + IsEncrypted = isEncrypted; + } - /// - /// Overrides the default method. - /// - /// Object from type . - /// Returns true if the is equal to another . - public override bool Equals(object obj) - { - if (obj is not ProfileFileInfo info) - return false; + /// + /// Overrides the default method. + /// + /// Object from type . + /// Returns true if the is equal to another . + public override bool Equals(object obj) + { + if (obj is not ProfileFileInfo info) + return false; - return info.ID == ID; - } + return info.ID == ID; + } - /// - /// Overrides the default GetHashCode() method. - /// - /// Return the hashcodes generated by the path of the . - public override int GetHashCode() - { - return ID.GetHashCode(); - } + /// + /// Overrides the default GetHashCode() method. + /// + /// Return the hashcodes generated by the path of the . + public override int GetHashCode() + { + return ID.GetHashCode(); } } diff --git a/Source/NETworkManager.Profiles/ProfileFileInfoArgs.cs b/Source/NETworkManager.Profiles/ProfileFileInfoArgs.cs index c9e5d0c56a..6ebe6808aa 100644 --- a/Source/NETworkManager.Profiles/ProfileFileInfoArgs.cs +++ b/Source/NETworkManager.Profiles/ProfileFileInfoArgs.cs @@ -1,15 +1,14 @@ using System; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public class ProfileFileInfoArgs : EventArgs { - public class ProfileFileInfoArgs : EventArgs - { - public ProfileFileInfo ProfileFileInfo { get; set; } + public ProfileFileInfo ProfileFileInfo { get; set; } - public ProfileFileInfoArgs(ProfileFileInfo profileFileInfo) - { - ProfileFileInfo = profileFileInfo; - } + public ProfileFileInfoArgs(ProfileFileInfo profileFileInfo) + { + ProfileFileInfo = profileFileInfo; } } diff --git a/Source/NETworkManager.Profiles/ProfileInfo.cs b/Source/NETworkManager.Profiles/ProfileInfo.cs index 20f9375ce8..65e3143473 100644 --- a/Source/NETworkManager.Profiles/ProfileInfo.cs +++ b/Source/NETworkManager.Profiles/ProfileInfo.cs @@ -5,379 +5,378 @@ using System.Security; using System.Xml.Serialization; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +/// +/// Class represents a profile. +/// +public class ProfileInfo { /// - /// Class represents a profile. + /// Name of the profile. + /// + public string Name { get; set; } + + /// + /// Hostname or IP address of the host. + /// + public string Host { get; set; } + + /// + /// Name of the group. Profiles are grouped based on the name. + /// + public string Group { get; set; } + + /// + /// Tags to classify the profiles and to filter by it. + /// + public string Tags { get; set; } + + /// + /// Dynamic profiles (e.g. AWS) are not save to file. + /// + public bool IsDynamic { get; set; } + + public bool NetworkInterface_Enabled { get; set; } + public bool NetworkInterface_EnableStaticIPAddress { get; set; } + public string NetworkInterface_IPAddress { get; set; } + public string NetworkInterface_SubnetmaskOrCidr { get; set; } + public string NetworkInterface_Gateway { get; set; } + public bool NetworkInterface_EnableStaticDNS { get; set; } + public string NetworkInterface_PrimaryDNSServer { get; set; } + public string NetworkInterface_SecondaryDNSServer { get; set; } + + public bool IPScanner_Enabled { get; set; } + public bool IPScanner_InheritHost { get; set; } = true; + public string IPScanner_HostOrIPRange { get; set; } + + public bool PortScanner_Enabled { get; set; } + public bool PortScanner_InheritHost { get; set; } = true; + public string PortScanner_Host { get; set; } + public string PortScanner_Ports { get; set; } + + public bool PingMonitor_Enabled { get; set; } + public bool PingMonitor_InheritHost { get; set; } = true; + public string PingMonitor_Host { get; set; } + + public bool Traceroute_Enabled { get; set; } + public bool Traceroute_InheritHost { get; set; } = true; + public string Traceroute_Host { get; set; } + + public bool DNSLookup_Enabled { get; set; } + public bool DNSLookup_InheritHost { get; set; } = true; + public string DNSLookup_Host { get; set; } + + public bool RemoteDesktop_Enabled { get; set; } + public bool RemoteDesktop_InheritHost { get; set; } = true; + public string RemoteDesktop_Host { get; set; } + + public bool RemoteDesktop_UseCredentials { get; set; } + + public string RemoteDesktop_Username { get; set; } + + [XmlIgnore] + public SecureString RemoteDesktop_Password { get; set; } + public bool RemoteDesktop_OverrideDisplay { get; set; } + public bool RemoteDesktop_AdjustScreenAutomatically { get; set; } + public bool RemoteDesktop_UseCurrentViewSize { get; set; } + public bool RemoteDesktop_UseFixedScreenSize { get; set; } = true; + public int RemoteDesktop_ScreenWidth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenWidth; + public int RemoteDesktop_ScreenHeight { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenHeight; + public bool RemoteDesktop_UseCustomScreenSize { get; set; } + public int RemoteDesktop_CustomScreenWidth { get; set; } + public int RemoteDesktop_CustomScreenHeight { get; set; } + public bool RemoteDesktop_OverrideColorDepth { get; set; } + public int RemoteDesktop_ColorDepth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ColorDepth; + public bool RemoteDesktop_OverridePort { get; set; } + public int RemoteDesktop_Port { get; set; } = GlobalStaticConfiguration.RemoteDesktop_Port; + public bool RemoteDesktop_OverrideCredSspSupport { get; set; } + public bool RemoteDesktop_EnableCredSspSupport { get; set; } + public bool RemoteDesktop_OverrideAuthenticationLevel { get; set; } + public uint RemoteDesktop_AuthenticationLevel { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AuthenticationLevel; + public bool RemoteDesktop_OverrideAudioRedirectionMode { get; set; } + public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioRedirectionMode; + public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode { get; set; } + public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioCaptureRedirectionMode; + public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations { get; set; } + public KeyboardHookMode RemoteDesktop_KeyboardHookMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_KeyboardHookMode; + public bool RemoteDesktop_OverrideRedirectClipboard { get; set; } + public bool RemoteDesktop_RedirectClipboard { get; set; } = true; + public bool RemoteDesktop_OverrideRedirectDevices { get; set; } + public bool RemoteDesktop_RedirectDevices { get; set; } + public bool RemoteDesktop_OverrideRedirectDrives { get; set; } + public bool RemoteDesktop_RedirectDrives { get; set; } + public bool RemoteDesktop_OverrideRedirectPorts { get; set; } + public bool RemoteDesktop_RedirectPorts { get; set; } + public bool RemoteDesktop_OverrideRedirectSmartcards { get; set; } + public bool RemoteDesktop_RedirectSmartCards { get; set; } + public bool RemoteDesktop_OverrideRedirectPrinters { get; set; } + public bool RemoteDesktop_RedirectPrinters { get; set; } + public bool RemoteDesktop_OverridePersistentBitmapCaching { get; set; } + public bool RemoteDesktop_PersistentBitmapCaching { get; set; } + public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped { get; set; } + public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped { get; set; } + public bool RemoteDesktop_OverrideNetworkConnectionType { get; set; } + public NetworkConnectionType RemoteDesktop_NetworkConnectionType { get; set; } + public bool RemoteDesktop_OverrideDesktopBackground { get; set; } + public bool RemoteDesktop_DesktopBackground { get; set; } + public bool RemoteDesktop_OverrideFontSmoothing { get; set; } + public bool RemoteDesktop_FontSmoothing { get; set; } + public bool RemoteDesktop_OverrideDesktopComposition { get; set; } + public bool RemoteDesktop_DesktopComposition { get; set; } + public bool RemoteDesktop_OverrideShowWindowContentsWhileDragging { get; set; } + public bool RemoteDesktop_ShowWindowContentsWhileDragging { get; set; } + public bool RemoteDesktop_OverrideMenuAndWindowAnimation { get; set; } + public bool RemoteDesktop_MenuAndWindowAnimation { get; set; } + public bool RemoteDesktop_OverrideVisualStyles { get; set; } + public bool RemoteDesktop_VisualStyles { get; set; } + + public bool PowerShell_Enabled { get; set; } + public bool PowerShell_EnableRemoteConsole { get; set; } = true; + public bool PowerShell_InheritHost { get; set; } = true; + public string PowerShell_Host { get; set; } + public bool PowerShell_OverrideCommand { get; set; } + public string PowerShell_Command { get; set; } + public bool PowerShell_OverrideAdditionalCommandLine { get; set; } + public string PowerShell_AdditionalCommandLine { get; set; } + public bool PowerShell_OverrideExecutionPolicy { get; set; } + public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy { get; set; } + + public bool PuTTY_Enabled { get; set; } + public ConnectionMode PuTTY_ConnectionMode { get; set; } + public bool PuTTY_InheritHost { get; set; } = true; + public string PuTTY_HostOrSerialLine { get; set; } + public bool PuTTY_OverridePortOrBaud { get; set; } + public int PuTTY_PortOrBaud { get; set; } + public bool PuTTY_OverrideUsername { get; set; } + public string PuTTY_Username { get; set; } + public bool PuTTY_OverridePrivateKeyFile { get; set; } + public string PuTTY_PrivateKeyFile { get; set; } + public bool PuTTY_OverrideProfile { get; set; } + public string PuTTY_Profile { get; set; } + public bool PuTTY_OverrideHostkey { get; set; } + public string PuTTY_Hostkey { get; set; } + public bool PuTTY_OverrideEnableLog { get; set; } + public bool PuTTY_EnableLog { get; set; } + public bool PuTTY_OverrideLogMode { get; set; } + public LogMode PuTTY_LogMode { get; set; } = GlobalStaticConfiguration.PuTTY_LogMode; + public bool PuTTY_OverrideLogPath { get; set; } + public string PuTTY_LogPath { get; set; } = GlobalStaticConfiguration.PuTTY_LogPath; + public bool PuTTY_OverrideLogFileName { get; set; } + public string PuTTY_LogFileName { get; set; } = GlobalStaticConfiguration.PuTTY_LogFileName; + public bool PuTTY_OverrideAdditionalCommandLine { get; set; } + public string PuTTY_AdditionalCommandLine { get; set; } + + public bool AWSSessionManager_Enabled { get; set; } + public string AWSSessionManager_InstanceID { get; set; } + public bool AWSSessionManager_OverrideProfile { get; set; } + public string AWSSessionManager_Profile { get; set; } + public bool AWSSessionManager_OverrideRegion { get; set; } + public string AWSSessionManager_Region { get; set; } + + public bool TigerVNC_Enabled { get; set; } + public bool TigerVNC_InheritHost { get; set; } = true; + public string TigerVNC_Host { get; set; } + public bool TigerVNC_OverridePort { get; set; } + public int TigerVNC_Port { get; set; } + + public bool WebConsole_Enabled { get; set; } + public string WebConsole_Url { get; set; } + + public bool WakeOnLAN_Enabled { get; set; } + public string WakeOnLAN_MACAddress { get; set; } + public string WakeOnLAN_Broadcast { get; set; } + public bool WakeOnLAN_OverridePort { get; set; } + public int WakeOnLAN_Port { get; set; } + + public bool Whois_Enabled { get; set; } + public bool Whois_InheritHost { get; set; } = true; + public string Whois_Domain { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public ProfileInfo() + { + + } + + /// + /// Initializes a new instance of the class with properties. /// - public class ProfileInfo + public ProfileInfo(ProfileInfo profile) { - /// - /// Name of the profile. - /// - public string Name { get; set; } - - /// - /// Hostname or IP address of the host. - /// - public string Host { get; set; } - - /// - /// Name of the group. Profiles are grouped based on the name. - /// - public string Group { get; set; } - - /// - /// Tags to classify the profiles and to filter by it. - /// - public string Tags { get; set; } - - /// - /// Dynamic profiles (e.g. AWS) are not save to file. - /// - public bool IsDynamic { get; set; } - - public bool NetworkInterface_Enabled { get; set; } - public bool NetworkInterface_EnableStaticIPAddress { get; set; } - public string NetworkInterface_IPAddress { get; set; } - public string NetworkInterface_SubnetmaskOrCidr { get; set; } - public string NetworkInterface_Gateway { get; set; } - public bool NetworkInterface_EnableStaticDNS { get; set; } - public string NetworkInterface_PrimaryDNSServer { get; set; } - public string NetworkInterface_SecondaryDNSServer { get; set; } - - public bool IPScanner_Enabled { get; set; } - public bool IPScanner_InheritHost { get; set; } = true; - public string IPScanner_HostOrIPRange { get; set; } - - public bool PortScanner_Enabled { get; set; } - public bool PortScanner_InheritHost { get; set; } = true; - public string PortScanner_Host { get; set; } - public string PortScanner_Ports { get; set; } - - public bool PingMonitor_Enabled { get; set; } - public bool PingMonitor_InheritHost { get; set; } = true; - public string PingMonitor_Host { get; set; } - - public bool Traceroute_Enabled { get; set; } - public bool Traceroute_InheritHost { get; set; } = true; - public string Traceroute_Host { get; set; } - - public bool DNSLookup_Enabled { get; set; } - public bool DNSLookup_InheritHost { get; set; } = true; - public string DNSLookup_Host { get; set; } - - public bool RemoteDesktop_Enabled { get; set; } - public bool RemoteDesktop_InheritHost { get; set; } = true; - public string RemoteDesktop_Host { get; set; } - - public bool RemoteDesktop_UseCredentials { get; set; } - - public string RemoteDesktop_Username { get; set; } - - [XmlIgnore] - public SecureString RemoteDesktop_Password { get; set; } - public bool RemoteDesktop_OverrideDisplay { get; set; } - public bool RemoteDesktop_AdjustScreenAutomatically { get; set; } - public bool RemoteDesktop_UseCurrentViewSize { get; set; } - public bool RemoteDesktop_UseFixedScreenSize { get; set; } = true; - public int RemoteDesktop_ScreenWidth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenWidth; - public int RemoteDesktop_ScreenHeight { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ScreenHeight; - public bool RemoteDesktop_UseCustomScreenSize { get; set; } - public int RemoteDesktop_CustomScreenWidth { get; set; } - public int RemoteDesktop_CustomScreenHeight { get; set; } - public bool RemoteDesktop_OverrideColorDepth { get; set; } - public int RemoteDesktop_ColorDepth { get; set; } = GlobalStaticConfiguration.RemoteDesktop_ColorDepth; - public bool RemoteDesktop_OverridePort { get; set; } - public int RemoteDesktop_Port { get; set; } = GlobalStaticConfiguration.RemoteDesktop_Port; - public bool RemoteDesktop_OverrideCredSspSupport { get; set; } - public bool RemoteDesktop_EnableCredSspSupport { get; set; } - public bool RemoteDesktop_OverrideAuthenticationLevel { get; set; } - public uint RemoteDesktop_AuthenticationLevel { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AuthenticationLevel; - public bool RemoteDesktop_OverrideAudioRedirectionMode { get; set; } - public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioRedirectionMode; - public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode { get; set; } - public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_AudioCaptureRedirectionMode; - public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations { get; set; } - public KeyboardHookMode RemoteDesktop_KeyboardHookMode { get; set; } = GlobalStaticConfiguration.RemoteDesktop_KeyboardHookMode; - public bool RemoteDesktop_OverrideRedirectClipboard { get; set; } - public bool RemoteDesktop_RedirectClipboard { get; set; } = true; - public bool RemoteDesktop_OverrideRedirectDevices { get; set; } - public bool RemoteDesktop_RedirectDevices { get; set; } - public bool RemoteDesktop_OverrideRedirectDrives { get; set; } - public bool RemoteDesktop_RedirectDrives { get; set; } - public bool RemoteDesktop_OverrideRedirectPorts { get; set; } - public bool RemoteDesktop_RedirectPorts { get; set; } - public bool RemoteDesktop_OverrideRedirectSmartcards { get; set; } - public bool RemoteDesktop_RedirectSmartCards { get; set; } - public bool RemoteDesktop_OverrideRedirectPrinters { get; set; } - public bool RemoteDesktop_RedirectPrinters { get; set; } - public bool RemoteDesktop_OverridePersistentBitmapCaching { get; set; } - public bool RemoteDesktop_PersistentBitmapCaching { get; set; } - public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped { get; set; } - public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped { get; set; } - public bool RemoteDesktop_OverrideNetworkConnectionType { get; set; } - public NetworkConnectionType RemoteDesktop_NetworkConnectionType { get; set; } - public bool RemoteDesktop_OverrideDesktopBackground { get; set; } - public bool RemoteDesktop_DesktopBackground { get; set; } - public bool RemoteDesktop_OverrideFontSmoothing { get; set; } - public bool RemoteDesktop_FontSmoothing { get; set; } - public bool RemoteDesktop_OverrideDesktopComposition { get; set; } - public bool RemoteDesktop_DesktopComposition { get; set; } - public bool RemoteDesktop_OverrideShowWindowContentsWhileDragging { get; set; } - public bool RemoteDesktop_ShowWindowContentsWhileDragging { get; set; } - public bool RemoteDesktop_OverrideMenuAndWindowAnimation { get; set; } - public bool RemoteDesktop_MenuAndWindowAnimation { get; set; } - public bool RemoteDesktop_OverrideVisualStyles { get; set; } - public bool RemoteDesktop_VisualStyles { get; set; } - - public bool PowerShell_Enabled { get; set; } - public bool PowerShell_EnableRemoteConsole { get; set; } = true; - public bool PowerShell_InheritHost { get; set; } = true; - public string PowerShell_Host { get; set; } - public bool PowerShell_OverrideCommand { get; set; } - public string PowerShell_Command { get; set; } - public bool PowerShell_OverrideAdditionalCommandLine { get; set; } - public string PowerShell_AdditionalCommandLine { get; set; } - public bool PowerShell_OverrideExecutionPolicy { get; set; } - public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy { get; set; } - - public bool PuTTY_Enabled { get; set; } - public ConnectionMode PuTTY_ConnectionMode { get; set; } - public bool PuTTY_InheritHost { get; set; } = true; - public string PuTTY_HostOrSerialLine { get; set; } - public bool PuTTY_OverridePortOrBaud { get; set; } - public int PuTTY_PortOrBaud { get; set; } - public bool PuTTY_OverrideUsername { get; set; } - public string PuTTY_Username { get; set; } - public bool PuTTY_OverridePrivateKeyFile { get; set; } - public string PuTTY_PrivateKeyFile { get; set; } - public bool PuTTY_OverrideProfile { get; set; } - public string PuTTY_Profile { get; set; } - public bool PuTTY_OverrideHostkey { get; set; } - public string PuTTY_Hostkey { get; set; } - public bool PuTTY_OverrideEnableLog { get; set; } - public bool PuTTY_EnableLog { get; set; } - public bool PuTTY_OverrideLogMode { get; set; } - public LogMode PuTTY_LogMode { get; set; } = GlobalStaticConfiguration.PuTTY_LogMode; - public bool PuTTY_OverrideLogPath { get; set; } - public string PuTTY_LogPath { get; set; } = GlobalStaticConfiguration.PuTTY_LogPath; - public bool PuTTY_OverrideLogFileName { get; set; } - public string PuTTY_LogFileName { get; set; } = GlobalStaticConfiguration.PuTTY_LogFileName; - public bool PuTTY_OverrideAdditionalCommandLine { get; set; } - public string PuTTY_AdditionalCommandLine { get; set; } - - public bool AWSSessionManager_Enabled { get; set; } - public string AWSSessionManager_InstanceID { get; set; } - public bool AWSSessionManager_OverrideProfile { get; set; } - public string AWSSessionManager_Profile { get; set; } - public bool AWSSessionManager_OverrideRegion { get; set; } - public string AWSSessionManager_Region { get; set; } - - public bool TigerVNC_Enabled { get; set; } - public bool TigerVNC_InheritHost { get; set; } = true; - public string TigerVNC_Host { get; set; } - public bool TigerVNC_OverridePort { get; set; } - public int TigerVNC_Port { get; set; } - - public bool WebConsole_Enabled { get; set; } - public string WebConsole_Url { get; set; } - - public bool WakeOnLAN_Enabled { get; set; } - public string WakeOnLAN_MACAddress { get; set; } - public string WakeOnLAN_Broadcast { get; set; } - public bool WakeOnLAN_OverridePort { get; set; } - public int WakeOnLAN_Port { get; set; } - - public bool Whois_Enabled { get; set; } - public bool Whois_InheritHost { get; set; } = true; - public string Whois_Domain { get; set; } - - /// - /// Initializes a new instance of the class. - /// - public ProfileInfo() - { - - } - - /// - /// Initializes a new instance of the class with properties. - /// - public ProfileInfo(ProfileInfo profile) - { - Name = profile.Name; - Host = profile.Host; - Group = profile.Group; - Tags = profile.Tags; - - IsDynamic = profile.IsDynamic; - - // Network Interface - NetworkInterface_Enabled = profile.NetworkInterface_Enabled; - NetworkInterface_EnableStaticIPAddress = profile.NetworkInterface_EnableStaticIPAddress; - NetworkInterface_IPAddress = profile.NetworkInterface_IPAddress; - NetworkInterface_SubnetmaskOrCidr = profile.NetworkInterface_SubnetmaskOrCidr; - NetworkInterface_Gateway = profile.NetworkInterface_Gateway; - NetworkInterface_EnableStaticDNS = profile.NetworkInterface_EnableStaticDNS; - NetworkInterface_PrimaryDNSServer = profile.NetworkInterface_PrimaryDNSServer; - NetworkInterface_SecondaryDNSServer = profile.NetworkInterface_SecondaryDNSServer; - - // IP Scanner - IPScanner_Enabled = profile.IPScanner_Enabled; - IPScanner_InheritHost = profile.IPScanner_InheritHost; - IPScanner_HostOrIPRange = profile.IPScanner_HostOrIPRange; - - // Port Scanner - PortScanner_Enabled = profile.PortScanner_Enabled; - PortScanner_InheritHost = profile.PortScanner_InheritHost; - PortScanner_Host = profile.PortScanner_Host; - PortScanner_Ports = profile.PortScanner_Ports; - - // Ping Monitor - PingMonitor_Enabled = profile.PingMonitor_Enabled; - PingMonitor_InheritHost = profile.PingMonitor_InheritHost; - PingMonitor_Host = profile.PingMonitor_Host; - - // Traceroute - Traceroute_Enabled = profile.Traceroute_Enabled; - Traceroute_InheritHost = profile.Traceroute_InheritHost; - Traceroute_Host = profile.Traceroute_Host; - - // DNS Lookup - DNSLookup_Enabled = profile.DNSLookup_Enabled; - DNSLookup_InheritHost = profile.DNSLookup_InheritHost; - DNSLookup_Host = profile.DNSLookup_Host; - - // Remote Desktop - RemoteDesktop_Enabled = profile.RemoteDesktop_Enabled; - RemoteDesktop_InheritHost = profile.RemoteDesktop_InheritHost; - RemoteDesktop_Host = profile.RemoteDesktop_Host; - RemoteDesktop_UseCredentials = profile.RemoteDesktop_UseCredentials; - RemoteDesktop_Username = profile.RemoteDesktop_Username; - RemoteDesktop_Password = profile.RemoteDesktop_Password; - RemoteDesktop_OverrideDisplay = profile.RemoteDesktop_OverrideDisplay; - RemoteDesktop_AdjustScreenAutomatically = profile.RemoteDesktop_AdjustScreenAutomatically; - RemoteDesktop_UseCurrentViewSize = profile.RemoteDesktop_UseCurrentViewSize; - RemoteDesktop_UseFixedScreenSize = profile.RemoteDesktop_UseFixedScreenSize; - RemoteDesktop_ScreenWidth = profile.RemoteDesktop_ScreenWidth; - RemoteDesktop_ScreenHeight = profile.RemoteDesktop_ScreenHeight; - RemoteDesktop_UseCustomScreenSize = profile.RemoteDesktop_UseCustomScreenSize; - RemoteDesktop_CustomScreenWidth = profile.RemoteDesktop_CustomScreenWidth; - RemoteDesktop_CustomScreenHeight = profile.RemoteDesktop_CustomScreenHeight; - RemoteDesktop_OverrideColorDepth = profile.RemoteDesktop_OverrideColorDepth; - RemoteDesktop_ColorDepth = profile.RemoteDesktop_ColorDepth; - RemoteDesktop_OverridePort = profile.RemoteDesktop_OverridePort; - RemoteDesktop_Port = profile.RemoteDesktop_Port; - RemoteDesktop_OverrideCredSspSupport = profile.RemoteDesktop_OverrideCredSspSupport; - RemoteDesktop_EnableCredSspSupport = profile.RemoteDesktop_EnableCredSspSupport; - RemoteDesktop_OverrideAuthenticationLevel = profile.RemoteDesktop_OverrideAuthenticationLevel; - RemoteDesktop_AuthenticationLevel = profile.RemoteDesktop_AuthenticationLevel; - RemoteDesktop_OverrideAudioRedirectionMode = profile.RemoteDesktop_OverrideAudioRedirectionMode; - RemoteDesktop_AudioRedirectionMode = profile.RemoteDesktop_AudioRedirectionMode; - RemoteDesktop_OverrideAudioCaptureRedirectionMode = profile.RemoteDesktop_OverrideAudioCaptureRedirectionMode; - RemoteDesktop_AudioCaptureRedirectionMode = profile.RemoteDesktop_AudioCaptureRedirectionMode; - RemoteDesktop_OverrideApplyWindowsKeyCombinations = profile.RemoteDesktop_OverrideApplyWindowsKeyCombinations; - RemoteDesktop_KeyboardHookMode = profile.RemoteDesktop_KeyboardHookMode; - RemoteDesktop_OverrideRedirectClipboard = profile.RemoteDesktop_OverrideRedirectClipboard; - RemoteDesktop_RedirectClipboard = profile.RemoteDesktop_RedirectClipboard; - RemoteDesktop_OverrideRedirectDevices = profile.RemoteDesktop_OverrideRedirectDevices; - RemoteDesktop_RedirectDevices = profile.RemoteDesktop_RedirectDevices; - RemoteDesktop_OverrideRedirectDrives = profile.RemoteDesktop_OverrideRedirectDrives; - RemoteDesktop_RedirectDrives = profile.RemoteDesktop_RedirectDrives; - RemoteDesktop_OverrideRedirectPorts = profile.RemoteDesktop_OverrideRedirectPorts; - RemoteDesktop_RedirectPorts = profile.RemoteDesktop_RedirectPorts; - RemoteDesktop_OverrideRedirectSmartcards = profile.RemoteDesktop_OverrideRedirectSmartcards; - RemoteDesktop_RedirectSmartCards = profile.RemoteDesktop_RedirectSmartCards; - RemoteDesktop_OverrideRedirectPrinters = profile.RemoteDesktop_OverrideRedirectPrinters; - RemoteDesktop_RedirectPrinters = profile.RemoteDesktop_RedirectPrinters; - RemoteDesktop_OverridePersistentBitmapCaching = profile.RemoteDesktop_OverridePersistentBitmapCaching; - RemoteDesktop_PersistentBitmapCaching = profile.RemoteDesktop_PersistentBitmapCaching; - RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = profile.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - RemoteDesktop_ReconnectIfTheConnectionIsDropped = profile.RemoteDesktop_ReconnectIfTheConnectionIsDropped; - RemoteDesktop_OverrideNetworkConnectionType = profile.RemoteDesktop_OverrideNetworkConnectionType; - RemoteDesktop_NetworkConnectionType = profile.RemoteDesktop_NetworkConnectionType; - RemoteDesktop_OverrideDesktopBackground = profile.RemoteDesktop_OverrideDesktopBackground; - RemoteDesktop_DesktopBackground = profile.RemoteDesktop_DesktopBackground; - RemoteDesktop_OverrideFontSmoothing = profile.RemoteDesktop_OverrideFontSmoothing; - RemoteDesktop_FontSmoothing = profile.RemoteDesktop_FontSmoothing; - RemoteDesktop_OverrideDesktopComposition = profile.RemoteDesktop_OverrideDesktopComposition; - RemoteDesktop_DesktopComposition = profile.RemoteDesktop_DesktopComposition; - RemoteDesktop_OverrideShowWindowContentsWhileDragging = profile.RemoteDesktop_OverrideShowWindowContentsWhileDragging; - RemoteDesktop_ShowWindowContentsWhileDragging = profile.RemoteDesktop_ShowWindowContentsWhileDragging; - RemoteDesktop_OverrideMenuAndWindowAnimation = profile.RemoteDesktop_OverrideMenuAndWindowAnimation; - RemoteDesktop_MenuAndWindowAnimation = profile.RemoteDesktop_MenuAndWindowAnimation; - RemoteDesktop_OverrideVisualStyles = profile.RemoteDesktop_OverrideVisualStyles; - RemoteDesktop_VisualStyles = profile.RemoteDesktop_VisualStyles; - - // PowerShell - PowerShell_Enabled = profile.PowerShell_Enabled; - PowerShell_EnableRemoteConsole = profile.PowerShell_EnableRemoteConsole; - PowerShell_InheritHost = profile.PowerShell_InheritHost; - PowerShell_Host = profile.PowerShell_Host; - PowerShell_OverrideCommand = profile.PowerShell_OverrideCommand; - PowerShell_Command = profile.PowerShell_Command; - PowerShell_OverrideAdditionalCommandLine = profile.PowerShell_OverrideAdditionalCommandLine; - PowerShell_AdditionalCommandLine = profile.PowerShell_AdditionalCommandLine; - PowerShell_OverrideExecutionPolicy = profile.PowerShell_OverrideExecutionPolicy; - PowerShell_ExecutionPolicy = profile.PowerShell_ExecutionPolicy; - - // PuTTY - PuTTY_Enabled = profile.PuTTY_Enabled; - PuTTY_ConnectionMode = profile.PuTTY_ConnectionMode; - PuTTY_InheritHost = profile.PuTTY_InheritHost; - PuTTY_HostOrSerialLine = profile.PuTTY_HostOrSerialLine; - PuTTY_OverridePortOrBaud = profile.PuTTY_OverridePortOrBaud; - PuTTY_PortOrBaud = profile.PuTTY_PortOrBaud; - PuTTY_OverrideUsername = profile.PuTTY_OverrideUsername; - PuTTY_Username = profile.PuTTY_Username; - PuTTY_OverridePrivateKeyFile = profile.PuTTY_OverridePrivateKeyFile; - PuTTY_PrivateKeyFile = profile.PuTTY_PrivateKeyFile; - PuTTY_OverrideProfile = profile.PuTTY_OverrideProfile; - PuTTY_Profile = profile.PuTTY_Profile; - PuTTY_OverrideHostkey = profile.PuTTY_OverrideHostkey; - PuTTY_Hostkey = profile.PuTTY_Hostkey; - PuTTY_OverrideEnableLog = profile.PuTTY_OverrideEnableLog; - PuTTY_EnableLog = profile.PuTTY_EnableLog; - PuTTY_OverrideLogMode = profile.PuTTY_OverrideLogMode; - PuTTY_LogMode = profile.PuTTY_LogMode; - PuTTY_OverrideLogPath = profile.PuTTY_OverrideLogPath; - PuTTY_LogPath = profile.PuTTY_LogPath; - PuTTY_OverrideLogFileName = profile.PuTTY_OverrideLogFileName; - PuTTY_LogFileName = profile.PuTTY_LogFileName; - PuTTY_OverrideAdditionalCommandLine = profile.PuTTY_OverrideAdditionalCommandLine; - PuTTY_AdditionalCommandLine = profile.PuTTY_AdditionalCommandLine; - - // AWS Session Manager - AWSSessionManager_Enabled = profile.AWSSessionManager_Enabled; - AWSSessionManager_InstanceID = profile.AWSSessionManager_InstanceID; - AWSSessionManager_OverrideProfile = profile.AWSSessionManager_OverrideProfile; - AWSSessionManager_Profile = profile.AWSSessionManager_Profile; - AWSSessionManager_OverrideRegion = profile.AWSSessionManager_OverrideRegion; - AWSSessionManager_Region = profile.AWSSessionManager_Region; - - // TigerVNC - TigerVNC_Enabled = profile.TigerVNC_Enabled; - TigerVNC_InheritHost = profile.TigerVNC_InheritHost; - TigerVNC_Host = profile.TigerVNC_Host; - TigerVNC_OverridePort = profile.TigerVNC_OverridePort; - TigerVNC_Port = profile.TigerVNC_Port; - - // WebConsole - WebConsole_Enabled = profile.WebConsole_Enabled; - WebConsole_Url = profile.WebConsole_Url; - - // Wake on LAN - WakeOnLAN_Enabled = profile.WakeOnLAN_Enabled; - WakeOnLAN_MACAddress = profile.WakeOnLAN_MACAddress; - WakeOnLAN_Broadcast = profile.WakeOnLAN_Broadcast; - WakeOnLAN_OverridePort = profile.WakeOnLAN_OverridePort; - WakeOnLAN_Port = profile.WakeOnLAN_Port; - - // Whois - Whois_Enabled = profile.Whois_Enabled; - Whois_InheritHost = profile.Whois_InheritHost; - Whois_Domain = profile.Whois_Domain; - } + Name = profile.Name; + Host = profile.Host; + Group = profile.Group; + Tags = profile.Tags; + + IsDynamic = profile.IsDynamic; + + // Network Interface + NetworkInterface_Enabled = profile.NetworkInterface_Enabled; + NetworkInterface_EnableStaticIPAddress = profile.NetworkInterface_EnableStaticIPAddress; + NetworkInterface_IPAddress = profile.NetworkInterface_IPAddress; + NetworkInterface_SubnetmaskOrCidr = profile.NetworkInterface_SubnetmaskOrCidr; + NetworkInterface_Gateway = profile.NetworkInterface_Gateway; + NetworkInterface_EnableStaticDNS = profile.NetworkInterface_EnableStaticDNS; + NetworkInterface_PrimaryDNSServer = profile.NetworkInterface_PrimaryDNSServer; + NetworkInterface_SecondaryDNSServer = profile.NetworkInterface_SecondaryDNSServer; + + // IP Scanner + IPScanner_Enabled = profile.IPScanner_Enabled; + IPScanner_InheritHost = profile.IPScanner_InheritHost; + IPScanner_HostOrIPRange = profile.IPScanner_HostOrIPRange; + + // Port Scanner + PortScanner_Enabled = profile.PortScanner_Enabled; + PortScanner_InheritHost = profile.PortScanner_InheritHost; + PortScanner_Host = profile.PortScanner_Host; + PortScanner_Ports = profile.PortScanner_Ports; + + // Ping Monitor + PingMonitor_Enabled = profile.PingMonitor_Enabled; + PingMonitor_InheritHost = profile.PingMonitor_InheritHost; + PingMonitor_Host = profile.PingMonitor_Host; + + // Traceroute + Traceroute_Enabled = profile.Traceroute_Enabled; + Traceroute_InheritHost = profile.Traceroute_InheritHost; + Traceroute_Host = profile.Traceroute_Host; + + // DNS Lookup + DNSLookup_Enabled = profile.DNSLookup_Enabled; + DNSLookup_InheritHost = profile.DNSLookup_InheritHost; + DNSLookup_Host = profile.DNSLookup_Host; + + // Remote Desktop + RemoteDesktop_Enabled = profile.RemoteDesktop_Enabled; + RemoteDesktop_InheritHost = profile.RemoteDesktop_InheritHost; + RemoteDesktop_Host = profile.RemoteDesktop_Host; + RemoteDesktop_UseCredentials = profile.RemoteDesktop_UseCredentials; + RemoteDesktop_Username = profile.RemoteDesktop_Username; + RemoteDesktop_Password = profile.RemoteDesktop_Password; + RemoteDesktop_OverrideDisplay = profile.RemoteDesktop_OverrideDisplay; + RemoteDesktop_AdjustScreenAutomatically = profile.RemoteDesktop_AdjustScreenAutomatically; + RemoteDesktop_UseCurrentViewSize = profile.RemoteDesktop_UseCurrentViewSize; + RemoteDesktop_UseFixedScreenSize = profile.RemoteDesktop_UseFixedScreenSize; + RemoteDesktop_ScreenWidth = profile.RemoteDesktop_ScreenWidth; + RemoteDesktop_ScreenHeight = profile.RemoteDesktop_ScreenHeight; + RemoteDesktop_UseCustomScreenSize = profile.RemoteDesktop_UseCustomScreenSize; + RemoteDesktop_CustomScreenWidth = profile.RemoteDesktop_CustomScreenWidth; + RemoteDesktop_CustomScreenHeight = profile.RemoteDesktop_CustomScreenHeight; + RemoteDesktop_OverrideColorDepth = profile.RemoteDesktop_OverrideColorDepth; + RemoteDesktop_ColorDepth = profile.RemoteDesktop_ColorDepth; + RemoteDesktop_OverridePort = profile.RemoteDesktop_OverridePort; + RemoteDesktop_Port = profile.RemoteDesktop_Port; + RemoteDesktop_OverrideCredSspSupport = profile.RemoteDesktop_OverrideCredSspSupport; + RemoteDesktop_EnableCredSspSupport = profile.RemoteDesktop_EnableCredSspSupport; + RemoteDesktop_OverrideAuthenticationLevel = profile.RemoteDesktop_OverrideAuthenticationLevel; + RemoteDesktop_AuthenticationLevel = profile.RemoteDesktop_AuthenticationLevel; + RemoteDesktop_OverrideAudioRedirectionMode = profile.RemoteDesktop_OverrideAudioRedirectionMode; + RemoteDesktop_AudioRedirectionMode = profile.RemoteDesktop_AudioRedirectionMode; + RemoteDesktop_OverrideAudioCaptureRedirectionMode = profile.RemoteDesktop_OverrideAudioCaptureRedirectionMode; + RemoteDesktop_AudioCaptureRedirectionMode = profile.RemoteDesktop_AudioCaptureRedirectionMode; + RemoteDesktop_OverrideApplyWindowsKeyCombinations = profile.RemoteDesktop_OverrideApplyWindowsKeyCombinations; + RemoteDesktop_KeyboardHookMode = profile.RemoteDesktop_KeyboardHookMode; + RemoteDesktop_OverrideRedirectClipboard = profile.RemoteDesktop_OverrideRedirectClipboard; + RemoteDesktop_RedirectClipboard = profile.RemoteDesktop_RedirectClipboard; + RemoteDesktop_OverrideRedirectDevices = profile.RemoteDesktop_OverrideRedirectDevices; + RemoteDesktop_RedirectDevices = profile.RemoteDesktop_RedirectDevices; + RemoteDesktop_OverrideRedirectDrives = profile.RemoteDesktop_OverrideRedirectDrives; + RemoteDesktop_RedirectDrives = profile.RemoteDesktop_RedirectDrives; + RemoteDesktop_OverrideRedirectPorts = profile.RemoteDesktop_OverrideRedirectPorts; + RemoteDesktop_RedirectPorts = profile.RemoteDesktop_RedirectPorts; + RemoteDesktop_OverrideRedirectSmartcards = profile.RemoteDesktop_OverrideRedirectSmartcards; + RemoteDesktop_RedirectSmartCards = profile.RemoteDesktop_RedirectSmartCards; + RemoteDesktop_OverrideRedirectPrinters = profile.RemoteDesktop_OverrideRedirectPrinters; + RemoteDesktop_RedirectPrinters = profile.RemoteDesktop_RedirectPrinters; + RemoteDesktop_OverridePersistentBitmapCaching = profile.RemoteDesktop_OverridePersistentBitmapCaching; + RemoteDesktop_PersistentBitmapCaching = profile.RemoteDesktop_PersistentBitmapCaching; + RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = profile.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + RemoteDesktop_ReconnectIfTheConnectionIsDropped = profile.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + RemoteDesktop_OverrideNetworkConnectionType = profile.RemoteDesktop_OverrideNetworkConnectionType; + RemoteDesktop_NetworkConnectionType = profile.RemoteDesktop_NetworkConnectionType; + RemoteDesktop_OverrideDesktopBackground = profile.RemoteDesktop_OverrideDesktopBackground; + RemoteDesktop_DesktopBackground = profile.RemoteDesktop_DesktopBackground; + RemoteDesktop_OverrideFontSmoothing = profile.RemoteDesktop_OverrideFontSmoothing; + RemoteDesktop_FontSmoothing = profile.RemoteDesktop_FontSmoothing; + RemoteDesktop_OverrideDesktopComposition = profile.RemoteDesktop_OverrideDesktopComposition; + RemoteDesktop_DesktopComposition = profile.RemoteDesktop_DesktopComposition; + RemoteDesktop_OverrideShowWindowContentsWhileDragging = profile.RemoteDesktop_OverrideShowWindowContentsWhileDragging; + RemoteDesktop_ShowWindowContentsWhileDragging = profile.RemoteDesktop_ShowWindowContentsWhileDragging; + RemoteDesktop_OverrideMenuAndWindowAnimation = profile.RemoteDesktop_OverrideMenuAndWindowAnimation; + RemoteDesktop_MenuAndWindowAnimation = profile.RemoteDesktop_MenuAndWindowAnimation; + RemoteDesktop_OverrideVisualStyles = profile.RemoteDesktop_OverrideVisualStyles; + RemoteDesktop_VisualStyles = profile.RemoteDesktop_VisualStyles; + + // PowerShell + PowerShell_Enabled = profile.PowerShell_Enabled; + PowerShell_EnableRemoteConsole = profile.PowerShell_EnableRemoteConsole; + PowerShell_InheritHost = profile.PowerShell_InheritHost; + PowerShell_Host = profile.PowerShell_Host; + PowerShell_OverrideCommand = profile.PowerShell_OverrideCommand; + PowerShell_Command = profile.PowerShell_Command; + PowerShell_OverrideAdditionalCommandLine = profile.PowerShell_OverrideAdditionalCommandLine; + PowerShell_AdditionalCommandLine = profile.PowerShell_AdditionalCommandLine; + PowerShell_OverrideExecutionPolicy = profile.PowerShell_OverrideExecutionPolicy; + PowerShell_ExecutionPolicy = profile.PowerShell_ExecutionPolicy; + + // PuTTY + PuTTY_Enabled = profile.PuTTY_Enabled; + PuTTY_ConnectionMode = profile.PuTTY_ConnectionMode; + PuTTY_InheritHost = profile.PuTTY_InheritHost; + PuTTY_HostOrSerialLine = profile.PuTTY_HostOrSerialLine; + PuTTY_OverridePortOrBaud = profile.PuTTY_OverridePortOrBaud; + PuTTY_PortOrBaud = profile.PuTTY_PortOrBaud; + PuTTY_OverrideUsername = profile.PuTTY_OverrideUsername; + PuTTY_Username = profile.PuTTY_Username; + PuTTY_OverridePrivateKeyFile = profile.PuTTY_OverridePrivateKeyFile; + PuTTY_PrivateKeyFile = profile.PuTTY_PrivateKeyFile; + PuTTY_OverrideProfile = profile.PuTTY_OverrideProfile; + PuTTY_Profile = profile.PuTTY_Profile; + PuTTY_OverrideHostkey = profile.PuTTY_OverrideHostkey; + PuTTY_Hostkey = profile.PuTTY_Hostkey; + PuTTY_OverrideEnableLog = profile.PuTTY_OverrideEnableLog; + PuTTY_EnableLog = profile.PuTTY_EnableLog; + PuTTY_OverrideLogMode = profile.PuTTY_OverrideLogMode; + PuTTY_LogMode = profile.PuTTY_LogMode; + PuTTY_OverrideLogPath = profile.PuTTY_OverrideLogPath; + PuTTY_LogPath = profile.PuTTY_LogPath; + PuTTY_OverrideLogFileName = profile.PuTTY_OverrideLogFileName; + PuTTY_LogFileName = profile.PuTTY_LogFileName; + PuTTY_OverrideAdditionalCommandLine = profile.PuTTY_OverrideAdditionalCommandLine; + PuTTY_AdditionalCommandLine = profile.PuTTY_AdditionalCommandLine; + + // AWS Session Manager + AWSSessionManager_Enabled = profile.AWSSessionManager_Enabled; + AWSSessionManager_InstanceID = profile.AWSSessionManager_InstanceID; + AWSSessionManager_OverrideProfile = profile.AWSSessionManager_OverrideProfile; + AWSSessionManager_Profile = profile.AWSSessionManager_Profile; + AWSSessionManager_OverrideRegion = profile.AWSSessionManager_OverrideRegion; + AWSSessionManager_Region = profile.AWSSessionManager_Region; + + // TigerVNC + TigerVNC_Enabled = profile.TigerVNC_Enabled; + TigerVNC_InheritHost = profile.TigerVNC_InheritHost; + TigerVNC_Host = profile.TigerVNC_Host; + TigerVNC_OverridePort = profile.TigerVNC_OverridePort; + TigerVNC_Port = profile.TigerVNC_Port; + + // WebConsole + WebConsole_Enabled = profile.WebConsole_Enabled; + WebConsole_Url = profile.WebConsole_Url; + + // Wake on LAN + WakeOnLAN_Enabled = profile.WakeOnLAN_Enabled; + WakeOnLAN_MACAddress = profile.WakeOnLAN_MACAddress; + WakeOnLAN_Broadcast = profile.WakeOnLAN_Broadcast; + WakeOnLAN_OverridePort = profile.WakeOnLAN_OverridePort; + WakeOnLAN_Port = profile.WakeOnLAN_Port; + + // Whois + Whois_Enabled = profile.Whois_Enabled; + Whois_InheritHost = profile.Whois_InheritHost; + Whois_Domain = profile.Whois_Domain; } } diff --git a/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs b/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs index 7fad985ff3..9f94581563 100644 --- a/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs +++ b/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs @@ -1,20 +1,19 @@ -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public class ProfileInfoSerializable : ProfileInfo { - public class ProfileInfoSerializable : ProfileInfo - { - /// - /// Override the default remote desktop password to make it serializable. - /// - public new string RemoteDesktop_Password { get; set; } + /// + /// Override the default remote desktop password to make it serializable. + /// + public new string RemoteDesktop_Password { get; set; } - public ProfileInfoSerializable() - { + public ProfileInfoSerializable() + { - } - - public ProfileInfoSerializable(ProfileInfo profile) : base(profile) - { + } - } + public ProfileInfoSerializable(ProfileInfo profile) : base(profile) + { + } } diff --git a/Source/NETworkManager.Profiles/ProfileViewInfo.cs b/Source/NETworkManager.Profiles/ProfileViewInfo.cs index 186d258675..bae8cd3948 100644 --- a/Source/NETworkManager.Profiles/ProfileViewInfo.cs +++ b/Source/NETworkManager.Profiles/ProfileViewInfo.cs @@ -1,30 +1,29 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public class ProfileViewInfo { - public class ProfileViewInfo - { - public ProfileViewName Name { get; set; } + public ProfileViewName Name { get; set; } - public Canvas Icon { get; set; } + public Canvas Icon { get; set; } - public ProfileViewInfo() - { - } + public ProfileViewInfo() + { + } - public ProfileViewInfo(ProfileViewName name, Canvas icon) - { - Name = name; - Icon = icon; - } + public ProfileViewInfo(ProfileViewName name, Canvas icon) + { + Name = name; + Icon = icon; + } - public ProfileViewInfo(ProfileViewName name, UIElement uiElement) - { - Name = name; - var canvas = new Canvas(); - canvas.Children.Add(uiElement); - Icon = canvas; - } + public ProfileViewInfo(ProfileViewName name, UIElement uiElement) + { + Name = name; + var canvas = new Canvas(); + canvas.Children.Add(uiElement); + Icon = canvas; } } diff --git a/Source/NETworkManager.Profiles/ProfileViewName.cs b/Source/NETworkManager.Profiles/ProfileViewName.cs index bf515e3609..9084983493 100644 --- a/Source/NETworkManager.Profiles/ProfileViewName.cs +++ b/Source/NETworkManager.Profiles/ProfileViewName.cs @@ -1,21 +1,20 @@ -namespace NETworkManager.Profiles +namespace NETworkManager.Profiles; + +public enum ProfileViewName { - public enum ProfileViewName - { - General, - NetworkInterface, - IPScanner, - PortScanner, - PingMonitor, - Traceroute, - DNSLookup, - RemoteDesktop, - PowerShell, - PuTTY, - AWSSessionManager, - TigerVNC, - WebConsole, - WakeOnLAN, - Whois - } + General, + NetworkInterface, + IPScanner, + PortScanner, + PingMonitor, + Traceroute, + DNSLookup, + RemoteDesktop, + PowerShell, + PuTTY, + AWSSessionManager, + TigerVNC, + WebConsole, + WakeOnLAN, + Whois } From 69405844409b2dd9314d4b198e2afe5f0d85a69d Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:28:46 +0100 Subject: [PATCH 06/11] Chore: Use .NET 7 syntax --- .../NETworkManager.Documentation/BaseInfo.cs | 55 ++- .../DocumentationIdentifier.cs | 403 +++++++++--------- .../DocumentationInfo.cs | 45 +- .../DocumentationManager.cs | 321 +++++++------- .../ExternalServicesInfo.cs | 25 +- .../ExternalServicesManager.cs | 21 +- .../LibraryInfo.cs | 49 ++- .../LibraryManager.cs | 85 ++-- .../ResourceInfo.cs | 25 +- .../ResourceManager.cs | 27 +- .../ILocalizationStringTranslator.cs | 21 +- .../LocalizationInfo.cs | 109 +++-- .../LocalizationManager.cs | 219 +++++----- .../Translators/AccentTranslator.cs | 39 +- .../Translators/ApplicationNameTranslator.cs | 53 ++- .../Translators/ConnectionStateTranslator.cs | 55 ++- .../DiscoveryProtocolTranslator.cs | 53 ++- .../Translators/GroupViewNameTranslator.cs | 55 ++- .../Translators/IPStatusTranslator.cs | 53 ++- .../Translators/PortStateTranslator.cs | 53 ++- .../Translators/ProfileViewNameTranslator.cs | 57 ++- .../Translators/PuTTYLogModeTranslator.cs | 53 ++- ...opAudioCaptureRedirectionModeTranslator.cs | 53 ++- ...teDesktopAudioRedirectionModeTranslator.cs | 53 ++- ...RemoteDesktopKeyboardHookModeTranslator.cs | 53 ++- ...eDesktopNetworkConnectionTypeTranslator.cs | 53 ++- .../SettingsViewGroupTranslator.cs | 53 ++- .../Translators/SettingsViewNameTranslator.cs | 57 ++- .../Translators/TcpStateTranslator.cs | 53 ++- .../Translators/ThemeTranslator.cs | 35 +- .../Translators/TimeUnitTranslator.cs | 53 ++- 31 files changed, 1154 insertions(+), 1185 deletions(-) diff --git a/Source/NETworkManager.Documentation/BaseInfo.cs b/Source/NETworkManager.Documentation/BaseInfo.cs index 18170162e8..117d3d6614 100644 --- a/Source/NETworkManager.Documentation/BaseInfo.cs +++ b/Source/NETworkManager.Documentation/BaseInfo.cs @@ -1,36 +1,35 @@ -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// Base class to hold informations about a library, service or resource. +/// +public abstract class BaseInfo { /// - /// Base class to hold informations about a library, service or resource. + /// Name of the library, service or resource. /// - public abstract class BaseInfo - { - /// - /// Name of the library, service or resource. - /// - public string Name { get; set; } + public string Name { get; set; } - /// - /// Url of the library, service or resource. - /// - public string WebsiteUrl { get; set; } + /// + /// Url of the library, service or resource. + /// + public string WebsiteUrl { get; set; } - /// - /// Description of the library, service or resource. - /// - public string Description { get; set; } + /// + /// Description of the library, service or resource. + /// + public string Description { get; set; } - /// - /// Create an instance of with parameters. - /// - /// Name of the library, service or resource. - /// Url of the library, service or resource. - /// Description of the library, service or resource. - protected BaseInfo(string name, string websiteUrl, string description) - { - Name = name; - WebsiteUrl = websiteUrl; - Description = description; - } + /// + /// Create an instance of with parameters. + /// + /// Name of the library, service or resource. + /// Url of the library, service or resource. + /// Description of the library, service or resource. + protected BaseInfo(string name, string websiteUrl, string description) + { + Name = name; + WebsiteUrl = websiteUrl; + Description = description; } } diff --git a/Source/NETworkManager.Documentation/DocumentationIdentifier.cs b/Source/NETworkManager.Documentation/DocumentationIdentifier.cs index 01467dc847..a6779cfa97 100644 --- a/Source/NETworkManager.Documentation/DocumentationIdentifier.cs +++ b/Source/NETworkManager.Documentation/DocumentationIdentifier.cs @@ -1,203 +1,202 @@ -namespace NETworkManager.Documentation -{ - /// - /// Enum to identify documentation page entries. - /// - public enum DocumentationIdentifier - { - /// - /// Default documentation page. - /// - Default, - - /// - /// Dashboard documentation page. - /// - ApplicationDashboard, - - /// - /// Network interface documentation page. - /// - ApplicationNetworkInterface, - - /// - /// WiFi documentation page. - /// - ApplicationWiFi, - - /// - /// IP scanner documentation page. - /// - ApplicationIPScanner, - - /// - /// Port scanner documentation page. - /// - ApplicationPortScanner, - - /// - /// Ping monitor documentation page. - /// - ApplicationPingMonitor, - - /// - /// Traceroute documentation page. - /// - ApplicationTraceroute, - - /// - /// DNS lookup documentation page. - /// - ApplicationDnsLookup, - - /// - /// Remote desktop documentation page. - /// - ApplicationRemoteDesktop, - - /// - /// PowerShell documentation page. - /// - ApplicationPowerShell, - - /// - /// PuTTY documentation page. - /// - ApplicationPutty, - - /// - /// AWS Session Manager documentation page. - /// - ApplicationAWSSessionManager, - - /// - /// TigerVNC documentation page. - /// - ApplicationTigerVNC, - - /// - /// Web Console documentation page. - /// - ApplicationWebConsole, - - /// - /// SNMP documentation page. - /// - ApplicationSnmp, - - /// - /// SNTP lookup documentation page. - /// - ApplicationSntpLookup, - - /// - /// Discovery Protocol documentation page. - /// - ApplicationDiscoveryProtocol, - - /// - /// Wake on LAN documentation page. - /// - ApplicationWakeOnLan, - - /// - /// Whois documentation page. - /// - ApplicationWhois, - - /// - /// Subnet Calculator documentation page. - /// - ApplicationSubnetCalculator, - - /// - /// Bit Calculator documentation page. - /// - ApplicationBitCalculator, - - /// - /// Lookup documentation page. - /// - ApplicationLookup, - - /// - /// Connections documentation page. - /// - ApplicationConnections, - - /// - /// Listeners documentation page. - /// - ApplicationListeners, - - /// - /// ARP Table documentation page. - /// - ApplicationArpTable, - - /// - /// Settings\General documentation page. - /// - SettingsGeneral, - - /// - /// Settings\Window documentation page. - /// - SettingsWindow, - - /// - /// Settings\Appearance documentation page. - /// - SettingsAppearance, - - /// - /// Settings\Language documentation page. - /// - SettingsLanguage, - - /// - /// Settings\Network documentation page. - /// - SettingsNetwork, - - /// - /// Settings\Status documentation page. - /// - SettingsStatus, - - /// - /// Settings\HotKeys documentation page. - /// - SettingsHotKeys, - - /// - /// Settings\Autostart documentation page. - /// - SettingsAutostart, - - /// - /// Settings\Update documentation page. - /// - SettingsUpdate, - - /// - /// Settings\Profiles documentation page. - /// - SettingsProfiles, - - /// - /// Settings\Settings documentation page. - /// - SettingsSettings, - - /// - /// Profiles documentation page. - /// - Profiles, - - /// - /// Command line arguments. - /// - CommandLineArguments - } +namespace NETworkManager.Documentation; + +/// +/// Enum to identify documentation page entries. +/// +public enum DocumentationIdentifier +{ + /// + /// Default documentation page. + /// + Default, + + /// + /// Dashboard documentation page. + /// + ApplicationDashboard, + + /// + /// Network interface documentation page. + /// + ApplicationNetworkInterface, + + /// + /// WiFi documentation page. + /// + ApplicationWiFi, + + /// + /// IP scanner documentation page. + /// + ApplicationIPScanner, + + /// + /// Port scanner documentation page. + /// + ApplicationPortScanner, + + /// + /// Ping monitor documentation page. + /// + ApplicationPingMonitor, + + /// + /// Traceroute documentation page. + /// + ApplicationTraceroute, + + /// + /// DNS lookup documentation page. + /// + ApplicationDnsLookup, + + /// + /// Remote desktop documentation page. + /// + ApplicationRemoteDesktop, + + /// + /// PowerShell documentation page. + /// + ApplicationPowerShell, + + /// + /// PuTTY documentation page. + /// + ApplicationPutty, + + /// + /// AWS Session Manager documentation page. + /// + ApplicationAWSSessionManager, + + /// + /// TigerVNC documentation page. + /// + ApplicationTigerVNC, + + /// + /// Web Console documentation page. + /// + ApplicationWebConsole, + + /// + /// SNMP documentation page. + /// + ApplicationSnmp, + + /// + /// SNTP lookup documentation page. + /// + ApplicationSntpLookup, + + /// + /// Discovery Protocol documentation page. + /// + ApplicationDiscoveryProtocol, + + /// + /// Wake on LAN documentation page. + /// + ApplicationWakeOnLan, + + /// + /// Whois documentation page. + /// + ApplicationWhois, + + /// + /// Subnet Calculator documentation page. + /// + ApplicationSubnetCalculator, + + /// + /// Bit Calculator documentation page. + /// + ApplicationBitCalculator, + + /// + /// Lookup documentation page. + /// + ApplicationLookup, + + /// + /// Connections documentation page. + /// + ApplicationConnections, + + /// + /// Listeners documentation page. + /// + ApplicationListeners, + + /// + /// ARP Table documentation page. + /// + ApplicationArpTable, + + /// + /// Settings\General documentation page. + /// + SettingsGeneral, + + /// + /// Settings\Window documentation page. + /// + SettingsWindow, + + /// + /// Settings\Appearance documentation page. + /// + SettingsAppearance, + + /// + /// Settings\Language documentation page. + /// + SettingsLanguage, + + /// + /// Settings\Network documentation page. + /// + SettingsNetwork, + + /// + /// Settings\Status documentation page. + /// + SettingsStatus, + + /// + /// Settings\HotKeys documentation page. + /// + SettingsHotKeys, + + /// + /// Settings\Autostart documentation page. + /// + SettingsAutostart, + + /// + /// Settings\Update documentation page. + /// + SettingsUpdate, + + /// + /// Settings\Profiles documentation page. + /// + SettingsProfiles, + + /// + /// Settings\Settings documentation page. + /// + SettingsSettings, + + /// + /// Profiles documentation page. + /// + Profiles, + + /// + /// Command line arguments. + /// + CommandLineArguments } diff --git a/Source/NETworkManager.Documentation/DocumentationInfo.cs b/Source/NETworkManager.Documentation/DocumentationInfo.cs index 2104e94fa4..06f2f29e42 100644 --- a/Source/NETworkManager.Documentation/DocumentationInfo.cs +++ b/Source/NETworkManager.Documentation/DocumentationInfo.cs @@ -1,29 +1,28 @@ -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// Class to hold all informations about a localization. +/// +public class DocumentationInfo { /// - /// Class to hold all informations about a localization. + /// Identifier for identifying a documentation entry. /// - public class DocumentationInfo - { - /// - /// Identifier for identifying a documentation entry. - /// - public DocumentationIdentifier Identifier { get; set; } - - /// - /// Path to the documentation, which is combined with the base path of the documentation. - /// - public string Path { get; set; } + public DocumentationIdentifier Identifier { get; set; } + + /// + /// Path to the documentation, which is combined with the base path of the documentation. + /// + public string Path { get; set; } - /// - /// Create an instance of with all parameters. - /// - /// of the documentation entry. - /// to the documentation page. - public DocumentationInfo(DocumentationIdentifier identifier, string path) - { - Identifier = identifier; - Path = path; - } + /// + /// Create an instance of with all parameters. + /// + /// of the documentation entry. + /// to the documentation page. + public DocumentationInfo(DocumentationIdentifier identifier, string path) + { + Identifier = identifier; + Path = path; } } diff --git a/Source/NETworkManager.Documentation/DocumentationManager.cs b/Source/NETworkManager.Documentation/DocumentationManager.cs index b3a166654b..49ed4743b6 100644 --- a/Source/NETworkManager.Documentation/DocumentationManager.cs +++ b/Source/NETworkManager.Documentation/DocumentationManager.cs @@ -5,181 +5,180 @@ using System.Linq; using System.Windows.Input; -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// This class is designed to interact with the documentation at https://borntoberoot.net/NETworkManager/. +/// +public static class DocumentationManager { /// - /// This class is designed to interact with the documentation at https://borntoberoot.net/NETworkManager/. + /// Base path of the documentation. /// - public static class DocumentationManager - { - /// - /// Base path of the documentation. - /// - public const string DocumentationBaseUrl = @"https://borntoberoot.net/NETworkManager/"; + public const string DocumentationBaseUrl = @"https://borntoberoot.net/NETworkManager/"; - /// - /// List with all known documentation entries. - /// - private static List List => new() - { - new DocumentationInfo(DocumentationIdentifier.ApplicationDashboard, @"Documentation/Application/Dashboard"), - new DocumentationInfo(DocumentationIdentifier.ApplicationNetworkInterface, @"Documentation/Application/NetworkInterface"), - new DocumentationInfo(DocumentationIdentifier.ApplicationWiFi, @"Documentation/Application/WiFi"), - new DocumentationInfo(DocumentationIdentifier.ApplicationIPScanner, @"Documentation/Application/IPScanner"), - new DocumentationInfo(DocumentationIdentifier.ApplicationPortScanner, @"Documentation/Application/PortScanner"), - new DocumentationInfo(DocumentationIdentifier.ApplicationPingMonitor, @"Documentation/Application/PingMonitor"), - new DocumentationInfo(DocumentationIdentifier.ApplicationTraceroute, @"Documentation/Application/Traceroute"), - new DocumentationInfo(DocumentationIdentifier.ApplicationDnsLookup, @"Documentation/Application/DNSLookup"), - new DocumentationInfo(DocumentationIdentifier.ApplicationRemoteDesktop, @"Documentation/Application/RemoteDesktop"), - new DocumentationInfo(DocumentationIdentifier.ApplicationPowerShell, @"Documentation/Application/PowerShell"), - new DocumentationInfo(DocumentationIdentifier.ApplicationPutty, @"Documentation/Application/PuTTY"), - new DocumentationInfo(DocumentationIdentifier.ApplicationAWSSessionManager, @"Documentation/Application/AWSSessionManager"), - new DocumentationInfo(DocumentationIdentifier.ApplicationTigerVNC, @"Documentation/Application/TigerVNC"), - new DocumentationInfo(DocumentationIdentifier.ApplicationWebConsole, @"Documentation/Application/WebConsole"), - new DocumentationInfo(DocumentationIdentifier.ApplicationSnmp, @"Documentation/Application/SNMP"), - new DocumentationInfo(DocumentationIdentifier.ApplicationSntpLookup, @"Documentation/Application/SNTPLookup"), - new DocumentationInfo(DocumentationIdentifier.ApplicationDiscoveryProtocol, @"Documentation/Application/DiscoveryProtocol"), - new DocumentationInfo(DocumentationIdentifier.ApplicationWakeOnLan, @"Documentation/Application/WakeOnLAN"), - new DocumentationInfo(DocumentationIdentifier.ApplicationWhois, @"Documentation/Application/Whois"), - new DocumentationInfo(DocumentationIdentifier.ApplicationSubnetCalculator, @"Documentation/Application/SubnetCalculator"), - new DocumentationInfo(DocumentationIdentifier.ApplicationBitCalculator, @"Documentation/Application/BitCalculator"), - new DocumentationInfo(DocumentationIdentifier.ApplicationLookup, @"Documentation/Application/Lookup"), - new DocumentationInfo(DocumentationIdentifier.ApplicationConnections, @"Documentation/Application/Connection"), - new DocumentationInfo(DocumentationIdentifier.ApplicationListeners, @"Documentation/Application/Listeners"), - new DocumentationInfo(DocumentationIdentifier.ApplicationArpTable, @"Documentation/Application/ARPTable"), - new DocumentationInfo(DocumentationIdentifier.SettingsGeneral, @"Documentation/Settings/General"), - new DocumentationInfo(DocumentationIdentifier.SettingsWindow, @"Documentation/Settings/Window"), - new DocumentationInfo(DocumentationIdentifier.SettingsAppearance, @"Documentation/Settings/Appearance"), - new DocumentationInfo(DocumentationIdentifier.SettingsLanguage, @"Documentation/Settings/Language"), - new DocumentationInfo(DocumentationIdentifier.SettingsNetwork, @"Documentation/Settings/Network"), - new DocumentationInfo(DocumentationIdentifier.SettingsStatus, @"Documentation/Settings/Status"), - new DocumentationInfo(DocumentationIdentifier.SettingsHotKeys, @"Documentation/Settings/HotKeys"), - new DocumentationInfo(DocumentationIdentifier.SettingsAutostart, @"Documentation/Settings/Autostart"), - new DocumentationInfo(DocumentationIdentifier.SettingsUpdate, @"Documentation/Settings/Update"), - new DocumentationInfo(DocumentationIdentifier.SettingsProfiles, @"Documentation/Settings/Profiles"), - new DocumentationInfo(DocumentationIdentifier.SettingsSettings, @"Documentation/Settings/Settings"), - new DocumentationInfo(DocumentationIdentifier.Profiles, @"Documentation/Profiles"), - new DocumentationInfo(DocumentationIdentifier.CommandLineArguments, @"Documentation/CommandLineArguments"), - }; + /// + /// List with all known documentation entries. + /// + private static List List => new() + { + new DocumentationInfo(DocumentationIdentifier.ApplicationDashboard, @"Documentation/Application/Dashboard"), + new DocumentationInfo(DocumentationIdentifier.ApplicationNetworkInterface, @"Documentation/Application/NetworkInterface"), + new DocumentationInfo(DocumentationIdentifier.ApplicationWiFi, @"Documentation/Application/WiFi"), + new DocumentationInfo(DocumentationIdentifier.ApplicationIPScanner, @"Documentation/Application/IPScanner"), + new DocumentationInfo(DocumentationIdentifier.ApplicationPortScanner, @"Documentation/Application/PortScanner"), + new DocumentationInfo(DocumentationIdentifier.ApplicationPingMonitor, @"Documentation/Application/PingMonitor"), + new DocumentationInfo(DocumentationIdentifier.ApplicationTraceroute, @"Documentation/Application/Traceroute"), + new DocumentationInfo(DocumentationIdentifier.ApplicationDnsLookup, @"Documentation/Application/DNSLookup"), + new DocumentationInfo(DocumentationIdentifier.ApplicationRemoteDesktop, @"Documentation/Application/RemoteDesktop"), + new DocumentationInfo(DocumentationIdentifier.ApplicationPowerShell, @"Documentation/Application/PowerShell"), + new DocumentationInfo(DocumentationIdentifier.ApplicationPutty, @"Documentation/Application/PuTTY"), + new DocumentationInfo(DocumentationIdentifier.ApplicationAWSSessionManager, @"Documentation/Application/AWSSessionManager"), + new DocumentationInfo(DocumentationIdentifier.ApplicationTigerVNC, @"Documentation/Application/TigerVNC"), + new DocumentationInfo(DocumentationIdentifier.ApplicationWebConsole, @"Documentation/Application/WebConsole"), + new DocumentationInfo(DocumentationIdentifier.ApplicationSnmp, @"Documentation/Application/SNMP"), + new DocumentationInfo(DocumentationIdentifier.ApplicationSntpLookup, @"Documentation/Application/SNTPLookup"), + new DocumentationInfo(DocumentationIdentifier.ApplicationDiscoveryProtocol, @"Documentation/Application/DiscoveryProtocol"), + new DocumentationInfo(DocumentationIdentifier.ApplicationWakeOnLan, @"Documentation/Application/WakeOnLAN"), + new DocumentationInfo(DocumentationIdentifier.ApplicationWhois, @"Documentation/Application/Whois"), + new DocumentationInfo(DocumentationIdentifier.ApplicationSubnetCalculator, @"Documentation/Application/SubnetCalculator"), + new DocumentationInfo(DocumentationIdentifier.ApplicationBitCalculator, @"Documentation/Application/BitCalculator"), + new DocumentationInfo(DocumentationIdentifier.ApplicationLookup, @"Documentation/Application/Lookup"), + new DocumentationInfo(DocumentationIdentifier.ApplicationConnections, @"Documentation/Application/Connection"), + new DocumentationInfo(DocumentationIdentifier.ApplicationListeners, @"Documentation/Application/Listeners"), + new DocumentationInfo(DocumentationIdentifier.ApplicationArpTable, @"Documentation/Application/ARPTable"), + new DocumentationInfo(DocumentationIdentifier.SettingsGeneral, @"Documentation/Settings/General"), + new DocumentationInfo(DocumentationIdentifier.SettingsWindow, @"Documentation/Settings/Window"), + new DocumentationInfo(DocumentationIdentifier.SettingsAppearance, @"Documentation/Settings/Appearance"), + new DocumentationInfo(DocumentationIdentifier.SettingsLanguage, @"Documentation/Settings/Language"), + new DocumentationInfo(DocumentationIdentifier.SettingsNetwork, @"Documentation/Settings/Network"), + new DocumentationInfo(DocumentationIdentifier.SettingsStatus, @"Documentation/Settings/Status"), + new DocumentationInfo(DocumentationIdentifier.SettingsHotKeys, @"Documentation/Settings/HotKeys"), + new DocumentationInfo(DocumentationIdentifier.SettingsAutostart, @"Documentation/Settings/Autostart"), + new DocumentationInfo(DocumentationIdentifier.SettingsUpdate, @"Documentation/Settings/Update"), + new DocumentationInfo(DocumentationIdentifier.SettingsProfiles, @"Documentation/Settings/Profiles"), + new DocumentationInfo(DocumentationIdentifier.SettingsSettings, @"Documentation/Settings/Settings"), + new DocumentationInfo(DocumentationIdentifier.Profiles, @"Documentation/Profiles"), + new DocumentationInfo(DocumentationIdentifier.CommandLineArguments, @"Documentation/CommandLineArguments"), + }; - /// - /// Method to create the documentation url from . - /// - /// of the documentation page you want to open. - /// URL of the documentation page. - private static string CreateUrl(DocumentationIdentifier documentationIdentifier) - { - var info = List.FirstOrDefault(x => x.Identifier == documentationIdentifier); + /// + /// Method to create the documentation url from . + /// + /// of the documentation page you want to open. + /// URL of the documentation page. + private static string CreateUrl(DocumentationIdentifier documentationIdentifier) + { + var info = List.FirstOrDefault(x => x.Identifier == documentationIdentifier); - var url = DocumentationBaseUrl; + var url = DocumentationBaseUrl; - if (info != null) - url += info.Path; + if (info != null) + url += info.Path; - return url; - } + return url; + } - /// - /// Method for opening a documentation page with the default webbrowser based on the . - /// - /// of the documentation page you want to open. - public static void OpenDocumentation(DocumentationIdentifier documentationIdentifier) - { - ExternalProcessStarter.OpenUrl(CreateUrl(documentationIdentifier)); - } + /// + /// Method for opening a documentation page with the default webbrowser based on the . + /// + /// of the documentation page you want to open. + public static void OpenDocumentation(DocumentationIdentifier documentationIdentifier) + { + ExternalProcessStarter.OpenUrl(CreateUrl(documentationIdentifier)); + } - /// - /// Command to open a documentation page based on . - /// - public static ICommand OpenDocumentationCommand => new RelayCommand(OpenDocumentationAction); + /// + /// Command to open a documentation page based on . + /// + public static ICommand OpenDocumentationCommand => new RelayCommand(OpenDocumentationAction); - /// - /// Method to open a documentation page based on . - /// - /// - private static void OpenDocumentationAction(object documentationIdentifier) - { - if (documentationIdentifier != null) - OpenDocumentation((DocumentationIdentifier)documentationIdentifier); - } + /// + /// Method to open a documentation page based on . + /// + /// + private static void OpenDocumentationAction(object documentationIdentifier) + { + if (documentationIdentifier != null) + OpenDocumentation((DocumentationIdentifier)documentationIdentifier); + } - /// - /// Method to get the from an . - /// - /// from which you want to get the . - /// of the application. - public static DocumentationIdentifier GetIdentifierByAppliactionName(ApplicationName name) + /// + /// Method to get the from an . + /// + /// from which you want to get the . + /// of the application. + public static DocumentationIdentifier GetIdentifierByAppliactionName(ApplicationName name) + { + return name switch { - return name switch - { - ApplicationName.Dashboard => DocumentationIdentifier.ApplicationDashboard, - ApplicationName.NetworkInterface => DocumentationIdentifier.ApplicationNetworkInterface, - ApplicationName.WiFi => DocumentationIdentifier.ApplicationWiFi, - ApplicationName.IPScanner => DocumentationIdentifier.ApplicationIPScanner, - ApplicationName.PortScanner => DocumentationIdentifier.ApplicationPortScanner, - ApplicationName.PingMonitor => DocumentationIdentifier.ApplicationPingMonitor, - ApplicationName.Traceroute => DocumentationIdentifier.ApplicationTraceroute, - ApplicationName.DNSLookup => DocumentationIdentifier.ApplicationDnsLookup, - ApplicationName.RemoteDesktop => DocumentationIdentifier.ApplicationRemoteDesktop, - ApplicationName.PowerShell => DocumentationIdentifier.ApplicationPowerShell, - ApplicationName.PuTTY => DocumentationIdentifier.ApplicationPutty, - ApplicationName.AWSSessionManager => DocumentationIdentifier.ApplicationAWSSessionManager, - ApplicationName.TigerVNC => DocumentationIdentifier.ApplicationTigerVNC, - ApplicationName.WebConsole => DocumentationIdentifier.ApplicationWebConsole, - ApplicationName.SNMP => DocumentationIdentifier.ApplicationSnmp, - ApplicationName.SNTPLookup => DocumentationIdentifier.ApplicationSntpLookup, - ApplicationName.DiscoveryProtocol => DocumentationIdentifier.ApplicationDiscoveryProtocol, - ApplicationName.WakeOnLAN => DocumentationIdentifier.ApplicationWakeOnLan, - ApplicationName.Whois => DocumentationIdentifier.ApplicationWhois, - ApplicationName.SubnetCalculator => DocumentationIdentifier.ApplicationSubnetCalculator, - ApplicationName.BitCalculator => DocumentationIdentifier.ApplicationBitCalculator, - ApplicationName.Lookup => DocumentationIdentifier.ApplicationLookup, - ApplicationName.Connections => DocumentationIdentifier.ApplicationConnections, - ApplicationName.Listeners => DocumentationIdentifier.ApplicationListeners, - ApplicationName.ARPTable => DocumentationIdentifier.ApplicationArpTable, - ApplicationName.None => DocumentationIdentifier.Default, - _ => DocumentationIdentifier.Default, - }; - } + ApplicationName.Dashboard => DocumentationIdentifier.ApplicationDashboard, + ApplicationName.NetworkInterface => DocumentationIdentifier.ApplicationNetworkInterface, + ApplicationName.WiFi => DocumentationIdentifier.ApplicationWiFi, + ApplicationName.IPScanner => DocumentationIdentifier.ApplicationIPScanner, + ApplicationName.PortScanner => DocumentationIdentifier.ApplicationPortScanner, + ApplicationName.PingMonitor => DocumentationIdentifier.ApplicationPingMonitor, + ApplicationName.Traceroute => DocumentationIdentifier.ApplicationTraceroute, + ApplicationName.DNSLookup => DocumentationIdentifier.ApplicationDnsLookup, + ApplicationName.RemoteDesktop => DocumentationIdentifier.ApplicationRemoteDesktop, + ApplicationName.PowerShell => DocumentationIdentifier.ApplicationPowerShell, + ApplicationName.PuTTY => DocumentationIdentifier.ApplicationPutty, + ApplicationName.AWSSessionManager => DocumentationIdentifier.ApplicationAWSSessionManager, + ApplicationName.TigerVNC => DocumentationIdentifier.ApplicationTigerVNC, + ApplicationName.WebConsole => DocumentationIdentifier.ApplicationWebConsole, + ApplicationName.SNMP => DocumentationIdentifier.ApplicationSnmp, + ApplicationName.SNTPLookup => DocumentationIdentifier.ApplicationSntpLookup, + ApplicationName.DiscoveryProtocol => DocumentationIdentifier.ApplicationDiscoveryProtocol, + ApplicationName.WakeOnLAN => DocumentationIdentifier.ApplicationWakeOnLan, + ApplicationName.Whois => DocumentationIdentifier.ApplicationWhois, + ApplicationName.SubnetCalculator => DocumentationIdentifier.ApplicationSubnetCalculator, + ApplicationName.BitCalculator => DocumentationIdentifier.ApplicationBitCalculator, + ApplicationName.Lookup => DocumentationIdentifier.ApplicationLookup, + ApplicationName.Connections => DocumentationIdentifier.ApplicationConnections, + ApplicationName.Listeners => DocumentationIdentifier.ApplicationListeners, + ApplicationName.ARPTable => DocumentationIdentifier.ApplicationArpTable, + ApplicationName.None => DocumentationIdentifier.Default, + _ => DocumentationIdentifier.Default, + }; + } - /// - /// Method to get the from an . - /// - /// from which you want to get the . - /// of the application or settings page. - public static DocumentationIdentifier GetIdentifierBySettingsName(SettingsViewName name) + /// + /// Method to get the from an . + /// + /// from which you want to get the . + /// of the application or settings page. + public static DocumentationIdentifier GetIdentifierBySettingsName(SettingsViewName name) + { + return name switch { - return name switch - { - SettingsViewName.General => DocumentationIdentifier.SettingsGeneral, - SettingsViewName.Window => DocumentationIdentifier.SettingsWindow, - SettingsViewName.Appearance => DocumentationIdentifier.SettingsAppearance, - SettingsViewName.Language => DocumentationIdentifier.SettingsLanguage, - SettingsViewName.Network => DocumentationIdentifier.SettingsNetwork, - SettingsViewName.Status => DocumentationIdentifier.SettingsStatus, - SettingsViewName.HotKeys => DocumentationIdentifier.SettingsHotKeys, - SettingsViewName.Autostart => DocumentationIdentifier.SettingsAutostart, - SettingsViewName.Update => DocumentationIdentifier.SettingsUpdate, - SettingsViewName.Profiles => DocumentationIdentifier.SettingsProfiles, - SettingsViewName.Settings => DocumentationIdentifier.SettingsSettings, - SettingsViewName.Dashboard => GetIdentifierByAppliactionName(ApplicationName.Dashboard), - SettingsViewName.IPScanner => GetIdentifierByAppliactionName(ApplicationName.IPScanner), - SettingsViewName.PortScanner => GetIdentifierByAppliactionName(ApplicationName.PortScanner), - SettingsViewName.PingMonitor => GetIdentifierByAppliactionName(ApplicationName.PingMonitor), - SettingsViewName.Traceroute => GetIdentifierByAppliactionName(ApplicationName.Traceroute), - SettingsViewName.DNSLookup => GetIdentifierByAppliactionName(ApplicationName.DNSLookup), - SettingsViewName.RemoteDesktop => GetIdentifierByAppliactionName(ApplicationName.RemoteDesktop), - SettingsViewName.PowerShell => GetIdentifierByAppliactionName(ApplicationName.PowerShell), - SettingsViewName.PuTTY => GetIdentifierByAppliactionName(ApplicationName.PuTTY), - SettingsViewName.AWSSessionManager => GetIdentifierByAppliactionName(ApplicationName.AWSSessionManager), - SettingsViewName.TigerVNC => GetIdentifierByAppliactionName(ApplicationName.TigerVNC), - SettingsViewName.SNMP => GetIdentifierByAppliactionName(ApplicationName.SNMP), - SettingsViewName.SNTPLookup => GetIdentifierByAppliactionName(ApplicationName.SNTPLookup), - SettingsViewName.WakeOnLAN => GetIdentifierByAppliactionName(ApplicationName.WakeOnLAN), - //SettingsViewName.Whois => GetIdentifierByAppliactionName(ApplicationName.Whois), - SettingsViewName.BitCalculator => GetIdentifierByAppliactionName(ApplicationName.BitCalculator), - _ => DocumentationIdentifier.Default, - }; - } + SettingsViewName.General => DocumentationIdentifier.SettingsGeneral, + SettingsViewName.Window => DocumentationIdentifier.SettingsWindow, + SettingsViewName.Appearance => DocumentationIdentifier.SettingsAppearance, + SettingsViewName.Language => DocumentationIdentifier.SettingsLanguage, + SettingsViewName.Network => DocumentationIdentifier.SettingsNetwork, + SettingsViewName.Status => DocumentationIdentifier.SettingsStatus, + SettingsViewName.HotKeys => DocumentationIdentifier.SettingsHotKeys, + SettingsViewName.Autostart => DocumentationIdentifier.SettingsAutostart, + SettingsViewName.Update => DocumentationIdentifier.SettingsUpdate, + SettingsViewName.Profiles => DocumentationIdentifier.SettingsProfiles, + SettingsViewName.Settings => DocumentationIdentifier.SettingsSettings, + SettingsViewName.Dashboard => GetIdentifierByAppliactionName(ApplicationName.Dashboard), + SettingsViewName.IPScanner => GetIdentifierByAppliactionName(ApplicationName.IPScanner), + SettingsViewName.PortScanner => GetIdentifierByAppliactionName(ApplicationName.PortScanner), + SettingsViewName.PingMonitor => GetIdentifierByAppliactionName(ApplicationName.PingMonitor), + SettingsViewName.Traceroute => GetIdentifierByAppliactionName(ApplicationName.Traceroute), + SettingsViewName.DNSLookup => GetIdentifierByAppliactionName(ApplicationName.DNSLookup), + SettingsViewName.RemoteDesktop => GetIdentifierByAppliactionName(ApplicationName.RemoteDesktop), + SettingsViewName.PowerShell => GetIdentifierByAppliactionName(ApplicationName.PowerShell), + SettingsViewName.PuTTY => GetIdentifierByAppliactionName(ApplicationName.PuTTY), + SettingsViewName.AWSSessionManager => GetIdentifierByAppliactionName(ApplicationName.AWSSessionManager), + SettingsViewName.TigerVNC => GetIdentifierByAppliactionName(ApplicationName.TigerVNC), + SettingsViewName.SNMP => GetIdentifierByAppliactionName(ApplicationName.SNMP), + SettingsViewName.SNTPLookup => GetIdentifierByAppliactionName(ApplicationName.SNTPLookup), + SettingsViewName.WakeOnLAN => GetIdentifierByAppliactionName(ApplicationName.WakeOnLAN), + //SettingsViewName.Whois => GetIdentifierByAppliactionName(ApplicationName.Whois), + SettingsViewName.BitCalculator => GetIdentifierByAppliactionName(ApplicationName.BitCalculator), + _ => DocumentationIdentifier.Default, + }; } } diff --git a/Source/NETworkManager.Documentation/ExternalServicesInfo.cs b/Source/NETworkManager.Documentation/ExternalServicesInfo.cs index 131ee2b7df..df404ffc67 100644 --- a/Source/NETworkManager.Documentation/ExternalServicesInfo.cs +++ b/Source/NETworkManager.Documentation/ExternalServicesInfo.cs @@ -1,20 +1,19 @@ -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// Class to hold all informations about an external service. +/// +public class ExternalServicesInfo : BaseInfo { /// - /// Class to hold all informations about an external service. + /// Create an instance of with parameters. /// - public class ExternalServicesInfo : BaseInfo + /// Name of the external service. + /// Url of the external service. + /// Description of the external service. + public ExternalServicesInfo(string name, string websiteUrl, string description) : base(name, websiteUrl, + description) { - /// - /// Create an instance of with parameters. - /// - /// Name of the external service. - /// Url of the external service. - /// Description of the external service. - public ExternalServicesInfo(string name, string websiteUrl, string description) : base(name, websiteUrl, - description) - { - } } } diff --git a/Source/NETworkManager.Documentation/ExternalServicesManager.cs b/Source/NETworkManager.Documentation/ExternalServicesManager.cs index 107330cdff..efc0679d12 100644 --- a/Source/NETworkManager.Documentation/ExternalServicesManager.cs +++ b/Source/NETworkManager.Documentation/ExternalServicesManager.cs @@ -1,18 +1,17 @@ using System.Collections.Generic; -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// This class provides information about external services used within the program. +/// +public static class ExternalServicesManager { /// - /// This class provides information about external services used within the program. + /// Static list with all external services that are used. /// - public static class ExternalServicesManager + public static List List => new() { - /// - /// Static list with all external services that are used. - /// - public static List List => new() - { - new ExternalServicesInfo("ipify", "https://www.ipify.org/", Localization.Resources.Strings.ExternalService_ipify_Description) - }; - } + new ExternalServicesInfo("ipify", "https://www.ipify.org/", Localization.Resources.Strings.ExternalService_ipify_Description) + }; } diff --git a/Source/NETworkManager.Documentation/LibraryInfo.cs b/Source/NETworkManager.Documentation/LibraryInfo.cs index 64975d2e7c..3167c24d15 100644 --- a/Source/NETworkManager.Documentation/LibraryInfo.cs +++ b/Source/NETworkManager.Documentation/LibraryInfo.cs @@ -1,32 +1,31 @@ -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// Class to hold all informations about a library. +/// +public class LibraryInfo : BaseInfo { /// - /// Class to hold all informations about a library. + /// License which is used by the library. /// - public class LibraryInfo : BaseInfo - { - /// - /// License which is used by the library. - /// - public string License { get; set; } + public string License { get; set; } - /// - /// Url of the license which is used by the library. - /// - public string LicenseUrl { get; set; } + /// + /// Url of the license which is used by the library. + /// + public string LicenseUrl { get; set; } - /// - /// Create an instance of with parameters. - /// - /// Name of the library. - /// Url of the library. - /// Description of the library. - /// License which is used by the library. - /// Url of the license which is used by the library. - public LibraryInfo(string name, string websiteUrl, string description, string license, string licenseUrl) : base(name, websiteUrl, description) - { - License = license; - LicenseUrl = licenseUrl; - } + /// + /// Create an instance of with parameters. + /// + /// Name of the library. + /// Url of the library. + /// Description of the library. + /// License which is used by the library. + /// Url of the license which is used by the library. + public LibraryInfo(string name, string websiteUrl, string description, string license, string licenseUrl) : base(name, websiteUrl, description) + { + License = license; + LicenseUrl = licenseUrl; } } diff --git a/Source/NETworkManager.Documentation/LibraryManager.cs b/Source/NETworkManager.Documentation/LibraryManager.cs index 2ca521dddd..56d5114990 100644 --- a/Source/NETworkManager.Documentation/LibraryManager.cs +++ b/Source/NETworkManager.Documentation/LibraryManager.cs @@ -2,52 +2,51 @@ using System.IO; using System.Reflection; -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// This class provides information about libraries used within the program. +/// +public static class LibraryManager { /// - /// This class provides information about libraries used within the program. + /// Name of the license folder. /// - public static class LibraryManager - { - /// - /// Name of the license folder. - /// - private const string LicenseFolderName = "Licenses"; - - /// - /// Method to get the license folder location. - /// - /// Location of the license folder. - public static string GetLicenseLocation() - { - return Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) ?? throw new DirectoryNotFoundException("Program execution directory not found, while trying to build path to license directory!"), LicenseFolderName); - } + private const string LicenseFolderName = "Licenses"; - /// - /// Static list with all libraries that are used. - /// - public static List List => new() - { - new LibraryInfo("MahApps.Metro", "https://github.com/mahapps/mahapps.metro", Localization.Resources.Strings.Library_MahAppsMetro_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/MahApps/MahApps.Metro/blob/master/LICENSE"), - new LibraryInfo("MahApps.Metro.IconPacks", "https://github.com/MahApps/MahApps.Metro.IconPacks", Localization.Resources.Strings.Library_MahAppsMetroIconPacks_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/MahApps/MahApps.Metro.IconPacks/blob/master/LICENSE"), - new LibraryInfo("ControlzEx", "https://github.com/ControlzEx/ControlzEx", Localization.Resources.Strings.Library_ControlzEx_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/ButchersBoy/Dragablz/blob/master/LICENSE"), - new LibraryInfo("Octokit", "https://github.com/octokit/octokit.net", Localization.Resources.Strings.Library_Octokit_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/octokit/octokit.net/blob/master/LICENSE.txt"), - new LibraryInfo("#SNMP Libary", "https://github.com/lextudio/sharpsnmplib", Localization.Resources.Strings.Library_SharpSNMP_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/lextudio/sharpsnmplib/blob/master/LICENSE"), - new LibraryInfo("Dragablz", "https://github.com/ButchersBoy/Dragablz", Localization.Resources.Strings.Library_Dragablz_Description, Localization.Resources.Strings.License_MITLicense,"https://github.com/ButchersBoy/Dragablz/blob/master/LICENSE"), - new LibraryInfo("IPNetwork", "https://github.com/lduchosal/ipnetwork", Localization.Resources.Strings.Library_IPNetwork_Description, Localization.Resources.Strings.License_BDS2Clause, "https://github.com/lduchosal/ipnetwork/blob/master/LICENSE"), - new LibraryInfo("AirspaceFixer" ,"https://github.com/chris84948/AirspaceFixer", Localization.Resources.Strings.Library_AirspaceFixer_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/chris84948/AirspaceFixer/blob/master/LICENSE"), - new LibraryInfo("Newtonsoft.Json", "https://github.com/JamesNK/Newtonsoft.Json", Localization.Resources.Strings.Library_NewtonsoftJson_Description, Localization.Resources.Strings.License_MITLicense,"https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md"), - new LibraryInfo("LiveCharts", "https://github.com/Live-Charts/Live-Charts", Localization.Resources.Strings.Library_LiveCharts_Description, Localization.Resources.Strings.License_MITLicense,"https://github.com/Live-Charts/Live-Charts/blob/master/LICENSE.TXT"), - new LibraryInfo("LoadingIndicators.WPF", "https://github.com/zeluisping/LoadingIndicators.WPF", Localization.Resources.Strings.Library_LoadingIndicatorsWPF_Description, Localization.Resources.Strings.License_Unlicense, "https://github.com/zeluisping/LoadingIndicators.WPF/blob/master/LICENSE"), - new LibraryInfo("DnsClient.NET", "https://github.com/MichaCo/DnsClient.NET",Localization.Resources.Strings.Library_DnsClientNET_Description, Localization.Resources.Strings.License_ApacheLicense2dot0, "https://github.com/MichaCo/DnsClient.NET/blob/dev/LICENSE"), - new LibraryInfo("PSDiscoveryProtocol", "https://github.com/lahell/PSDiscoveryProtocol",Localization.Resources.Strings.Library_PSDicoveryProtocol_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/lahell/PSDiscoveryProtocol/blob/master/LICENSE"), - new LibraryInfo("Microsoft.PowerShell.SDK", "https://github.com/PowerShell/PowerShell", Localization.Resources.Strings.Library_PowerShellSDK_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/PowerShell/PowerShell/blob/master/LICENSE.txt"), - new LibraryInfo("Microsoft.Web.WebView2", "https://docs.microsoft.com/en-us/microsoft-edge/webview2/", Localization.Resources.Strings.Library_WebView2_Description, Localization.Resources.Strings.License_MicrosoftWebView2License, "https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.824-prerelease/License"), - new LibraryInfo("Microsoft.Windows.CsWinRT", "https://github.com/microsoft/cswinrt/tree/master/", Localization.Resources.Strings.Library_CsWinRT_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/microsoft/CsWinRT/blob/master/LICENSE"), - new LibraryInfo("Microsoft.Xaml.Behaviors.Wpf", "https://github.com/microsoft/XamlBehaviorsWpf", Localization.Resources.Strings.Library_XamlBehaviorsWpf_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/microsoft/XamlBehaviorsWpf/blob/master/LICENSE"), - new LibraryInfo("log4net", "https://logging.apache.org/log4net/", Localization.Resources.Strings.Library_log4net_Description, Localization.Resources.Strings.License_ApacheLicense2dot0, "https://github.com/apache/logging-log4net/blob/master/LICENSE"), - new LibraryInfo("AWSSDK.EC2", "https://github.com/aws/aws-sdk-net/", Localization.Resources.Strings.Library_AWSSDKdotEC2_Description, Localization.Resources.Strings.License_ApacheLicense2dot0, "https://aws.amazon.com/apache-2-0/"), - new LibraryInfo("nulastudio.NetBeauty", "https://github.com/nulastudio/NetBeauty2", Localization.Resources.Strings.Library_nulastudioNetBeauty_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/nulastudio/NetBeauty2/blob/master/LICENSE"), - }; + /// + /// Method to get the license folder location. + /// + /// Location of the license folder. + public static string GetLicenseLocation() + { + return Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) ?? throw new DirectoryNotFoundException("Program execution directory not found, while trying to build path to license directory!"), LicenseFolderName); } + + /// + /// Static list with all libraries that are used. + /// + public static List List => new() + { + new LibraryInfo("MahApps.Metro", "https://github.com/mahapps/mahapps.metro", Localization.Resources.Strings.Library_MahAppsMetro_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/MahApps/MahApps.Metro/blob/master/LICENSE"), + new LibraryInfo("MahApps.Metro.IconPacks", "https://github.com/MahApps/MahApps.Metro.IconPacks", Localization.Resources.Strings.Library_MahAppsMetroIconPacks_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/MahApps/MahApps.Metro.IconPacks/blob/master/LICENSE"), + new LibraryInfo("ControlzEx", "https://github.com/ControlzEx/ControlzEx", Localization.Resources.Strings.Library_ControlzEx_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/ButchersBoy/Dragablz/blob/master/LICENSE"), + new LibraryInfo("Octokit", "https://github.com/octokit/octokit.net", Localization.Resources.Strings.Library_Octokit_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/octokit/octokit.net/blob/master/LICENSE.txt"), + new LibraryInfo("#SNMP Libary", "https://github.com/lextudio/sharpsnmplib", Localization.Resources.Strings.Library_SharpSNMP_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/lextudio/sharpsnmplib/blob/master/LICENSE"), + new LibraryInfo("Dragablz", "https://github.com/ButchersBoy/Dragablz", Localization.Resources.Strings.Library_Dragablz_Description, Localization.Resources.Strings.License_MITLicense,"https://github.com/ButchersBoy/Dragablz/blob/master/LICENSE"), + new LibraryInfo("IPNetwork", "https://github.com/lduchosal/ipnetwork", Localization.Resources.Strings.Library_IPNetwork_Description, Localization.Resources.Strings.License_BDS2Clause, "https://github.com/lduchosal/ipnetwork/blob/master/LICENSE"), + new LibraryInfo("AirspaceFixer" ,"https://github.com/chris84948/AirspaceFixer", Localization.Resources.Strings.Library_AirspaceFixer_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/chris84948/AirspaceFixer/blob/master/LICENSE"), + new LibraryInfo("Newtonsoft.Json", "https://github.com/JamesNK/Newtonsoft.Json", Localization.Resources.Strings.Library_NewtonsoftJson_Description, Localization.Resources.Strings.License_MITLicense,"https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md"), + new LibraryInfo("LiveCharts", "https://github.com/Live-Charts/Live-Charts", Localization.Resources.Strings.Library_LiveCharts_Description, Localization.Resources.Strings.License_MITLicense,"https://github.com/Live-Charts/Live-Charts/blob/master/LICENSE.TXT"), + new LibraryInfo("LoadingIndicators.WPF", "https://github.com/zeluisping/LoadingIndicators.WPF", Localization.Resources.Strings.Library_LoadingIndicatorsWPF_Description, Localization.Resources.Strings.License_Unlicense, "https://github.com/zeluisping/LoadingIndicators.WPF/blob/master/LICENSE"), + new LibraryInfo("DnsClient.NET", "https://github.com/MichaCo/DnsClient.NET",Localization.Resources.Strings.Library_DnsClientNET_Description, Localization.Resources.Strings.License_ApacheLicense2dot0, "https://github.com/MichaCo/DnsClient.NET/blob/dev/LICENSE"), + new LibraryInfo("PSDiscoveryProtocol", "https://github.com/lahell/PSDiscoveryProtocol",Localization.Resources.Strings.Library_PSDicoveryProtocol_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/lahell/PSDiscoveryProtocol/blob/master/LICENSE"), + new LibraryInfo("Microsoft.PowerShell.SDK", "https://github.com/PowerShell/PowerShell", Localization.Resources.Strings.Library_PowerShellSDK_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/PowerShell/PowerShell/blob/master/LICENSE.txt"), + new LibraryInfo("Microsoft.Web.WebView2", "https://docs.microsoft.com/en-us/microsoft-edge/webview2/", Localization.Resources.Strings.Library_WebView2_Description, Localization.Resources.Strings.License_MicrosoftWebView2License, "https://www.nuget.org/packages/Microsoft.Web.WebView2/1.0.824-prerelease/License"), + new LibraryInfo("Microsoft.Windows.CsWinRT", "https://github.com/microsoft/cswinrt/tree/master/", Localization.Resources.Strings.Library_CsWinRT_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/microsoft/CsWinRT/blob/master/LICENSE"), + new LibraryInfo("Microsoft.Xaml.Behaviors.Wpf", "https://github.com/microsoft/XamlBehaviorsWpf", Localization.Resources.Strings.Library_XamlBehaviorsWpf_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/microsoft/XamlBehaviorsWpf/blob/master/LICENSE"), + new LibraryInfo("log4net", "https://logging.apache.org/log4net/", Localization.Resources.Strings.Library_log4net_Description, Localization.Resources.Strings.License_ApacheLicense2dot0, "https://github.com/apache/logging-log4net/blob/master/LICENSE"), + new LibraryInfo("AWSSDK.EC2", "https://github.com/aws/aws-sdk-net/", Localization.Resources.Strings.Library_AWSSDKdotEC2_Description, Localization.Resources.Strings.License_ApacheLicense2dot0, "https://aws.amazon.com/apache-2-0/"), + new LibraryInfo("nulastudio.NetBeauty", "https://github.com/nulastudio/NetBeauty2", Localization.Resources.Strings.Library_nulastudioNetBeauty_Description, Localization.Resources.Strings.License_MITLicense, "https://github.com/nulastudio/NetBeauty2/blob/master/LICENSE"), + }; } diff --git a/Source/NETworkManager.Documentation/ResourceInfo.cs b/Source/NETworkManager.Documentation/ResourceInfo.cs index d3a4f970fd..a9e32b72b0 100644 --- a/Source/NETworkManager.Documentation/ResourceInfo.cs +++ b/Source/NETworkManager.Documentation/ResourceInfo.cs @@ -1,19 +1,18 @@ -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// Class to hold all informations about a resource. +/// +public class ResourceInfo : BaseInfo { /// - /// Class to hold all informations about a resource. + /// Create an instance of with parameters. /// - public class ResourceInfo : BaseInfo + /// Name of the resource. + /// Url of the resource. + /// Description of the resource. + public ResourceInfo(string name, string websiteUrl, string description) : base(name, websiteUrl, description) { - /// - /// Create an instance of with parameters. - /// - /// Name of the resource. - /// Url of the resource. - /// Description of the resource. - public ResourceInfo(string name, string websiteUrl, string description) : base(name, websiteUrl, description) - { - - } + } } diff --git a/Source/NETworkManager.Documentation/ResourceManager.cs b/Source/NETworkManager.Documentation/ResourceManager.cs index 09ac4eeba4..ec82831e6d 100644 --- a/Source/NETworkManager.Documentation/ResourceManager.cs +++ b/Source/NETworkManager.Documentation/ResourceManager.cs @@ -1,21 +1,20 @@ using System.Collections.Generic; -namespace NETworkManager.Documentation +namespace NETworkManager.Documentation; + +/// +/// This class provides information about resources used within the program. +/// +public static class ResourceManager { /// - /// This class provides information about resources used within the program. + /// Static list with all resources that are used. /// - public static class ResourceManager + public static List List => new() { - /// - /// Static list with all resources that are used. - /// - public static List List => new() - { - new ResourceInfo("Organizationally unique identifier", "https://standards-oui.ieee.org/oui/oui.txt", Localization.Resources.Strings.Resource_OUI_Description), - new ResourceInfo("Service names and port numbers", "https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml", Localization.Resources.Strings.Resource_ServiceNamePortNumber_Description), - new ResourceInfo("flag-icon-css","https://github.com/lipis/flag-icon-css", Localization.Resources.Strings.Resource_Flag_Description), - new ResourceInfo("List of Top-Level-Domains", "https://data.iana.org/TLD/tlds-alpha-by-domain.txt", Localization.Resources.Strings.Resource_ListTLD_Description) - }; - } + new ResourceInfo("Organizationally unique identifier", "https://standards-oui.ieee.org/oui/oui.txt", Localization.Resources.Strings.Resource_OUI_Description), + new ResourceInfo("Service names and port numbers", "https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml", Localization.Resources.Strings.Resource_ServiceNamePortNumber_Description), + new ResourceInfo("flag-icon-css","https://github.com/lipis/flag-icon-css", Localization.Resources.Strings.Resource_Flag_Description), + new ResourceInfo("List of Top-Level-Domains", "https://data.iana.org/TLD/tlds-alpha-by-domain.txt", Localization.Resources.Strings.Resource_ListTLD_Description) + }; } diff --git a/Source/NETworkManager.Localization/ILocalizationStringTranslator.cs b/Source/NETworkManager.Localization/ILocalizationStringTranslator.cs index b92454c66e..01d50ff417 100644 --- a/Source/NETworkManager.Localization/ILocalizationStringTranslator.cs +++ b/Source/NETworkManager.Localization/ILocalizationStringTranslator.cs @@ -1,15 +1,14 @@ -namespace NETworkManager.Localization +namespace NETworkManager.Localization; + +/// +/// Interface to translate strings. +/// +interface ILocalizationStringTranslator { /// - /// Interface to translate strings. + /// Method to translate strings. /// - interface ILocalizationStringTranslator - { - /// - /// Method to translate strings. - /// - /// Original string to translate. - /// Translated string. - string Translate(string value); - } + /// Original string to translate. + /// Translated string. + string Translate(string value); } diff --git a/Source/NETworkManager.Localization/LocalizationInfo.cs b/Source/NETworkManager.Localization/LocalizationInfo.cs index 136591d29e..b5be086020 100644 --- a/Source/NETworkManager.Localization/LocalizationInfo.cs +++ b/Source/NETworkManager.Localization/LocalizationInfo.cs @@ -1,69 +1,68 @@ using System; -namespace NETworkManager.Localization +namespace NETworkManager.Localization; + +/// +/// Class to hold all informations about a localization. +/// +public class LocalizationInfo { /// - /// Class to hold all informations about a localization. + /// Name of the Language. /// - public class LocalizationInfo - { - /// - /// Name of the Language. - /// - public string Name { get; set; } + public string Name { get; set; } - /// - /// Native name of the language. - /// - public string NativeName { get; set; } + /// + /// Native name of the language. + /// + public string NativeName { get; set; } - /// - /// Uri of the country flag. - /// - public Uri FlagUri { get; set; } + /// + /// Uri of the country flag. + /// + public Uri FlagUri { get; set; } - /// - /// Culture code of the language. - /// - public string Code { get; set; } + /// + /// Culture code of the language. + /// + public string Code { get; set; } - /// - /// Indicates whether the language has been translated by the maintainer or the community - /// - public bool IsOfficial { get; set; } - - /// - /// Create an empty instance of . - /// - public LocalizationInfo() - { + /// + /// Indicates whether the language has been translated by the maintainer or the community + /// + public bool IsOfficial { get; set; } + + /// + /// Create an empty instance of . + /// + public LocalizationInfo() + { - } + } - /// - /// Create an instance of with a culture code. - /// - /// Culture code (like "en-US") - public LocalizationInfo(string code) - { - Code = code; - } + /// + /// Create an instance of with a culture code. + /// + /// Culture code (like "en-US") + public LocalizationInfo(string code) + { + Code = code; + } - /// - /// Create an instance of with all parameters. - /// - /// . - /// . - /// . - /// . - /// . - public LocalizationInfo(string name, string nativeName, Uri flagUri, string code, bool isOfficial = false) - { - Name = name; - NativeName = nativeName; - FlagUri = flagUri; - Code = code; - IsOfficial = isOfficial; - } + /// + /// Create an instance of with all parameters. + /// + /// . + /// . + /// . + /// . + /// . + public LocalizationInfo(string name, string nativeName, Uri flagUri, string code, bool isOfficial = false) + { + Name = name; + NativeName = nativeName; + FlagUri = flagUri; + Code = code; + IsOfficial = isOfficial; } } diff --git a/Source/NETworkManager.Localization/LocalizationManager.cs b/Source/NETworkManager.Localization/LocalizationManager.cs index f35f2e44bf..a831050be8 100644 --- a/Source/NETworkManager.Localization/LocalizationManager.cs +++ b/Source/NETworkManager.Localization/LocalizationManager.cs @@ -3,129 +3,128 @@ using System.Globalization; using System.Linq; -namespace NETworkManager.Localization +namespace NETworkManager.Localization; + +/// +/// Class provides variables/methods to manage localization. +/// +public class LocalizationManager { /// - /// Class provides variables/methods to manage localization. + /// Constant for the default culture code. + /// + private const string _defaultCultureCode = "en-US"; + + /// + /// Constant with the path to the flag images. + /// + private const string _baseFlagImageUri = @"pack://application:,,,/NETworkManager.Localization;component/Resources/Flags/"; + + /// + /// Variable for the instance of the class. /// - public class LocalizationManager + private static LocalizationManager _instance = null; + + /// + /// Returns the current instance of the class. + /// The language can be set on creation (first call), by passing a culture code (like "en-US") as parameter. + /// Use to change it later. + /// + /// Culture code (default is "en-US"). See also . + /// Instance of the class. + public static LocalizationManager GetInstance(string cultureCode = _defaultCultureCode) { - /// - /// Constant for the default culture code. - /// - private const string _defaultCultureCode = "en-US"; - - /// - /// Constant with the path to the flag images. - /// - private const string _baseFlagImageUri = @"pack://application:,,,/NETworkManager.Localization;component/Resources/Flags/"; - - /// - /// Variable for the instance of the class. - /// - private static LocalizationManager _instance = null; - - /// - /// Returns the current instance of the class. - /// The language can be set on creation (first call), by passing a culture code (like "en-US") as parameter. - /// Use to change it later. - /// - /// Culture code (default is "en-US"). See also . - /// Instance of the class. - public static LocalizationManager GetInstance(string cultureCode = _defaultCultureCode) - { - _instance ??= new LocalizationManager(cultureCode); + _instance ??= new LocalizationManager(cultureCode); - return _instance; - } + return _instance; + } - /// - /// Method to build the uri for a flag image based on the culture code. - /// - /// Culture code like "en-US". - /// Uri of the flag image. - public static Uri GetImageUri(string cultureCode) - { - return new Uri(_baseFlagImageUri + cultureCode + ".png"); - } + /// + /// Method to build the uri for a flag image based on the culture code. + /// + /// Culture code like "en-US". + /// Uri of the flag image. + public static Uri GetImageUri(string cultureCode) + { + return new Uri(_baseFlagImageUri + cultureCode + ".png"); + } - /// - /// List with all s. - /// - public static List List => new List - { - // Offical - new LocalizationInfo("English", "English", GetImageUri("en-US"), "en-US", true), - new LocalizationInfo("German (Germany)", "Deutsch", GetImageUri("de-DE"), "de-DE", true), - - // Community - new LocalizationInfo("Chinese (China)", "大陆简体", GetImageUri("zh-CN"), "zh-CN"), - new LocalizationInfo("Chinese (Taiwan)", "台灣正體", GetImageUri("zh-TW"), "zh-TW"), - new LocalizationInfo("Czech (Czech Republic)", "Čeština", GetImageUri("cs-CZ"), "cs-CZ"), - new LocalizationInfo("Dutch (Netherlands)", "Nederlands", GetImageUri("nl-NL"), "nl-NL"), - new LocalizationInfo("French (France)", "Français", GetImageUri("fr-FR"), "fr-FR"), - new LocalizationInfo("Hungarian (Hungary)", "Magyar", GetImageUri("hu-HU"), "hu-HU"), - new LocalizationInfo("Italian (Italy)", "Italiano", GetImageUri("it-IT"), "it-IT"), - new LocalizationInfo("Korean (Korea)", "한국어",GetImageUri("ko-KR"),"ko-KR"), - new LocalizationInfo("Polish (Poland)", "Język polski", GetImageUri("pl-PL"), "pl-PL"), - new LocalizationInfo("Portuguese (Brazil)", "português brasileiro", GetImageUri("pt-BR"), "pt-BR"), - new LocalizationInfo("Russian (Russia)", "Русский", GetImageUri("ru-RU"), "ru-RU"), - new LocalizationInfo("Slovenian (Slovenia)", "slovenski jezik", GetImageUri("sl-SI"), "sl-SI"), - new LocalizationInfo("Spanish (Spain)", "Español", GetImageUri("es-ES"), "es-ES") - - }; - - /// - /// Variable with the currently used . - /// - public LocalizationInfo Current { get; private set; } = new LocalizationInfo(); - - /// - /// Variable with the currently used . - /// - public CultureInfo Culture { get; private set; } - - /// - /// Create an instance and load the language based on the culture code. - /// - /// Culture code (default is "en-US"). See also . - private LocalizationManager(string cultureCode = _defaultCultureCode) - { - if (string.IsNullOrEmpty(cultureCode)) - cultureCode = CultureInfo.CurrentCulture.Name; - - var info = GetLocalizationInfoBasedOnCode(cultureCode) ?? List.First(); - - if (info.Code != List.First().Code) - { - Change(info); - } - else - { - Current = info; - Culture = new CultureInfo(info.Code); - } - } + /// + /// List with all s. + /// + public static List List => new List + { + // Offical + new LocalizationInfo("English", "English", GetImageUri("en-US"), "en-US", true), + new LocalizationInfo("German (Germany)", "Deutsch", GetImageUri("de-DE"), "de-DE", true), + + // Community + new LocalizationInfo("Chinese (China)", "大陆简体", GetImageUri("zh-CN"), "zh-CN"), + new LocalizationInfo("Chinese (Taiwan)", "台灣正體", GetImageUri("zh-TW"), "zh-TW"), + new LocalizationInfo("Czech (Czech Republic)", "Čeština", GetImageUri("cs-CZ"), "cs-CZ"), + new LocalizationInfo("Dutch (Netherlands)", "Nederlands", GetImageUri("nl-NL"), "nl-NL"), + new LocalizationInfo("French (France)", "Français", GetImageUri("fr-FR"), "fr-FR"), + new LocalizationInfo("Hungarian (Hungary)", "Magyar", GetImageUri("hu-HU"), "hu-HU"), + new LocalizationInfo("Italian (Italy)", "Italiano", GetImageUri("it-IT"), "it-IT"), + new LocalizationInfo("Korean (Korea)", "한국어",GetImageUri("ko-KR"),"ko-KR"), + new LocalizationInfo("Polish (Poland)", "Język polski", GetImageUri("pl-PL"), "pl-PL"), + new LocalizationInfo("Portuguese (Brazil)", "português brasileiro", GetImageUri("pt-BR"), "pt-BR"), + new LocalizationInfo("Russian (Russia)", "Русский", GetImageUri("ru-RU"), "ru-RU"), + new LocalizationInfo("Slovenian (Slovenia)", "slovenski jezik", GetImageUri("sl-SI"), "sl-SI"), + new LocalizationInfo("Spanish (Spain)", "Español", GetImageUri("es-ES"), "es-ES") + + }; - /// - /// Method to get the based on the culture code. - /// - /// - /// Return the or if not found. - public static LocalizationInfo GetLocalizationInfoBasedOnCode(string cultureCode) + /// + /// Variable with the currently used . + /// + public LocalizationInfo Current { get; private set; } = new LocalizationInfo(); + + /// + /// Variable with the currently used . + /// + public CultureInfo Culture { get; private set; } + + /// + /// Create an instance and load the language based on the culture code. + /// + /// Culture code (default is "en-US"). See also . + private LocalizationManager(string cultureCode = _defaultCultureCode) + { + if (string.IsNullOrEmpty(cultureCode)) + cultureCode = CultureInfo.CurrentCulture.Name; + + var info = GetLocalizationInfoBasedOnCode(cultureCode) ?? List.First(); + + if (info.Code != List.First().Code) { - return List.FirstOrDefault(x => x.Code == cultureCode) ?? null; + Change(info); } - - /// - /// Method to change the langauge. - /// - /// - public void Change(LocalizationInfo info) + else { Current = info; - Culture = new CultureInfo(info.Code); } } + + /// + /// Method to get the based on the culture code. + /// + /// + /// Return the or if not found. + public static LocalizationInfo GetLocalizationInfoBasedOnCode(string cultureCode) + { + return List.FirstOrDefault(x => x.Code == cultureCode) ?? null; + } + + /// + /// Method to change the langauge. + /// + /// + public void Change(LocalizationInfo info) + { + Current = info; + + Culture = new CultureInfo(info.Code); + } } diff --git a/Source/NETworkManager.Localization/Translators/AccentTranslator.cs b/Source/NETworkManager.Localization/Translators/AccentTranslator.cs index 132794fd09..c065aa8390 100644 --- a/Source/NETworkManager.Localization/Translators/AccentTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/AccentTranslator.cs @@ -1,29 +1,28 @@ using NETworkManager.Models.Appearance; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + + +/// +/// Class to translate . +/// +public class AccentTranslator : SingletonBase, ILocalizationStringTranslator { - - /// - /// Class to translate . + /// + /// Constant to identify the strings in the language files. /// - public class AccentTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "Accent_"; + private const string _identifier = "Accent_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/ApplicationNameTranslator.cs b/Source/NETworkManager.Localization/Translators/ApplicationNameTranslator.cs index 061888b2f4..4f88e94b9b 100644 --- a/Source/NETworkManager.Localization/Translators/ApplicationNameTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/ApplicationNameTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class ApplicationNameTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class ApplicationNameTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "ApplicationName_"; + private const string _identifier = "ApplicationName_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(ApplicationName name) - { - return Translate(name.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(ApplicationName name) + { + return Translate(name.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/ConnectionStateTranslator.cs b/Source/NETworkManager.Localization/Translators/ConnectionStateTranslator.cs index 941ffdabc8..4d300e42fa 100644 --- a/Source/NETworkManager.Localization/Translators/ConnectionStateTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/ConnectionStateTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.Network; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators -{ +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class ConnectionStateTranslator : SingletonBase, ILocalizationStringTranslator +{ /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class ConnectionStateTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "ConnectionState_"; + private const string _identifier = "ConnectionState_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(ConnectionState connectionState) - { - return Translate(connectionState.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(ConnectionState connectionState) + { + return Translate(connectionState.ToString()); } } diff --git a/Source/NETworkManager.Localization/Translators/DiscoveryProtocolTranslator.cs b/Source/NETworkManager.Localization/Translators/DiscoveryProtocolTranslator.cs index 12ac251ee6..2dce15e427 100644 --- a/Source/NETworkManager.Localization/Translators/DiscoveryProtocolTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/DiscoveryProtocolTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.Network; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class DiscoveryProtocolTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class DiscoveryProtocolTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "DiscoveryProtocolIdentifier_"; + private const string _identifier = "DiscoveryProtocolIdentifier_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(DiscoveryProtocol.Protocol discoveryProtocol) - { - return Translate(discoveryProtocol.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(DiscoveryProtocol.Protocol discoveryProtocol) + { + return Translate(discoveryProtocol.ToString()); } } diff --git a/Source/NETworkManager.Localization/Translators/GroupViewNameTranslator.cs b/Source/NETworkManager.Localization/Translators/GroupViewNameTranslator.cs index 8b5477bad0..5731ba2140 100644 --- a/Source/NETworkManager.Localization/Translators/GroupViewNameTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/GroupViewNameTranslator.cs @@ -1,39 +1,38 @@ using NETworkManager.Profiles; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class GroupViewNameTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. + /// For groups this is the same identifier as for the profiles. /// - public class GroupViewNameTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// For groups this is the same identifier as for the profiles. - /// - private const string _identifier = "ProfileViewName_"; + private const string _identifier = "ProfileViewName_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(GroupViewName name) - { - return Translate(name.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(GroupViewName name) + { + return Translate(name.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/IPStatusTranslator.cs b/Source/NETworkManager.Localization/Translators/IPStatusTranslator.cs index 6920da1459..5089eefa26 100644 --- a/Source/NETworkManager.Localization/Translators/IPStatusTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/IPStatusTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Utilities; using System.Net.NetworkInformation; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class IPStatusTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class IPStatusTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "IPStatus_"; + private const string _identifier = "IPStatus_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(IPStatus ipStatus) - { - return Translate(ipStatus.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(IPStatus ipStatus) + { + return Translate(ipStatus.ToString()); } } diff --git a/Source/NETworkManager.Localization/Translators/PortStateTranslator.cs b/Source/NETworkManager.Localization/Translators/PortStateTranslator.cs index e1387cc9d9..d570b2700c 100644 --- a/Source/NETworkManager.Localization/Translators/PortStateTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/PortStateTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.Network; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class PortStateTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files /// - public class PortStateTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files - /// - private const string _identifier = "PortState_"; + private const string _identifier = "PortState_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(PortState portState) - { - return Translate(portState.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(PortState portState) + { + return Translate(portState.ToString()); } } diff --git a/Source/NETworkManager.Localization/Translators/ProfileViewNameTranslator.cs b/Source/NETworkManager.Localization/Translators/ProfileViewNameTranslator.cs index b8c5c2dd83..ea1d240e68 100644 --- a/Source/NETworkManager.Localization/Translators/ProfileViewNameTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/ProfileViewNameTranslator.cs @@ -1,40 +1,39 @@ using NETworkManager.Profiles; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class ProfileViewNameTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class ProfileViewNameTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "ProfileViewName_"; + private const string _identifier = "ProfileViewName_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - // Get the translation for the profile page - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + // Get the translation for the profile page + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - // If empty, try to get application name - return string.IsNullOrEmpty(translation) ? ApplicationNameTranslator.GetInstance().Translate(value) : translation; - } + // If empty, try to get application name + return string.IsNullOrEmpty(translation) ? ApplicationNameTranslator.GetInstance().Translate(value) : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(ProfileViewName name) - { - return Translate(name.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(ProfileViewName name) + { + return Translate(name.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/PuTTYLogModeTranslator.cs b/Source/NETworkManager.Localization/Translators/PuTTYLogModeTranslator.cs index 08f195959a..c8f0bfc34c 100644 --- a/Source/NETworkManager.Localization/Translators/PuTTYLogModeTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/PuTTYLogModeTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.PuTTY; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class PuTTYLogModeTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class PuTTYLogModeTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "PuTTYLogMode_"; + private const string _identifier = "PuTTYLogMode_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(LogMode logMode) - { - return Translate(logMode.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(LogMode logMode) + { + return Translate(logMode.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioCaptureRedirectionModeTranslator.cs b/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioCaptureRedirectionModeTranslator.cs index 9c780ad4ed..adc3258909 100644 --- a/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioCaptureRedirectionModeTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioCaptureRedirectionModeTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.RemoteDesktop; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class RemoteDesktopAudioCaptureRedirectionModeTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class RemoteDesktopAudioCaptureRedirectionModeTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "RemoteDesktopAudioCaptureRedirectionMode_"; + private const string _identifier = "RemoteDesktopAudioCaptureRedirectionMode_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(AudioCaptureRedirectionMode audioCaptureRedirectionMode) - { - return Translate(audioCaptureRedirectionMode.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(AudioCaptureRedirectionMode audioCaptureRedirectionMode) + { + return Translate(audioCaptureRedirectionMode.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioRedirectionModeTranslator.cs b/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioRedirectionModeTranslator.cs index 5fec98edc9..c455743515 100644 --- a/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioRedirectionModeTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/RemoteDesktopAudioRedirectionModeTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.RemoteDesktop; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class RemoteDesktopAudioRedirectionModeTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class RemoteDesktopAudioRedirectionModeTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "RemoteDesktopAudioRedirectionMode_"; + private const string _identifier = "RemoteDesktopAudioRedirectionMode_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(AudioRedirectionMode audioRedirectionMode) - { - return Translate(audioRedirectionMode.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(AudioRedirectionMode audioRedirectionMode) + { + return Translate(audioRedirectionMode.ToString()); } } diff --git a/Source/NETworkManager.Localization/Translators/RemoteDesktopKeyboardHookModeTranslator.cs b/Source/NETworkManager.Localization/Translators/RemoteDesktopKeyboardHookModeTranslator.cs index 78b6caacae..984658aa8b 100644 --- a/Source/NETworkManager.Localization/Translators/RemoteDesktopKeyboardHookModeTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/RemoteDesktopKeyboardHookModeTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.RemoteDesktop; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class RemoteDesktopKeyboardHookModeTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class RemoteDesktopKeyboardHookModeTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "RemoteDesktopKeyboardHookMode_"; + private const string _identifier = "RemoteDesktopKeyboardHookMode_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(KeyboardHookMode keyboardHookMode) - { - return Translate(keyboardHookMode.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(KeyboardHookMode keyboardHookMode) + { + return Translate(keyboardHookMode.ToString()); } } diff --git a/Source/NETworkManager.Localization/Translators/RemoteDesktopNetworkConnectionTypeTranslator.cs b/Source/NETworkManager.Localization/Translators/RemoteDesktopNetworkConnectionTypeTranslator.cs index 4ea1978895..1d6bf90b55 100644 --- a/Source/NETworkManager.Localization/Translators/RemoteDesktopNetworkConnectionTypeTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/RemoteDesktopNetworkConnectionTypeTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Models.RemoteDesktop; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class RemoteDesktopNetworkConnectionTypeTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class RemoteDesktopNetworkConnectionTypeTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "RemoteDesktopNetworkConnectionType_"; + private const string _identifier = "RemoteDesktopNetworkConnectionType_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(NetworkConnectionType networkConnectionType) - { - return Translate(networkConnectionType.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(NetworkConnectionType networkConnectionType) + { + return Translate(networkConnectionType.ToString()); } } diff --git a/Source/NETworkManager.Localization/Translators/SettingsViewGroupTranslator.cs b/Source/NETworkManager.Localization/Translators/SettingsViewGroupTranslator.cs index e10af1bf38..482268f609 100644 --- a/Source/NETworkManager.Localization/Translators/SettingsViewGroupTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/SettingsViewGroupTranslator.cs @@ -1,38 +1,37 @@ using NETworkManager.Settings; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class SettingsViewGroupTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. + /// + private const string _identifier = "SettingsViewGroup_"; + + /// + /// Method to translate . /// - public class SettingsViewGroupTranslator : SingletonBase, ILocalizationStringTranslator + /// as . + /// Translated . + public string Translate(string value) { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "SettingsViewGroup_"; - - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(SettingsViewGroup group) - { - return Translate(group.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(SettingsViewGroup group) + { + return Translate(group.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/SettingsViewNameTranslator.cs b/Source/NETworkManager.Localization/Translators/SettingsViewNameTranslator.cs index 6aea02a55c..5873d0690b 100644 --- a/Source/NETworkManager.Localization/Translators/SettingsViewNameTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/SettingsViewNameTranslator.cs @@ -1,40 +1,39 @@ using NETworkManager.Settings; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class SettingsViewNameTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class SettingsViewNameTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "SettingsViewName_"; + private const string _identifier = "SettingsViewName_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - // Get the translation for the settings page - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + // Get the translation for the settings page + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - // If empty, try to get application name - return string.IsNullOrEmpty(translation) ? ApplicationNameTranslator.GetInstance().Translate(value) : translation; - } + // If empty, try to get application name + return string.IsNullOrEmpty(translation) ? ApplicationNameTranslator.GetInstance().Translate(value) : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(SettingsViewName name) - { - return Translate(name.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(SettingsViewName name) + { + return Translate(name.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/TcpStateTranslator.cs b/Source/NETworkManager.Localization/Translators/TcpStateTranslator.cs index 9848c85e3b..171c75b4d2 100644 --- a/Source/NETworkManager.Localization/Translators/TcpStateTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/TcpStateTranslator.cs @@ -1,39 +1,38 @@ using NETworkManager.Utilities; using System.Net.NetworkInformation; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class TcpStateTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class TcpStateTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "TcpState_"; + private const string _identifier = "TcpState_"; - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(TcpState tcpState) - { - return Translate(tcpState.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(TcpState tcpState) + { + return Translate(tcpState.ToString()); } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/ThemeTranslator.cs b/Source/NETworkManager.Localization/Translators/ThemeTranslator.cs index ab38e5741f..d6d3751856 100644 --- a/Source/NETworkManager.Localization/Translators/ThemeTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/ThemeTranslator.cs @@ -1,28 +1,27 @@ using NETworkManager.Models.Appearance; using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate . +/// +public class ThemeTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate . + /// Constant to identify the strings in the language files. /// - public class ThemeTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "Theme_"; + private const string _identifier = "Theme_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; } } \ No newline at end of file diff --git a/Source/NETworkManager.Localization/Translators/TimeUnitTranslator.cs b/Source/NETworkManager.Localization/Translators/TimeUnitTranslator.cs index b06acc2cea..34dd75e301 100644 --- a/Source/NETworkManager.Localization/Translators/TimeUnitTranslator.cs +++ b/Source/NETworkManager.Localization/Translators/TimeUnitTranslator.cs @@ -1,37 +1,36 @@ using NETworkManager.Utilities; -namespace NETworkManager.Localization.Translators +namespace NETworkManager.Localization.Translators; + +/// +/// Class to translate +/// +public class TimeUnitTranslator : SingletonBase, ILocalizationStringTranslator { /// - /// Class to translate + /// Constant to identify the strings in the language files. /// - public class TimeUnitTranslator : SingletonBase, ILocalizationStringTranslator - { - /// - /// Constant to identify the strings in the language files. - /// - private const string _identifier = "TimeUnit_"; + private const string _identifier = "TimeUnit_"; - /// - /// Method to translate . - /// - /// as . - /// Translated . - public string Translate(string value) - { - var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); + /// + /// Method to translate . + /// + /// as . + /// Translated . + public string Translate(string value) + { + var translation = Resources.Strings.ResourceManager.GetString(_identifier + value, LocalizationManager.GetInstance().Culture); - return string.IsNullOrEmpty(translation) ? value : translation; - } + return string.IsNullOrEmpty(translation) ? value : translation; + } - /// - /// Method to translate . - /// - /// . - /// Translated . - public string Translate(TimeUnit timeUnit) - { - return Translate(timeUnit.ToString()); - } + /// + /// Method to translate . + /// + /// . + /// Translated . + public string Translate(TimeUnit timeUnit) + { + return Translate(timeUnit.ToString()); } } \ No newline at end of file From 8c360e66cd53455c215b01d0350090b74122d63d Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:29:45 +0100 Subject: [PATCH 07/11] Chore: Use .NET 7 syntax --- .../MultiSelectDataGrid.cs | 33 ++++++------ .../MultiSelectScrollingDataGrid.cs | 49 +++++++++--------- .../ObservableSetCollection.cs | 51 +++++++++---------- 3 files changed, 65 insertions(+), 68 deletions(-) diff --git a/Source/NETworkManager.Controls/MultiSelectDataGrid.cs b/Source/NETworkManager.Controls/MultiSelectDataGrid.cs index e096889df7..bf10978108 100644 --- a/Source/NETworkManager.Controls/MultiSelectDataGrid.cs +++ b/Source/NETworkManager.Controls/MultiSelectDataGrid.cs @@ -2,26 +2,25 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public class MultiSelectDataGrid : DataGrid { - public class MultiSelectDataGrid : DataGrid + public MultiSelectDataGrid() { - public MultiSelectDataGrid() - { - SelectionChanged += DataGridMultiItemSelect_SelectionChanged; - } - - private void DataGridMultiItemSelect_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - SelectedItemsList = SelectedItems; - } + SelectionChanged += DataGridMultiItemSelect_SelectionChanged; + } - public IList SelectedItemsList - { - get => (IList)GetValue(SelectedItemsListProperty); - set => SetValue(SelectedItemsListProperty, value); - } + private void DataGridMultiItemSelect_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + SelectedItemsList = SelectedItems; + } - public static readonly DependencyProperty SelectedItemsListProperty = DependencyProperty.Register("SelectedItemsList", typeof(IList), typeof(MultiSelectDataGrid), new PropertyMetadata(null)); + public IList SelectedItemsList + { + get => (IList)GetValue(SelectedItemsListProperty); + set => SetValue(SelectedItemsListProperty, value); } + + public static readonly DependencyProperty SelectedItemsListProperty = DependencyProperty.Register("SelectedItemsList", typeof(IList), typeof(MultiSelectDataGrid), new PropertyMetadata(null)); } diff --git a/Source/NETworkManager.Controls/MultiSelectScrollingDataGrid.cs b/Source/NETworkManager.Controls/MultiSelectScrollingDataGrid.cs index 7d94c1e296..2a4325aa32 100644 --- a/Source/NETworkManager.Controls/MultiSelectScrollingDataGrid.cs +++ b/Source/NETworkManager.Controls/MultiSelectScrollingDataGrid.cs @@ -3,39 +3,38 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public class MultiSelectScrollingDataGrid : DataGrid { - public class MultiSelectScrollingDataGrid : DataGrid + public MultiSelectScrollingDataGrid() { - public MultiSelectScrollingDataGrid() - { - SelectionChanged += DataGridMultiItemSelect_SelectionChanged; - } + SelectionChanged += DataGridMultiItemSelect_SelectionChanged; + } - private void DataGridMultiItemSelect_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - SelectedItemsList = SelectedItems; - } + private void DataGridMultiItemSelect_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + SelectedItemsList = SelectedItems; + } - public IList SelectedItemsList - { - get => (IList)GetValue(SelectedItemsListProperty); - set => SetValue(SelectedItemsListProperty, value); - } + public IList SelectedItemsList + { + get => (IList)GetValue(SelectedItemsListProperty); + set => SetValue(SelectedItemsListProperty, value); + } - public static readonly DependencyProperty SelectedItemsListProperty = DependencyProperty.Register("SelectedItemsList", typeof(IList), typeof(MultiSelectScrollingDataGrid), new PropertyMetadata(null)); + public static readonly DependencyProperty SelectedItemsListProperty = DependencyProperty.Register("SelectedItemsList", typeof(IList), typeof(MultiSelectScrollingDataGrid), new PropertyMetadata(null)); - protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) - { - if (e.NewItems == null) - return; + protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) + { + if (e.NewItems == null) + return; - var newItemCount = e.NewItems.Count; + var newItemCount = e.NewItems.Count; - if (newItemCount > 0) - ScrollIntoView(e.NewItems[newItemCount - 1]); + if (newItemCount > 0) + ScrollIntoView(e.NewItems[newItemCount - 1]); - base.OnItemsChanged(e); - } + base.OnItemsChanged(e); } } \ No newline at end of file diff --git a/Source/NETworkManager.Controls/ObservableSetCollection.cs b/Source/NETworkManager.Controls/ObservableSetCollection.cs index 48825552ff..7a2be4fbdf 100644 --- a/Source/NETworkManager.Controls/ObservableSetCollection.cs +++ b/Source/NETworkManager.Controls/ObservableSetCollection.cs @@ -2,41 +2,40 @@ using System.Collections.ObjectModel; -namespace NETworkManager.Controls -{ - public class ObservableSetCollection : ObservableCollection - { - public ObservableSetCollection() - { +namespace NETworkManager.Controls; - } +public class ObservableSetCollection : ObservableCollection +{ + public ObservableSetCollection() + { - public ObservableSetCollection(List list) : base(list) - { + } - } + public ObservableSetCollection(List list) : base(list) + { - public ObservableSetCollection(IEnumerable collection) : base(collection) - { + } - } + public ObservableSetCollection(IEnumerable collection) : base(collection) + { - protected override void InsertItem(int index, T item) - { - if (Contains(item)) - return; // Item already exists + } - base.InsertItem(index, item); - } + protected override void InsertItem(int index, T item) + { + if (Contains(item)) + return; // Item already exists + + base.InsertItem(index, item); + } - protected override void SetItem(int index, T item) - { - int i = IndexOf(item); + protected override void SetItem(int index, T item) + { + int i = IndexOf(item); - if (i >= 0 && i != index) - return; // Item already exists + if (i >= 0 && i != index) + return; // Item already exists - base.SetItem(index, item); - } + base.SetItem(index, item); } } \ No newline at end of file From 75dba705ef3066e41d77a36964b1b637c59a3191 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:33:46 +0100 Subject: [PATCH 08/11] Chore: Use .NET 7 syntax --- .../AccentToStringConverter.cs | 59 +++++++------ .../ApplicationNameToIconConverter.cs | 59 +++++++------ ...licationNameToTranslatedStringConverter.cs | 59 +++++++------ .../AutoRefreshTimeToStringConverter.cs | 59 +++++++------ .../BandwidthBytesToSpeedConverter.cs | 19 ++--- .../BandwidthBytesWithSizeConverter.cs | 19 ++--- .../BigIntegerToStringConverter.cs | 23 +++-- .../BooleanReverseConverter.cs | 19 ++--- ...anReverseToVisibilityCollapsedConverter.cs | 19 ++--- ...oleanReverseToVisibilityHiddenConverter.cs | 19 ++--- .../BooleanToStringConverter.cs | 23 +++-- .../BooleanToVisibilityCollapsedConverter.cs | 19 ++--- .../BooleanToVisibilityHiddenConverter.cs | 19 ++--- .../BooleansOrConverter.cs | 19 ++--- .../Bytes1000ToSizeConverter.cs | 19 ++--- .../Bytes1000ToSpeedConverter.cs | 35 ++++---- ...onnectionStateToRectangleStyleConverter.cs | 49 ++++++----- .../ConnectionStateToStringConverter.cs | 59 +++++++------ .../DNSServerConnectionInfoProfileToString.cs | 27 +++--- .../DiscoveryProtocolToStringConverter.cs | 57 +++++++------ ...roupViewNameToTranslatedStringConverter.cs | 59 +++++++------ .../IPAddressArrayToStringConverter.cs | 41 +++++---- ...ssSubnetmaskTupleArrayToStringConverter.cs | 41 +++++---- .../IPAddressToStringConverter.cs | 19 ++--- .../IPStatusToStringConverter.cs | 61 +++++++------- .../IntGreater1ToBooleanConverter.cs | 23 +++-- .../IntToStringConverter.cs | 25 +++--- ...roReverseToVisibilityCollapsedConverter.cs | 19 ++--- .../IntZeroToVisibilityCollapsedConverter.cs | 19 ++--- .../IsDynamicProfileToBooleanConverter.cs | 23 +++-- .../IsProfilesLocationToBooleanConverter.cs | 19 ++--- .../IsSettingsLocationToBooleanConverter.cs | 19 ++--- ...stServerConnectionInfoToStringConverter.cs | 39 +++++---- .../ListToStringConverter.cs | 19 ++--- .../LvlChartsBandwidthValueConverter.cs | 41 +++++---- .../LvlChartsHeaderConverter.cs | 31 ++++--- .../LvlChartsPingTimeValueConverter.cs | 41 +++++---- .../MACAddressToVendorConverter.cs | 23 +++-- .../NullOrEmptyToBoolConverter.cs | 19 ++--- .../NullOrEmptyToStringConverter.cs | 21 +++-- .../NullToFalseConverter.cs | 19 ++--- .../NullableDateTimeToStringConverter.cs | 23 +++-- .../OperationalStatusToStringConverter.cs | 25 +++--- .../PercentConverter.cs | 23 +++-- .../PhysicalAddressToStringConverter.cs | 25 +++--- .../PingStatusToBooleanConverter.cs | 19 ++--- .../PingTimeToStringConverter.cs | 19 ++--- .../PortStateToStringConverter.cs | 59 +++++++------ ...fileViewNameToTranslatedStringConverter.cs | 59 +++++++------ .../PuTTYLogModeToStringConverter.cs | 57 +++++++------ ...CaptureRedirectionModeToStringConverter.cs | 57 +++++++------ ...opAudioRedirectionModeToStringConverter.cs | 57 +++++++------ ...esktopKeyboardHookModeToStringConverter.cs | 57 +++++++------ ...pNetworkConnectionTypeToStringConverter.cs | 57 +++++++------ .../SelectedItemsToBooleanConverter.cs | 19 ++--- ...ngsViewGroupToTranslatedStringConverter.cs | 59 +++++++------ ...ingsViewNameToTranslatedStringConverter.cs | 59 +++++++------ ...lOrEmptyOrIPv4AddressToBooleanConverter.cs | 19 ++--- ...tringIsNotNullOrEmptyToBooleanConverter.cs | 19 ++--- ...llOrEmptyToVisibilityCollapsedConverter.cs | 19 ++--- .../TcpStateToStringConverter.cs | 59 +++++++------ .../ThemeToStringConverter.cs | 59 +++++++------ .../TimeSpanToMillisecondConverter.cs | 27 +++--- .../TimeSpanToStringConverter.cs | 23 +++-- .../TimeUnitToStringConverter.cs | 57 +++++++------ .../TimestampToStringConverter.cs | 19 ++--- ...ValidateNetworkInterfaceConfigConverter.cs | 19 ++--- ...dateSubnetCalculatorSubnettingConverter.cs | 83 +++++++++---------- ...teSubnetCalculatorSupernettingConverter.cs | 49 ++++++----- ...ationTypeToHumanReadableStringConverter.cs | 27 +++--- ...enterFrequencyToChannelStringConvertert.cs | 23 +++-- ...nterFrequencyToFrequencyStringConverter.cs | 23 +++-- .../WiFiDBMReverseConverter.cs | 23 +++-- ...lliwattsToSignalStrengthStringConverter.cs | 23 +++-- .../WiFiPhyKindToStringConverter.cs | 23 +++-- 75 files changed, 1247 insertions(+), 1322 deletions(-) diff --git a/Source/NETworkManager.Converters/AccentToStringConverter.cs b/Source/NETworkManager.Converters/AccentToStringConverter.cs index f48e4f4cb7..2dcd494e83 100644 --- a/Source/NETworkManager.Converters/AccentToStringConverter.cs +++ b/Source/NETworkManager.Converters/AccentToStringConverter.cs @@ -4,41 +4,40 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.Appearance; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class AccentToStringConverter : IValueConverter { + /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class AccentToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (!(value is string accent)) + return "-/-"; - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is string accent)) - return "-/-"; - - return AccentTranslator.GetInstance().Translate(accent); - } + return AccentTranslator.GetInstance().Translate(accent); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ApplicationNameToIconConverter.cs b/Source/NETworkManager.Converters/ApplicationNameToIconConverter.cs index 19f52f54a6..e919a8d718 100644 --- a/Source/NETworkManager.Converters/ApplicationNameToIconConverter.cs +++ b/Source/NETworkManager.Converters/ApplicationNameToIconConverter.cs @@ -4,40 +4,39 @@ using System.Windows.Data; using NETworkManager.Models; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to icon () or wise versa. +/// +public sealed class ApplicationNameToIconConverter : IValueConverter { /// - /// Convert to icon () or wise versa. + /// Convert to icon (). /// - public sealed class ApplicationNameToIconConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Icon (cref="Canvas"/>). + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to icon (). - /// - /// Object from type . - /// - /// - /// - /// Icon (cref="Canvas"/>). - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is ApplicationName name)) - return null; + if (!(value is ApplicationName name)) + return null; - return ApplicationManager.GetIcon(name); - } - - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return ApplicationManager.GetIcon(name); + } + + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ApplicationNameToTranslatedStringConverter.cs b/Source/NETworkManager.Converters/ApplicationNameToTranslatedStringConverter.cs index b8e5647741..acb939fc4c 100644 --- a/Source/NETworkManager.Converters/ApplicationNameToTranslatedStringConverter.cs +++ b/Source/NETworkManager.Converters/ApplicationNameToTranslatedStringConverter.cs @@ -4,40 +4,39 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class ApplicationNameToTranslatedStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class ApplicationNameToTranslatedStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is ApplicationName name)) - return "-/-"; + if (!(value is ApplicationName name)) + return "-/-"; - return ApplicationNameTranslator.GetInstance().Translate(name); - } - - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return ApplicationNameTranslator.GetInstance().Translate(name); + } + + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/AutoRefreshTimeToStringConverter.cs b/Source/NETworkManager.Converters/AutoRefreshTimeToStringConverter.cs index 5aedca1896..60004b1d7a 100644 --- a/Source/NETworkManager.Converters/AutoRefreshTimeToStringConverter.cs +++ b/Source/NETworkManager.Converters/AutoRefreshTimeToStringConverter.cs @@ -4,40 +4,39 @@ using NETworkManager.Localization.Translators; using NETworkManager.Utilities; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class AutoRefreshTimeToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class AutoRefreshTimeToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is TimeUnit timeUnit)) - return "-/-"; - - return TimeUnitTranslator.GetInstance().Translate(timeUnit); - } + if (!(value is TimeUnit timeUnit)) + return "-/-"; + + return TimeUnitTranslator.GetInstance().Translate(timeUnit); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } \ No newline at end of file diff --git a/Source/NETworkManager.Converters/BandwidthBytesToSpeedConverter.cs b/Source/NETworkManager.Converters/BandwidthBytesToSpeedConverter.cs index c5451d8dc6..a6c652d265 100644 --- a/Source/NETworkManager.Converters/BandwidthBytesToSpeedConverter.cs +++ b/Source/NETworkManager.Converters/BandwidthBytesToSpeedConverter.cs @@ -3,18 +3,17 @@ using System.Windows.Data; using NETworkManager.Utilities; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BandwidthBytesToSpeedConverter : IValueConverter { - public sealed class BandwidthBytesToSpeedConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null ? $"{FileSizeConverter.GetBytesReadable((long)value * 8)}it/s ({FileSizeConverter.GetBytesReadable((long)value)}/s)" : "-/-"; - } + return value != null ? $"{FileSizeConverter.GetBytesReadable((long)value * 8)}it/s ({FileSizeConverter.GetBytesReadable((long)value)}/s)" : "-/-"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BandwidthBytesWithSizeConverter.cs b/Source/NETworkManager.Converters/BandwidthBytesWithSizeConverter.cs index c080ac2061..7784443a6b 100644 --- a/Source/NETworkManager.Converters/BandwidthBytesWithSizeConverter.cs +++ b/Source/NETworkManager.Converters/BandwidthBytesWithSizeConverter.cs @@ -3,18 +3,17 @@ using System.Windows.Data; using NETworkManager.Utilities; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BandwidthBytesWithSizeConverter : IValueConverter { - public sealed class BandwidthBytesWithSizeConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null ? $"{(long)value} ({FileSizeConverter.GetBytesReadable((long)value)})" : "-/-"; - } + return value != null ? $"{(long)value} ({FileSizeConverter.GetBytesReadable((long)value)})" : "-/-"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BigIntegerToStringConverter.cs b/Source/NETworkManager.Converters/BigIntegerToStringConverter.cs index 406cff3baa..30d6584916 100644 --- a/Source/NETworkManager.Converters/BigIntegerToStringConverter.cs +++ b/Source/NETworkManager.Converters/BigIntegerToStringConverter.cs @@ -5,21 +5,20 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BigIntegerToStringConverter : IValueConverter { - public sealed class BigIntegerToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) - return "-/-"; + if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) + return "-/-"; - return value != null ? ((BigInteger) value).ToString() : "-/-"; - } + return value != null ? ((BigInteger) value).ToString() : "-/-"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BooleanReverseConverter.cs b/Source/NETworkManager.Converters/BooleanReverseConverter.cs index ece7ddcd05..ea9e88f072 100644 --- a/Source/NETworkManager.Converters/BooleanReverseConverter.cs +++ b/Source/NETworkManager.Converters/BooleanReverseConverter.cs @@ -2,18 +2,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BooleanReverseConverter : IValueConverter { - public sealed class BooleanReverseConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null && !(bool)value; - } + return value != null && !(bool)value; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BooleanReverseToVisibilityCollapsedConverter.cs b/Source/NETworkManager.Converters/BooleanReverseToVisibilityCollapsedConverter.cs index d926252bac..7047f8aaa8 100644 --- a/Source/NETworkManager.Converters/BooleanReverseToVisibilityCollapsedConverter.cs +++ b/Source/NETworkManager.Converters/BooleanReverseToVisibilityCollapsedConverter.cs @@ -3,18 +3,17 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BooleanReverseToVisibilityCollapsedConverter : IValueConverter { - public sealed class BooleanReverseToVisibilityCollapsedConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is bool visible && visible ? Visibility.Collapsed : Visibility.Visible; - } + return value is bool visible && visible ? Visibility.Collapsed : Visibility.Visible; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BooleanReverseToVisibilityHiddenConverter.cs b/Source/NETworkManager.Converters/BooleanReverseToVisibilityHiddenConverter.cs index c7ddd1a41b..5ca3134224 100644 --- a/Source/NETworkManager.Converters/BooleanReverseToVisibilityHiddenConverter.cs +++ b/Source/NETworkManager.Converters/BooleanReverseToVisibilityHiddenConverter.cs @@ -3,18 +3,17 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BooleanReverseToVisibilityHiddenConverter : IValueConverter { - public sealed class BooleanReverseToVisibilityHiddenConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is bool visible && visible ? Visibility.Hidden : Visibility.Visible; - } + return value is bool visible && visible ? Visibility.Hidden : Visibility.Visible; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BooleanToStringConverter.cs b/Source/NETworkManager.Converters/BooleanToStringConverter.cs index 90a1901f99..546e777491 100644 --- a/Source/NETworkManager.Converters/BooleanToStringConverter.cs +++ b/Source/NETworkManager.Converters/BooleanToStringConverter.cs @@ -2,21 +2,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BooleanToStringConverter : IValueConverter { - public sealed class BooleanToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value != null && (bool) value) - return Localization.Resources.Strings.Yes; + if (value != null && (bool) value) + return Localization.Resources.Strings.Yes; - return Localization.Resources.Strings.No; - } + return Localization.Resources.Strings.No; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BooleanToVisibilityCollapsedConverter.cs b/Source/NETworkManager.Converters/BooleanToVisibilityCollapsedConverter.cs index aded844365..47b64f7864 100644 --- a/Source/NETworkManager.Converters/BooleanToVisibilityCollapsedConverter.cs +++ b/Source/NETworkManager.Converters/BooleanToVisibilityCollapsedConverter.cs @@ -3,18 +3,17 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BooleanToVisibilityCollapsedConverter : IValueConverter { - public sealed class BooleanToVisibilityCollapsedConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is bool visible && visible ? Visibility.Visible : Visibility.Collapsed; - } + return value is bool visible && visible ? Visibility.Visible : Visibility.Collapsed; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BooleanToVisibilityHiddenConverter.cs b/Source/NETworkManager.Converters/BooleanToVisibilityHiddenConverter.cs index 5282d355de..f8b691c2ff 100644 --- a/Source/NETworkManager.Converters/BooleanToVisibilityHiddenConverter.cs +++ b/Source/NETworkManager.Converters/BooleanToVisibilityHiddenConverter.cs @@ -3,18 +3,17 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BooleanToVisibilityHiddenConverter : IValueConverter { - public sealed class BooleanToVisibilityHiddenConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is bool visible && visible ? Visibility.Visible : Visibility.Hidden; - } + return value is bool visible && visible ? Visibility.Visible : Visibility.Hidden; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/BooleansOrConverter.cs b/Source/NETworkManager.Converters/BooleansOrConverter.cs index a5cd475aa3..35cbd91778 100644 --- a/Source/NETworkManager.Converters/BooleansOrConverter.cs +++ b/Source/NETworkManager.Converters/BooleansOrConverter.cs @@ -3,18 +3,17 @@ using System.Linq; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class BooleansOrConverter : IMultiValueConverter { - public sealed class BooleansOrConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - return values.Any(value => (bool) value); - } + return values.Any(value => (bool) value); + } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/Bytes1000ToSizeConverter.cs b/Source/NETworkManager.Converters/Bytes1000ToSizeConverter.cs index 82d19b99da..002c229faf 100644 --- a/Source/NETworkManager.Converters/Bytes1000ToSizeConverter.cs +++ b/Source/NETworkManager.Converters/Bytes1000ToSizeConverter.cs @@ -3,18 +3,17 @@ using System.Windows.Data; using NETworkManager.Utilities; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class Bytes1000ToSizeConverter : IValueConverter { - public sealed class Bytes1000ToSizeConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null ? $"{FileSizeConverter.GetBytesReadable((long)value)}" : "-/-"; - } + return value != null ? $"{FileSizeConverter.GetBytesReadable((long)value)}" : "-/-"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/Bytes1000ToSpeedConverter.cs b/Source/NETworkManager.Converters/Bytes1000ToSpeedConverter.cs index 927e872b31..35e458f8a4 100644 --- a/Source/NETworkManager.Converters/Bytes1000ToSpeedConverter.cs +++ b/Source/NETworkManager.Converters/Bytes1000ToSpeedConverter.cs @@ -2,30 +2,29 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class Bytes1000ToSpeedConverter : IValueConverter { - public sealed class Bytes1000ToSpeedConverter : IValueConverter - { - private readonly string[] _sizes = { "Bit/s", "KBit/s", "MBit/s", "GBit/s", "Tbit/s" }; + private readonly string[] _sizes = { "Bit/s", "KBit/s", "MBit/s", "GBit/s", "Tbit/s" }; - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value == null) - return "-/-"; + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value == null) + return "-/-"; - double.TryParse(value.ToString(), out var bits); + double.TryParse(value.ToString(), out var bits); - var sizeCount = 0; + var sizeCount = 0; - while (bits >= 1000 && ++sizeCount < _sizes.Length) - bits /= 1000; + while (bits >= 1000 && ++sizeCount < _sizes.Length) + bits /= 1000; - return $"{bits} {_sizes[sizeCount]}"; - } + return $"{bits} {_sizes[sizeCount]}"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ConnectionStateToRectangleStyleConverter.cs b/Source/NETworkManager.Converters/ConnectionStateToRectangleStyleConverter.cs index b9de369148..c9c10736fb 100644 --- a/Source/NETworkManager.Converters/ConnectionStateToRectangleStyleConverter.cs +++ b/Source/NETworkManager.Converters/ConnectionStateToRectangleStyleConverter.cs @@ -4,37 +4,36 @@ using System.Windows.Data; using NETworkManager.Models.Network; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class ConnectionStateToRectangleStyleConverter : IValueConverter { - public sealed class ConnectionStateToRectangleStyleConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + if (value != null && value is ConnectionState state) { - if (value != null && value is ConnectionState state) + switch (state) { - switch (state) - { - case ConnectionState.None: - break; - case ConnectionState.OK: - return Application.Current.Resources["CheckRectangle"] as Style; - case ConnectionState.Warning: - return Application.Current.Resources["AlertRectangle"] as Style; - case ConnectionState.Critical: - return Application.Current.Resources["ErrorRectangle"] as Style; - case ConnectionState.Info: - return Application.Current.Resources["InfoRectangle"] as Style; - default: - throw new ArgumentOutOfRangeException(); - } + case ConnectionState.None: + break; + case ConnectionState.OK: + return Application.Current.Resources["CheckRectangle"] as Style; + case ConnectionState.Warning: + return Application.Current.Resources["AlertRectangle"] as Style; + case ConnectionState.Critical: + return Application.Current.Resources["ErrorRectangle"] as Style; + case ConnectionState.Info: + return Application.Current.Resources["InfoRectangle"] as Style; + default: + throw new ArgumentOutOfRangeException(); } - - return Application.Current.Resources["HiddenRectangle"] as Style; } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return Application.Current.Resources["HiddenRectangle"] as Style; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ConnectionStateToStringConverter.cs b/Source/NETworkManager.Converters/ConnectionStateToStringConverter.cs index 60ad07e8b0..6773384c27 100644 --- a/Source/NETworkManager.Converters/ConnectionStateToStringConverter.cs +++ b/Source/NETworkManager.Converters/ConnectionStateToStringConverter.cs @@ -4,40 +4,39 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.Network; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class ConnectionStateToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class ConnectionStateToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is ConnectionState connectionState)) - return "-/-"; - - return ConnectionStateTranslator.GetInstance().Translate(connectionState); - } + if (!(value is ConnectionState connectionState)) + return "-/-"; + + return ConnectionStateTranslator.GetInstance().Translate(connectionState); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } \ No newline at end of file diff --git a/Source/NETworkManager.Converters/DNSServerConnectionInfoProfileToString.cs b/Source/NETworkManager.Converters/DNSServerConnectionInfoProfileToString.cs index 77a81448f3..01ccb173c2 100644 --- a/Source/NETworkManager.Converters/DNSServerConnectionInfoProfileToString.cs +++ b/Source/NETworkManager.Converters/DNSServerConnectionInfoProfileToString.cs @@ -4,21 +4,20 @@ using NETworkManager.Models.Network; using NETworkManager.Localization.Resources; -namespace NETworkManager.Converters -{ - public sealed class DNSServerConnectionInfoProfileToString : IValueConverter - { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not DNSServerConnectionInfoProfile dnsServerInfo) - return "-/-"; +namespace NETworkManager.Converters; - return dnsServerInfo.UseWindowsDNSServer ? $"[{Strings.WindowsDNSSettings}]" : dnsServerInfo.Name; - } +public sealed class DNSServerConnectionInfoProfileToString : IValueConverter +{ + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is not DNSServerConnectionInfoProfile dnsServerInfo) + return "-/-"; - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return dnsServerInfo.UseWindowsDNSServer ? $"[{Strings.WindowsDNSSettings}]" : dnsServerInfo.Name; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/DiscoveryProtocolToStringConverter.cs b/Source/NETworkManager.Converters/DiscoveryProtocolToStringConverter.cs index af943e3dd2..3f5e6baf44 100644 --- a/Source/NETworkManager.Converters/DiscoveryProtocolToStringConverter.cs +++ b/Source/NETworkManager.Converters/DiscoveryProtocolToStringConverter.cs @@ -4,41 +4,40 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.Network; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class DiscoveryProtocolToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class DiscoveryProtocolToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is DiscoveryProtocol.Protocol discoveryProtocol)) - return "-/-"; + if (!(value is DiscoveryProtocol.Protocol discoveryProtocol)) + return "-/-"; - return DiscoveryProtocolTranslator.GetInstance().Translate(discoveryProtocol); - } + return DiscoveryProtocolTranslator.GetInstance().Translate(discoveryProtocol); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/GroupViewNameToTranslatedStringConverter.cs b/Source/NETworkManager.Converters/GroupViewNameToTranslatedStringConverter.cs index 56c63df009..f26252a30f 100644 --- a/Source/NETworkManager.Converters/GroupViewNameToTranslatedStringConverter.cs +++ b/Source/NETworkManager.Converters/GroupViewNameToTranslatedStringConverter.cs @@ -4,40 +4,39 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class GroupViewNameToTranslatedStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class GroupViewNameToTranslatedStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not GroupViewName name) - return "-/-"; + if (value is not GroupViewName name) + return "-/-"; - return GroupViewNameTranslator.GetInstance().Translate(name); - } - - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return GroupViewNameTranslator.GetInstance().Translate(name); + } + + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IPAddressArrayToStringConverter.cs b/Source/NETworkManager.Converters/IPAddressArrayToStringConverter.cs index a6ebc532da..174d41937c 100644 --- a/Source/NETworkManager.Converters/IPAddressArrayToStringConverter.cs +++ b/Source/NETworkManager.Converters/IPAddressArrayToStringConverter.cs @@ -5,34 +5,33 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IPAddressArrayToStringConverter : IValueConverter { - public sealed class IPAddressArrayToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) - return "-/-"; - - if (!(value is IPAddress[] ipAddresses)) - return "-/-"; + if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) + return "-/-"; - var result = string.Empty; + if (!(value is IPAddress[] ipAddresses)) + return "-/-"; - foreach (var ipAddr in ipAddresses) - { - if (!string.IsNullOrEmpty(result)) - result += Environment.NewLine; + var result = string.Empty; - result += ipAddr.ToString(); - } + foreach (var ipAddr in ipAddresses) + { + if (!string.IsNullOrEmpty(result)) + result += Environment.NewLine; - return result; + result += ipAddr.ToString(); } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return result; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IPAddressSubnetmaskTupleArrayToStringConverter.cs b/Source/NETworkManager.Converters/IPAddressSubnetmaskTupleArrayToStringConverter.cs index 22aca67e78..bef60b6ef9 100644 --- a/Source/NETworkManager.Converters/IPAddressSubnetmaskTupleArrayToStringConverter.cs +++ b/Source/NETworkManager.Converters/IPAddressSubnetmaskTupleArrayToStringConverter.cs @@ -6,34 +6,33 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IPAddressSubnetmaskTupleArrayToStringConverter : IValueConverter { - public sealed class IPAddressSubnetmaskTupleArrayToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) - return "-/-"; - - if (!(value is Tuple[] ipAddresses)) - return "-/-"; + if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) + return "-/-"; - var result = string.Empty; + if (!(value is Tuple[] ipAddresses)) + return "-/-"; - foreach (var ipAddr in ipAddresses) - { - if (!string.IsNullOrEmpty(result)) - result += Environment.NewLine; + var result = string.Empty; - result += ipAddr.Item1.ToString() + "/" + Subnetmask.ConvertSubnetmaskToCidr(ipAddr.Item2); - } + foreach (var ipAddr in ipAddresses) + { + if (!string.IsNullOrEmpty(result)) + result += Environment.NewLine; - return result; + result += ipAddr.Item1.ToString() + "/" + Subnetmask.ConvertSubnetmaskToCidr(ipAddr.Item2); } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return result; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IPAddressToStringConverter.cs b/Source/NETworkManager.Converters/IPAddressToStringConverter.cs index 595accd4f0..019a994dc2 100644 --- a/Source/NETworkManager.Converters/IPAddressToStringConverter.cs +++ b/Source/NETworkManager.Converters/IPAddressToStringConverter.cs @@ -3,18 +3,17 @@ using System.Net; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IPAddressToStringConverter : IValueConverter { - public sealed class IPAddressToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return !(value is IPAddress) ? "-/-" : ((IPAddress)value).ToString(); - } + return !(value is IPAddress) ? "-/-" : ((IPAddress)value).ToString(); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IPStatusToStringConverter.cs b/Source/NETworkManager.Converters/IPStatusToStringConverter.cs index edb77fec78..ec56df11af 100644 --- a/Source/NETworkManager.Converters/IPStatusToStringConverter.cs +++ b/Source/NETworkManager.Converters/IPStatusToStringConverter.cs @@ -4,40 +4,39 @@ using System.Net.NetworkInformation; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class IPStatusToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class IPStatusToStringConverter : IValueConverter - { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is IPStatus ipStatus)) - return "-/-"; - - return IPStatusTranslator.GetInstance().Translate(ipStatus); - } + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (!(value is IPStatus ipStatus)) + return "-/-"; + + return IPStatusTranslator.GetInstance().Translate(ipStatus); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IntGreater1ToBooleanConverter.cs b/Source/NETworkManager.Converters/IntGreater1ToBooleanConverter.cs index 6eaf69c9fd..ee1bc4f2ed 100644 --- a/Source/NETworkManager.Converters/IntGreater1ToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/IntGreater1ToBooleanConverter.cs @@ -3,20 +3,19 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IntGreater1ToBooleanConverter : IValueConverter { - public sealed class IntGreater1ToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - var x = value is int count && count > 1; - - return x; - } + var x = value is int count && count > 1; + + return x; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IntToStringConverter.cs b/Source/NETworkManager.Converters/IntToStringConverter.cs index 0fce872f0f..0153dce56b 100644 --- a/Source/NETworkManager.Converters/IntToStringConverter.cs +++ b/Source/NETworkManager.Converters/IntToStringConverter.cs @@ -2,23 +2,22 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IntToStringConverter : IValueConverter { - public sealed class IntToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value == null) - return "-/-"; + if (value == null) + return "-/-"; - long.TryParse(value.ToString(), out var intValue); + long.TryParse(value.ToString(), out var intValue); - return intValue == 0 ? "-/-" : intValue.ToString(); - } + return intValue == 0 ? "-/-" : intValue.ToString(); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IntZeroReverseToVisibilityCollapsedConverter.cs b/Source/NETworkManager.Converters/IntZeroReverseToVisibilityCollapsedConverter.cs index 418df6ddd0..c0256329fb 100644 --- a/Source/NETworkManager.Converters/IntZeroReverseToVisibilityCollapsedConverter.cs +++ b/Source/NETworkManager.Converters/IntZeroReverseToVisibilityCollapsedConverter.cs @@ -3,18 +3,17 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IntZeroReverseToVisibilityCollapsedConverter : IValueConverter { - public sealed class IntZeroReverseToVisibilityCollapsedConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is int count && count > 0 ? Visibility.Visible : Visibility.Collapsed; - } + return value is int count && count > 0 ? Visibility.Visible : Visibility.Collapsed; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IntZeroToVisibilityCollapsedConverter.cs b/Source/NETworkManager.Converters/IntZeroToVisibilityCollapsedConverter.cs index 116329f2bf..a2d6baef99 100644 --- a/Source/NETworkManager.Converters/IntZeroToVisibilityCollapsedConverter.cs +++ b/Source/NETworkManager.Converters/IntZeroToVisibilityCollapsedConverter.cs @@ -3,18 +3,17 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IntZeroToVisibilityCollapsedConverter : IValueConverter { - public sealed class IntZeroToVisibilityCollapsedConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value is int count && count == 0 ? Visibility.Visible : Visibility.Collapsed; - } + return value is int count && count == 0 ? Visibility.Visible : Visibility.Collapsed; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IsDynamicProfileToBooleanConverter.cs b/Source/NETworkManager.Converters/IsDynamicProfileToBooleanConverter.cs index 71088f4b25..487376649e 100644 --- a/Source/NETworkManager.Converters/IsDynamicProfileToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/IsDynamicProfileToBooleanConverter.cs @@ -2,21 +2,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IsDynamicProfileToBooleanConverter : IValueConverter { - public sealed class IsDynamicProfileToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value != null && value is string name) - return name.StartsWith("~"); + if (value != null && value is string name) + return name.StartsWith("~"); - return false; - } + return false; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IsProfilesLocationToBooleanConverter.cs b/Source/NETworkManager.Converters/IsProfilesLocationToBooleanConverter.cs index a9583786d7..ce3cb0b3f4 100644 --- a/Source/NETworkManager.Converters/IsProfilesLocationToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/IsProfilesLocationToBooleanConverter.cs @@ -3,18 +3,17 @@ using System.Windows.Data; using NETworkManager.Profiles; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IsProfilesLocationToBooleanConverter : IValueConverter { - public sealed class IsProfilesLocationToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value as string == ProfileManager.GetProfilesFolderLocation(); - } + return value as string == ProfileManager.GetProfilesFolderLocation(); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/IsSettingsLocationToBooleanConverter.cs b/Source/NETworkManager.Converters/IsSettingsLocationToBooleanConverter.cs index 015ec0852f..3ab454a9bf 100644 --- a/Source/NETworkManager.Converters/IsSettingsLocationToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/IsSettingsLocationToBooleanConverter.cs @@ -3,18 +3,17 @@ using System.Windows.Data; using NETworkManager.Settings; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class IsSettingsLocationToBooleanConverter : IValueConverter { - public sealed class IsSettingsLocationToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value as string == SettingsManager.GetSettingsFolderLocation(); - } + return value as string == SettingsManager.GetSettingsFolderLocation(); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ListServerConnectionInfoToStringConverter.cs b/Source/NETworkManager.Converters/ListServerConnectionInfoToStringConverter.cs index 227f3dd362..4f8ef03b5a 100644 --- a/Source/NETworkManager.Converters/ListServerConnectionInfoToStringConverter.cs +++ b/Source/NETworkManager.Converters/ListServerConnectionInfoToStringConverter.cs @@ -5,31 +5,30 @@ using System.Windows.Data; using System.Text; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class ListServerConnectionInfoToStringConverter : IValueConverter { - public sealed class ListServerConnectionInfoToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value == null) - return string.Empty; + if (value == null) + return string.Empty; - StringBuilder stringBuilder = new(); + StringBuilder stringBuilder = new(); + + foreach (var server in (List)value) + { + if (stringBuilder.Length > 0) + stringBuilder.Append("; "); - foreach (var server in (List)value) - { - if (stringBuilder.Length > 0) - stringBuilder.Append("; "); - - stringBuilder.Append(server.ToString()); - } - - return stringBuilder.ToString(); + stringBuilder.Append(server.ToString()); } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return stringBuilder.ToString(); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ListToStringConverter.cs b/Source/NETworkManager.Converters/ListToStringConverter.cs index 6e56324658..0ac4ad69de 100644 --- a/Source/NETworkManager.Converters/ListToStringConverter.cs +++ b/Source/NETworkManager.Converters/ListToStringConverter.cs @@ -3,18 +3,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class ListToStringConverter : IValueConverter { - public sealed class ListToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value == null ? string.Empty : string.Join("; ", (List)value); - } + return value == null ? string.Empty : string.Join("; ", (List)value); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/LvlChartsBandwidthValueConverter.cs b/Source/NETworkManager.Converters/LvlChartsBandwidthValueConverter.cs index 7868dd6cc8..e6c2f99182 100644 --- a/Source/NETworkManager.Converters/LvlChartsBandwidthValueConverter.cs +++ b/Source/NETworkManager.Converters/LvlChartsBandwidthValueConverter.cs @@ -3,30 +3,29 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class LvlChartsBandwidthValueConverter : IValueConverter { - public sealed class LvlChartsBandwidthValueConverter : IValueConverter + + /// + /// + /// + /// ChartPoint.Instance (object) + /// + /// + /// + /// + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - - /// - /// - /// - /// ChartPoint.Instance (object) - /// - /// - /// - /// - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value != null && value is LvlChartsDefaultInfo info) - return $"{FileSizeConverter.GetBytesReadable((long)info.Value * 8)}it/s"; + if (value != null && value is LvlChartsDefaultInfo info) + return $"{FileSizeConverter.GetBytesReadable((long)info.Value * 8)}it/s"; - return "-/-"; - } + return "-/-"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/LvlChartsHeaderConverter.cs b/Source/NETworkManager.Converters/LvlChartsHeaderConverter.cs index a69744ac94..939842f0b2 100644 --- a/Source/NETworkManager.Converters/LvlChartsHeaderConverter.cs +++ b/Source/NETworkManager.Converters/LvlChartsHeaderConverter.cs @@ -3,28 +3,27 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class LvlChartsHeaderConverter : IValueConverter { - public sealed class LvlChartsHeaderConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + if (value is TooltipData info) { - if (value is TooltipData info) - { - double index = info.SharedValue ?? -1; - - if (index == -1) - return "-/-"; + double index = info.SharedValue ?? -1; - return info.XFormatter.Invoke(index) as string; - } + if (index == -1) + return "-/-"; - return "-/-"; + return info.XFormatter.Invoke(index) as string; } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return "-/-"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/LvlChartsPingTimeValueConverter.cs b/Source/NETworkManager.Converters/LvlChartsPingTimeValueConverter.cs index 07388e676a..446a1ab106 100644 --- a/Source/NETworkManager.Converters/LvlChartsPingTimeValueConverter.cs +++ b/Source/NETworkManager.Converters/LvlChartsPingTimeValueConverter.cs @@ -3,30 +3,29 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class LvlChartsPingTimeValueConverter : IValueConverter { - public sealed class LvlChartsPingTimeValueConverter : IValueConverter + + /// + /// + /// + /// ChartPoint.Instance (object) + /// + /// + /// + /// + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - - /// - /// - /// - /// ChartPoint.Instance (object) - /// - /// - /// - /// - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value != null && value is LvlChartsDefaultInfo info) - return $"{info.Value} ms"; + if (value != null && value is LvlChartsDefaultInfo info) + return $"{info.Value} ms"; - return "-/-"; - } + return "-/-"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/MACAddressToVendorConverter.cs b/Source/NETworkManager.Converters/MACAddressToVendorConverter.cs index 5018dbc1a7..2cae6d989e 100644 --- a/Source/NETworkManager.Converters/MACAddressToVendorConverter.cs +++ b/Source/NETworkManager.Converters/MACAddressToVendorConverter.cs @@ -4,21 +4,20 @@ using System.Linq; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class MACAddressToVendorConverter : IValueConverter { - public sealed class MACAddressToVendorConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not string macAddress) - return "-/-"; + if (value is not string macAddress) + return "-/-"; - return OUILookup.Lookup(macAddress).FirstOrDefault()?.Vendor; - } + return OUILookup.Lookup(macAddress).FirstOrDefault()?.Vendor; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/NullOrEmptyToBoolConverter.cs b/Source/NETworkManager.Converters/NullOrEmptyToBoolConverter.cs index e218942724..bdab4cc969 100644 --- a/Source/NETworkManager.Converters/NullOrEmptyToBoolConverter.cs +++ b/Source/NETworkManager.Converters/NullOrEmptyToBoolConverter.cs @@ -2,18 +2,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class NullOrEmptyToBoolConverter : IValueConverter { - public sealed class NullOrEmptyToBoolConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return string.IsNullOrEmpty(value as string); - } + return string.IsNullOrEmpty(value as string); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/NullOrEmptyToStringConverter.cs b/Source/NETworkManager.Converters/NullOrEmptyToStringConverter.cs index 7a41837103..eb24bd7aec 100644 --- a/Source/NETworkManager.Converters/NullOrEmptyToStringConverter.cs +++ b/Source/NETworkManager.Converters/NullOrEmptyToStringConverter.cs @@ -2,20 +2,19 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class NullOrEmptyToStringConverter : IValueConverter { - public sealed class NullOrEmptyToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - var str = value as string; + var str = value as string; - return string.IsNullOrEmpty(str) ? "-/-" : str; - } + return string.IsNullOrEmpty(str) ? "-/-" : str; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/NullToFalseConverter.cs b/Source/NETworkManager.Converters/NullToFalseConverter.cs index 92d2ec2644..9de921c463 100644 --- a/Source/NETworkManager.Converters/NullToFalseConverter.cs +++ b/Source/NETworkManager.Converters/NullToFalseConverter.cs @@ -2,18 +2,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class NullToFalseConverter : IValueConverter { - public sealed class NullToFalseConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null; - } + return value != null; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/NullableDateTimeToStringConverter.cs b/Source/NETworkManager.Converters/NullableDateTimeToStringConverter.cs index 53de1907ee..a5f63831a3 100644 --- a/Source/NETworkManager.Converters/NullableDateTimeToStringConverter.cs +++ b/Source/NETworkManager.Converters/NullableDateTimeToStringConverter.cs @@ -2,21 +2,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class NullableDateTimeToStringConverter : IValueConverter { - public sealed class NullableDateTimeToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is DateTime time) - return time; + if (value is DateTime time) + return time; - return "-/-"; - } + return "-/-"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/OperationalStatusToStringConverter.cs b/Source/NETworkManager.Converters/OperationalStatusToStringConverter.cs index 10dbbe50d5..333ba4ec65 100644 --- a/Source/NETworkManager.Converters/OperationalStatusToStringConverter.cs +++ b/Source/NETworkManager.Converters/OperationalStatusToStringConverter.cs @@ -3,21 +3,20 @@ using System.Net.NetworkInformation; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class OperationalStatusToStringConverter : IValueConverter { - public sealed class OperationalStatusToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is OperationalStatus operationalStatus)) - return "-/-"; - - return operationalStatus.ToString(); - } + if (!(value is OperationalStatus operationalStatus)) + return "-/-"; + + return operationalStatus.ToString(); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/PercentConverter.cs b/Source/NETworkManager.Converters/PercentConverter.cs index d05425c756..3dada7e353 100644 --- a/Source/NETworkManager.Converters/PercentConverter.cs +++ b/Source/NETworkManager.Converters/PercentConverter.cs @@ -2,21 +2,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class PercentConverter : IMultiValueConverter { - public sealed class PercentConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - if ((int)values[0] == 0) - return 0; + if ((int)values[0] == 0) + return 0; - return Math.Round(((float)((int)values[1]) / (int)values[0]) * 100, 2); - } + return Math.Round(((float)((int)values[1]) / (int)values[0]) * 100, 2); + } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/PhysicalAddressToStringConverter.cs b/Source/NETworkManager.Converters/PhysicalAddressToStringConverter.cs index cdfe309015..cb041f0e2d 100644 --- a/Source/NETworkManager.Converters/PhysicalAddressToStringConverter.cs +++ b/Source/NETworkManager.Converters/PhysicalAddressToStringConverter.cs @@ -4,23 +4,22 @@ using NETworkManager.Utilities; using System.Net.NetworkInformation; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class PhysicalAddressToStringConverter : IValueConverter { - public sealed class PhysicalAddressToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is PhysicalAddress physicalAddress)) - return string.Empty; + if (!(value is PhysicalAddress physicalAddress)) + return string.Empty; - string macAddress = physicalAddress.ToString(); + string macAddress = physicalAddress.ToString(); - return string.IsNullOrEmpty(macAddress) ? string.Empty : MACAddressHelper.GetDefaultFormat(macAddress); - } + return string.IsNullOrEmpty(macAddress) ? string.Empty : MACAddressHelper.GetDefaultFormat(macAddress); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/PingStatusToBooleanConverter.cs b/Source/NETworkManager.Converters/PingStatusToBooleanConverter.cs index f48a8caa04..e11a0d8dd5 100644 --- a/Source/NETworkManager.Converters/PingStatusToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/PingStatusToBooleanConverter.cs @@ -3,18 +3,17 @@ using System.Net.NetworkInformation; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class PingStatusToBooleanConverter : IValueConverter { - public sealed class PingStatusToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null && (IPStatus) value == IPStatus.Success; - } + return value != null && (IPStatus) value == IPStatus.Success; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/PingTimeToStringConverter.cs b/Source/NETworkManager.Converters/PingTimeToStringConverter.cs index 1d91a48295..f3f42029e7 100644 --- a/Source/NETworkManager.Converters/PingTimeToStringConverter.cs +++ b/Source/NETworkManager.Converters/PingTimeToStringConverter.cs @@ -3,18 +3,17 @@ using System.Net.NetworkInformation; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class PingTimeToStringConverter : IMultiValueConverter { - public sealed class PingTimeToStringConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - return Models.Network.Ping.TimeToString((IPStatus)values[0], (long)values[1]); - } + return Models.Network.Ping.TimeToString((IPStatus)values[0], (long)values[1]); + } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/PortStateToStringConverter.cs b/Source/NETworkManager.Converters/PortStateToStringConverter.cs index c618204240..4b15730dc9 100644 --- a/Source/NETworkManager.Converters/PortStateToStringConverter.cs +++ b/Source/NETworkManager.Converters/PortStateToStringConverter.cs @@ -4,40 +4,39 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.Network; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class PortStateToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class PortStateToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not PortState portState) - return "-/-"; + if (value is not PortState portState) + return "-/-"; - return PortStateTranslator.GetInstance().Translate(portState); - } - - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return PortStateTranslator.GetInstance().Translate(portState); + } + + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ProfileViewNameToTranslatedStringConverter.cs b/Source/NETworkManager.Converters/ProfileViewNameToTranslatedStringConverter.cs index ffb398b9c9..097bb10853 100644 --- a/Source/NETworkManager.Converters/ProfileViewNameToTranslatedStringConverter.cs +++ b/Source/NETworkManager.Converters/ProfileViewNameToTranslatedStringConverter.cs @@ -4,40 +4,39 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class ProfileViewNameToTranslatedStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class ProfileViewNameToTranslatedStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is ProfileViewName name)) - return "-/-"; + if (!(value is ProfileViewName name)) + return "-/-"; - return ProfileViewNameTranslator.GetInstance().Translate(name); - } - - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return ProfileViewNameTranslator.GetInstance().Translate(name); + } + + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/PuTTYLogModeToStringConverter.cs b/Source/NETworkManager.Converters/PuTTYLogModeToStringConverter.cs index 46265abf9a..d3c27b27c6 100644 --- a/Source/NETworkManager.Converters/PuTTYLogModeToStringConverter.cs +++ b/Source/NETworkManager.Converters/PuTTYLogModeToStringConverter.cs @@ -4,40 +4,39 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.PuTTY; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class PuTTYLogModeToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class PuTTYLogModeToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is LogMode audioRedirectionMode)) - return "-/-"; + if (!(value is LogMode audioRedirectionMode)) + return "-/-"; - return PuTTYLogModeTranslator.GetInstance().Translate(audioRedirectionMode); - } + return PuTTYLogModeTranslator.GetInstance().Translate(audioRedirectionMode); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/RemoteDesktopAudioCaptureRedirectionModeToStringConverter.cs b/Source/NETworkManager.Converters/RemoteDesktopAudioCaptureRedirectionModeToStringConverter.cs index d1f5af41a8..d21c4ea2fa 100644 --- a/Source/NETworkManager.Converters/RemoteDesktopAudioCaptureRedirectionModeToStringConverter.cs +++ b/Source/NETworkManager.Converters/RemoteDesktopAudioCaptureRedirectionModeToStringConverter.cs @@ -4,40 +4,39 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class RemoteDesktopAudioCaptureRedirectionModeToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class RemoteDesktopAudioCaptureRedirectionModeToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is AudioCaptureRedirectionMode audioCaptureRedirectionMode)) - return "-/-"; + if (!(value is AudioCaptureRedirectionMode audioCaptureRedirectionMode)) + return "-/-"; - return RemoteDesktopAudioCaptureRedirectionModeTranslator.GetInstance().Translate(audioCaptureRedirectionMode); - } + return RemoteDesktopAudioCaptureRedirectionModeTranslator.GetInstance().Translate(audioCaptureRedirectionMode); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/RemoteDesktopAudioRedirectionModeToStringConverter.cs b/Source/NETworkManager.Converters/RemoteDesktopAudioRedirectionModeToStringConverter.cs index e250376e9a..a9f5c4e55a 100644 --- a/Source/NETworkManager.Converters/RemoteDesktopAudioRedirectionModeToStringConverter.cs +++ b/Source/NETworkManager.Converters/RemoteDesktopAudioRedirectionModeToStringConverter.cs @@ -4,40 +4,39 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.RemoteDesktop; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class RemoteDesktopAudioRedirectionModeToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class RemoteDesktopAudioRedirectionModeToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is AudioRedirectionMode audioRedirectionMode)) - return "-/-"; + if (!(value is AudioRedirectionMode audioRedirectionMode)) + return "-/-"; - return RemoteDesktopAudioRedirectionModeTranslator.GetInstance().Translate(audioRedirectionMode); - } + return RemoteDesktopAudioRedirectionModeTranslator.GetInstance().Translate(audioRedirectionMode); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/RemoteDesktopKeyboardHookModeToStringConverter.cs b/Source/NETworkManager.Converters/RemoteDesktopKeyboardHookModeToStringConverter.cs index 17cbaeaa56..5e90f6ffed 100644 --- a/Source/NETworkManager.Converters/RemoteDesktopKeyboardHookModeToStringConverter.cs +++ b/Source/NETworkManager.Converters/RemoteDesktopKeyboardHookModeToStringConverter.cs @@ -4,40 +4,39 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.RemoteDesktop; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class RemoteDesktopKeyboardHookModeToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class RemoteDesktopKeyboardHookModeToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is KeyboardHookMode keyboardHookMode)) - return "-/-"; + if (!(value is KeyboardHookMode keyboardHookMode)) + return "-/-"; - return RemoteDesktopKeyboardHookModeTranslator.GetInstance().Translate(keyboardHookMode); - } + return RemoteDesktopKeyboardHookModeTranslator.GetInstance().Translate(keyboardHookMode); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/RemoteDesktopNetworkConnectionTypeToStringConverter.cs b/Source/NETworkManager.Converters/RemoteDesktopNetworkConnectionTypeToStringConverter.cs index 0b52566923..35d404bbf4 100644 --- a/Source/NETworkManager.Converters/RemoteDesktopNetworkConnectionTypeToStringConverter.cs +++ b/Source/NETworkManager.Converters/RemoteDesktopNetworkConnectionTypeToStringConverter.cs @@ -4,40 +4,39 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.RemoteDesktop; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class RemoteDesktopNetworkConnectionTypeToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class RemoteDesktopNetworkConnectionTypeToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is NetworkConnectionType networkConnectionType)) - return "-/-"; + if (!(value is NetworkConnectionType networkConnectionType)) + return "-/-"; - return RemoteDesktopNetworkConnectionTypeTranslator.GetInstance().Translate(networkConnectionType); - } + return RemoteDesktopNetworkConnectionTypeTranslator.GetInstance().Translate(networkConnectionType); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/SelectedItemsToBooleanConverter.cs b/Source/NETworkManager.Converters/SelectedItemsToBooleanConverter.cs index 049309c4c6..a329922daf 100644 --- a/Source/NETworkManager.Converters/SelectedItemsToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/SelectedItemsToBooleanConverter.cs @@ -3,18 +3,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class SelectedItemsToBooleanConverter : IValueConverter { - public sealed class SelectedItemsToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value != null && ((IList) value).Count > 0; - } + return value != null && ((IList) value).Count > 0; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/SettingsViewGroupToTranslatedStringConverter.cs b/Source/NETworkManager.Converters/SettingsViewGroupToTranslatedStringConverter.cs index 5c982c67f5..ada5256514 100644 --- a/Source/NETworkManager.Converters/SettingsViewGroupToTranslatedStringConverter.cs +++ b/Source/NETworkManager.Converters/SettingsViewGroupToTranslatedStringConverter.cs @@ -4,40 +4,39 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class SettingsViewGroupToTranslatedStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class SettingsViewGroupToTranslatedStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is SettingsViewGroup group)) - return "-/-"; + if (!(value is SettingsViewGroup group)) + return "-/-"; - return SettingsViewGroupTranslator.GetInstance().Translate(group); - } - - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return SettingsViewGroupTranslator.GetInstance().Translate(group); + } + + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/SettingsViewNameToTranslatedStringConverter.cs b/Source/NETworkManager.Converters/SettingsViewNameToTranslatedStringConverter.cs index 3f7f699194..02f2dea3de 100644 --- a/Source/NETworkManager.Converters/SettingsViewNameToTranslatedStringConverter.cs +++ b/Source/NETworkManager.Converters/SettingsViewNameToTranslatedStringConverter.cs @@ -4,40 +4,39 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class SettingsViewNameToTranslatedStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class SettingsViewNameToTranslatedStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is SettingsViewName name)) - return "-/-"; + if (!(value is SettingsViewName name)) + return "-/-"; - return SettingsViewNameTranslator.GetInstance().Translate(name); - } - - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return SettingsViewNameTranslator.GetInstance().Translate(name); + } + + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/StringIsNotNullOrEmptyOrIPv4AddressToBooleanConverter.cs b/Source/NETworkManager.Converters/StringIsNotNullOrEmptyOrIPv4AddressToBooleanConverter.cs index 23a3f66834..c5ce0f50c6 100644 --- a/Source/NETworkManager.Converters/StringIsNotNullOrEmptyOrIPv4AddressToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/StringIsNotNullOrEmptyOrIPv4AddressToBooleanConverter.cs @@ -4,18 +4,17 @@ using System.Windows.Data; using NETworkManager.Utilities; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class StringIsNotNullOrEmptyOrIPv4AddressToBooleanConverter : IValueConverter { - public sealed class StringIsNotNullOrEmptyOrIPv4AddressToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return !string.IsNullOrEmpty(value as string) && !Regex.IsMatch((string) value, RegexHelper.IPv4AddressRegex); - } + return !string.IsNullOrEmpty(value as string) && !Regex.IsMatch((string) value, RegexHelper.IPv4AddressRegex); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToBooleanConverter.cs b/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToBooleanConverter.cs index 64eb1b74b4..dbb4e488fa 100644 --- a/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToBooleanConverter.cs +++ b/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToBooleanConverter.cs @@ -2,18 +2,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class StringIsNotNullOrEmptyToBooleanConverter : IValueConverter { - public sealed class StringIsNotNullOrEmptyToBooleanConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return !string.IsNullOrEmpty(value as string); - } + return !string.IsNullOrEmpty(value as string); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToVisibilityCollapsedConverter.cs b/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToVisibilityCollapsedConverter.cs index 751b07fa55..5b1cf96c9a 100644 --- a/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToVisibilityCollapsedConverter.cs +++ b/Source/NETworkManager.Converters/StringIsNotNullOrEmptyToVisibilityCollapsedConverter.cs @@ -3,18 +3,17 @@ using System.Windows; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class StringIsNotNullOrEmptyToVisibilityCollapsedConverter : IValueConverter { - public sealed class StringIsNotNullOrEmptyToVisibilityCollapsedConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return string.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible; - } + return string.IsNullOrEmpty(value as string) ? Visibility.Collapsed : Visibility.Visible; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/TcpStateToStringConverter.cs b/Source/NETworkManager.Converters/TcpStateToStringConverter.cs index 55a715211a..7d74f23ded 100644 --- a/Source/NETworkManager.Converters/TcpStateToStringConverter.cs +++ b/Source/NETworkManager.Converters/TcpStateToStringConverter.cs @@ -4,41 +4,40 @@ using System.Windows.Data; using NETworkManager.Localization.Translators; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class TcpStateToStringConverter : IValueConverter { + /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class TcpStateToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (!(value is TcpState tcpState)) + return "-/-"; - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is TcpState tcpState)) - return "-/-"; - - return TcpStateTranslator.GetInstance().Translate(tcpState); - } + return TcpStateTranslator.GetInstance().Translate(tcpState); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ThemeToStringConverter.cs b/Source/NETworkManager.Converters/ThemeToStringConverter.cs index 0173a180fa..06aa635d60 100644 --- a/Source/NETworkManager.Converters/ThemeToStringConverter.cs +++ b/Source/NETworkManager.Converters/ThemeToStringConverter.cs @@ -4,41 +4,40 @@ using NETworkManager.Localization.Translators; using NETworkManager.Models.Appearance; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class ThemeToStringConverter : IValueConverter { + /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class ThemeToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (!(value is string theme)) + return "-/-"; - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is string theme)) - return "-/-"; - - return ThemeTranslator.GetInstance().Translate(theme); - } + return ThemeTranslator.GetInstance().Translate(theme); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/TimeSpanToMillisecondConverter.cs b/Source/NETworkManager.Converters/TimeSpanToMillisecondConverter.cs index e85a9eb3a9..be1fdd20b3 100644 --- a/Source/NETworkManager.Converters/TimeSpanToMillisecondConverter.cs +++ b/Source/NETworkManager.Converters/TimeSpanToMillisecondConverter.cs @@ -2,22 +2,21 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters -{ - public sealed class TimeSpanToMillisecondConverter : IValueConverter - { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not TimeSpan timeSpan) - return "-/-"; +namespace NETworkManager.Converters; +public sealed class TimeSpanToMillisecondConverter : IValueConverter +{ + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is not TimeSpan timeSpan) + return "-/-"; - return $"{timeSpan.TotalMilliseconds} ms"; - } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + return $"{timeSpan.TotalMilliseconds} ms"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/TimeSpanToStringConverter.cs b/Source/NETworkManager.Converters/TimeSpanToStringConverter.cs index 58e0f17963..158ab17c74 100644 --- a/Source/NETworkManager.Converters/TimeSpanToStringConverter.cs +++ b/Source/NETworkManager.Converters/TimeSpanToStringConverter.cs @@ -2,21 +2,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class TimeSpanToStringConverter : IValueConverter { - public sealed class TimeSpanToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not TimeSpan timeSpan) - return "-/-"; + if (value is not TimeSpan timeSpan) + return "-/-"; - return $"{Math.Floor(timeSpan.TotalDays)}d {timeSpan.Hours}h {timeSpan.Minutes}m {timeSpan.Seconds}s"; - } + return $"{Math.Floor(timeSpan.TotalDays)}d {timeSpan.Hours}h {timeSpan.Minutes}m {timeSpan.Seconds}s"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/TimeUnitToStringConverter.cs b/Source/NETworkManager.Converters/TimeUnitToStringConverter.cs index 80d404d97f..7595de749b 100644 --- a/Source/NETworkManager.Converters/TimeUnitToStringConverter.cs +++ b/Source/NETworkManager.Converters/TimeUnitToStringConverter.cs @@ -4,40 +4,39 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +/// +/// Convert to translated or wise versa. +/// +public sealed class TimeUnitToStringConverter : IValueConverter { /// - /// Convert to translated or wise versa. + /// Convert to translated . /// - public sealed class TimeUnitToStringConverter : IValueConverter + /// Object from type . + /// + /// + /// + /// Translated . + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /// - /// Convert to translated . - /// - /// Object from type . - /// - /// - /// - /// Translated . - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is TimeUnit timeUnit)) - return "-/-" ; + if (!(value is TimeUnit timeUnit)) + return "-/-" ; - return TimeUnitTranslator.GetInstance().Translate(timeUnit); - } + return TimeUnitTranslator.GetInstance().Translate(timeUnit); + } - /// - /// !!! Method not implemented !!! - /// - /// - /// - /// - /// - /// - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + /// + /// !!! Method not implemented !!! + /// + /// + /// + /// + /// + /// + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/TimestampToStringConverter.cs b/Source/NETworkManager.Converters/TimestampToStringConverter.cs index ff98b674ab..540261a68c 100644 --- a/Source/NETworkManager.Converters/TimestampToStringConverter.cs +++ b/Source/NETworkManager.Converters/TimestampToStringConverter.cs @@ -2,18 +2,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class TimestampToStringConverter : IValueConverter { - public sealed class TimestampToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return value == null ? string.Empty : ((DateTime)value).ToLongTimeString(); - } + return value == null ? string.Empty : ((DateTime)value).ToLongTimeString(); + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ValidateNetworkInterfaceConfigConverter.cs b/Source/NETworkManager.Converters/ValidateNetworkInterfaceConfigConverter.cs index d3fb884a98..5e45bb3e8e 100644 --- a/Source/NETworkManager.Converters/ValidateNetworkInterfaceConfigConverter.cs +++ b/Source/NETworkManager.Converters/ValidateNetworkInterfaceConfigConverter.cs @@ -2,18 +2,17 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class ValidateNetworkInterfaceConfigConverter : IMultiValueConverter { - public sealed class ValidateNetworkInterfaceConfigConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - return ((bool)values[0] || (bool)values[1] && !(bool)values[2] && !(bool)values[3] && !(bool)values[4]) && ((bool)values[5] || (bool)values[6] && !(bool)values[7] && !(bool)values[8]); - } + return ((bool)values[0] || (bool)values[1] && !(bool)values[2] && !(bool)values[3] && !(bool)values[4]) && ((bool)values[5] || (bool)values[6] && !(bool)values[7] && !(bool)values[8]); + } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ValidateSubnetCalculatorSubnettingConverter.cs b/Source/NETworkManager.Converters/ValidateSubnetCalculatorSubnettingConverter.cs index 32280c2b11..df5148d728 100644 --- a/Source/NETworkManager.Converters/ValidateSubnetCalculatorSubnettingConverter.cs +++ b/Source/NETworkManager.Converters/ValidateSubnetCalculatorSubnettingConverter.cs @@ -6,50 +6,49 @@ using System.Text.RegularExpressions; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class ValidateSubnetCalculatorSubnettingConverter : IMultiValueConverter { - public sealed class ValidateSubnetCalculatorSubnettingConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - // if Validation.HasError is true... - if ((bool)values[0] || (bool)values[1]) - return false; - - var subnet = (values[2] as string)?.Trim(); - var newSubnetmaskOrCidr = (values[3] as string)?.Trim(); - - // Catch null exceptions... - if (string.IsNullOrEmpty(subnet) || string.IsNullOrEmpty(newSubnetmaskOrCidr)) - return false; - - // Get the cidr to compare... - var subnetData = subnet.Split('/'); - - var ipAddress = IPAddress.Parse(subnetData[0]); - var subnetmaskOrCidr = subnetData[1]; - - var cidr = ipAddress.AddressFamily switch - { - System.Net.Sockets.AddressFamily.InterNetwork when subnetmaskOrCidr.Length < 3 => int.Parse(subnetmaskOrCidr), - System.Net.Sockets.AddressFamily.InterNetwork => Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(subnetmaskOrCidr)), - _ => int.Parse(subnetmaskOrCidr), - }; - int newCidr; - - // Support subnetmask like 255.255.255.0 - if (Regex.IsMatch(newSubnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) - newCidr = System.Convert.ToByte(Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(newSubnetmaskOrCidr))); - else - newCidr = System.Convert.ToByte(newSubnetmaskOrCidr.TrimStart('/')); - - // Compare - return newCidr > cidr; - } - - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + // if Validation.HasError is true... + if ((bool)values[0] || (bool)values[1]) + return false; + + var subnet = (values[2] as string)?.Trim(); + var newSubnetmaskOrCidr = (values[3] as string)?.Trim(); + + // Catch null exceptions... + if (string.IsNullOrEmpty(subnet) || string.IsNullOrEmpty(newSubnetmaskOrCidr)) + return false; + + // Get the cidr to compare... + var subnetData = subnet.Split('/'); + + var ipAddress = IPAddress.Parse(subnetData[0]); + var subnetmaskOrCidr = subnetData[1]; + + var cidr = ipAddress.AddressFamily switch { - throw new NotImplementedException(); - } + System.Net.Sockets.AddressFamily.InterNetwork when subnetmaskOrCidr.Length < 3 => int.Parse(subnetmaskOrCidr), + System.Net.Sockets.AddressFamily.InterNetwork => Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(subnetmaskOrCidr)), + _ => int.Parse(subnetmaskOrCidr), + }; + int newCidr; + + // Support subnetmask like 255.255.255.0 + if (Regex.IsMatch(newSubnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) + newCidr = System.Convert.ToByte(Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(newSubnetmaskOrCidr))); + else + newCidr = System.Convert.ToByte(newSubnetmaskOrCidr.TrimStart('/')); + + // Compare + return newCidr > cidr; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/ValidateSubnetCalculatorSupernettingConverter.cs b/Source/NETworkManager.Converters/ValidateSubnetCalculatorSupernettingConverter.cs index b3a5f3e4dc..b12c10891c 100644 --- a/Source/NETworkManager.Converters/ValidateSubnetCalculatorSupernettingConverter.cs +++ b/Source/NETworkManager.Converters/ValidateSubnetCalculatorSupernettingConverter.cs @@ -3,39 +3,38 @@ using System.Net; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class ValidateSubnetCalculatorSupernettingConverter : IMultiValueConverter { - public sealed class ValidateSubnetCalculatorSupernettingConverter : IMultiValueConverter + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) - { - // if Validation.HasError is true... - if ((bool)values[0] || (bool)values[1]) - return false; + // if Validation.HasError is true... + if ((bool)values[0] || (bool)values[1]) + return false; - var subnet1 = values[2] as string; - var subnet2 = values[3] as string; + var subnet1 = values[2] as string; + var subnet2 = values[3] as string; - // Catch null exceptions... - if (string.IsNullOrEmpty(subnet1) || string.IsNullOrEmpty(subnet2)) - return false; + // Catch null exceptions... + if (string.IsNullOrEmpty(subnet1) || string.IsNullOrEmpty(subnet2)) + return false; - // Compare... - var subnet1Data = subnet1.Split('/'); - var subnet2Data = subnet2.Split('/'); + // Compare... + var subnet1Data = subnet1.Split('/'); + var subnet2Data = subnet2.Split('/'); - var subnet1Ip = IPAddress.Parse(subnet1Data[0]); - var subnet2Ip = IPAddress.Parse(subnet2Data[0]); + var subnet1Ip = IPAddress.Parse(subnet1Data[0]); + var subnet2Ip = IPAddress.Parse(subnet2Data[0]); - if (subnet1Ip.AddressFamily == subnet2Ip.AddressFamily) - return subnet1Data[1] == subnet2Data[1]; + if (subnet1Ip.AddressFamily == subnet2Ip.AddressFamily) + return subnet1Data[1] == subnet2Data[1]; - return false; - } + return false; + } - public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/WiFiAuthenticationTypeToHumanReadableStringConverter.cs b/Source/NETworkManager.Converters/WiFiAuthenticationTypeToHumanReadableStringConverter.cs index b23fd0ad64..288a635203 100644 --- a/Source/NETworkManager.Converters/WiFiAuthenticationTypeToHumanReadableStringConverter.cs +++ b/Source/NETworkManager.Converters/WiFiAuthenticationTypeToHumanReadableStringConverter.cs @@ -4,22 +4,21 @@ using System.Windows.Data; using Windows.Networking.Connectivity; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class WiFiAuthenticationTypeToHumanReadableStringConverter : IValueConverter { - public sealed class WiFiAuthenticationTypeToHumanReadableStringConverter : IValueConverter + /* Translate the name of the accent */ + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - /* Translate the name of the accent */ - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not NetworkAuthenticationType type) - return "-/-"; - - return $"{WiFi.GetHumanReadableNetworkAuthenticationType(type)}"; - } + if (value is not NetworkAuthenticationType type) + return "-/-"; + + return $"{WiFi.GetHumanReadableNetworkAuthenticationType(type)}"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToChannelStringConvertert.cs b/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToChannelStringConvertert.cs index a5f5efc81b..acce5b7254 100644 --- a/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToChannelStringConvertert.cs +++ b/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToChannelStringConvertert.cs @@ -3,21 +3,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class WiFiChannelCenterFrequencyToChannelStringConvertert : IValueConverter { - public sealed class WiFiChannelCenterFrequencyToChannelStringConvertert : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not int channelCenterFrequencyInKilohertz) - return "-/-"; + if (value is not int channelCenterFrequencyInKilohertz) + return "-/-"; - return $"{WiFi.GetChannelFromChannelFrequency(channelCenterFrequencyInKilohertz)}"; - } + return $"{WiFi.GetChannelFromChannelFrequency(channelCenterFrequencyInKilohertz)}"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToFrequencyStringConverter.cs b/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToFrequencyStringConverter.cs index 217985d783..c92be96a85 100644 --- a/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToFrequencyStringConverter.cs +++ b/Source/NETworkManager.Converters/WiFiChannelCenterFrequencyToFrequencyStringConverter.cs @@ -3,21 +3,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class WiFiChannelCenterFrequencyToFrequencyStringConverter : IValueConverter { - public sealed class WiFiChannelCenterFrequencyToFrequencyStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not int channelCenterFrequencyInKilohertz) - return "-/-"; + if (value is not int channelCenterFrequencyInKilohertz) + return "-/-"; - return $"{WiFi.ConvertChannelFrequencyToGigahertz(channelCenterFrequencyInKilohertz)} GHz"; - } + return $"{WiFi.ConvertChannelFrequencyToGigahertz(channelCenterFrequencyInKilohertz)} GHz"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/WiFiDBMReverseConverter.cs b/Source/NETworkManager.Converters/WiFiDBMReverseConverter.cs index a29a242d87..47ef32b073 100644 --- a/Source/NETworkManager.Converters/WiFiDBMReverseConverter.cs +++ b/Source/NETworkManager.Converters/WiFiDBMReverseConverter.cs @@ -2,21 +2,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class WiFiDBMReverseConverter : IValueConverter { - public sealed class WiFiDBMReverseConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is double)) - return "-/-"; + if (!(value is double)) + return "-/-"; - return $"-{100 - (double)value} dBm"; - } + return $"-{100 - (double)value} dBm"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/WiFiNetworkRssiInDecibelMilliwattsToSignalStrengthStringConverter.cs b/Source/NETworkManager.Converters/WiFiNetworkRssiInDecibelMilliwattsToSignalStrengthStringConverter.cs index 03e1813a9c..0d04e89db9 100644 --- a/Source/NETworkManager.Converters/WiFiNetworkRssiInDecibelMilliwattsToSignalStrengthStringConverter.cs +++ b/Source/NETworkManager.Converters/WiFiNetworkRssiInDecibelMilliwattsToSignalStrengthStringConverter.cs @@ -2,21 +2,20 @@ using System.Globalization; using System.Windows.Data; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class WiFiNetworkRssiInDecibelMilliwattsToSignalStrengthStringConverter : IValueConverter { - public sealed class WiFiNetworkRssiInDecibelMilliwattsToSignalStrengthStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is not double networkRssiInDecibelMilliwatts) - return "-/-"; + if (value is not double networkRssiInDecibelMilliwatts) + return "-/-"; - return $"{networkRssiInDecibelMilliwatts} dBm"; - } + return $"{networkRssiInDecibelMilliwatts} dBm"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } diff --git a/Source/NETworkManager.Converters/WiFiPhyKindToStringConverter.cs b/Source/NETworkManager.Converters/WiFiPhyKindToStringConverter.cs index c1522ec168..794d1bb0c8 100644 --- a/Source/NETworkManager.Converters/WiFiPhyKindToStringConverter.cs +++ b/Source/NETworkManager.Converters/WiFiPhyKindToStringConverter.cs @@ -4,21 +4,20 @@ using System.Windows.Data; using Windows.Devices.WiFi; -namespace NETworkManager.Converters +namespace NETworkManager.Converters; + +public sealed class WiFiPhyKindToStringConverter : IValueConverter { - public sealed class WiFiPhyKindToStringConverter : IValueConverter + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (!(value is WiFiPhyKind phyKind)) - return "-/-"; + if (!(value is WiFiPhyKind phyKind)) + return "-/-"; - return $"{WiFi.GetHumandReadablePhyKind(phyKind)}"; - } + return $"{WiFi.GetHumandReadablePhyKind(phyKind)}"; + } - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); } } From 3df5e896237d470d1050614721a5e5e1135cec3d Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:44:56 +0100 Subject: [PATCH 09/11] Chore: Use .NET 7 syntax --- .../NETworkManager.Models/AWS/AWSProfile.cs | 17 +- .../AWS/AWSProfileInfo.cs | 77 +- Source/NETworkManager.Models/AWS/AWSRegion.cs | 25 +- .../AWS/AWSSessionManager.cs | 33 +- .../AWS/AWSSessionManagerSessionInfo.cs | 19 +- .../Appearance/AccentColorInfo.cs | 14 +- .../Appearance/BaseColorInfo.cs | 17 +- .../Appearance/ThemeColorInfo.cs | 14 +- .../NETworkManager.Models/ApplicationInfo.cs | 121 +- .../ApplicationManager.cs | 221 +- .../NETworkManager.Models/ApplicationName.cs | 269 ++- .../EventSystem/EventSystem.cs | 29 +- .../EventSystem/EventSystemRedirectArgs.cs | 19 +- .../Export/ExportManager.ExportFileType.cs | 17 +- .../Export/ExportManager.cs | 1841 ++++++++--------- .../NETworkManager.Models/Lookup/OUIInfo.cs | 21 +- .../NETworkManager.Models/Lookup/OUILookup.cs | 93 +- .../Lookup/PortLookup.Protocol.cs | 17 +- .../Lookup/PortLookup.cs | 97 +- .../Lookup/PortLookupInfo.cs | 29 +- Source/NETworkManager.Models/Network/ARP.cs | 325 ++- .../NETworkManager.Models/Network/ARPInfo.cs | 33 +- .../Network/BandwidthMeter.cs | 139 +- .../Network/BandwidthMeterSpeedArgs.cs | 31 +- .../Network/BitCaluclator.cs | 109 +- .../Network/BitCaluclatorInfo.cs | 65 +- .../Network/BitCaluclatorNotation.cs | 25 +- .../Network/BitCaluclatorUnit.cs | 105 +- .../Network/Connection.Protocol.cs | 11 +- .../Network/Connection.cs | 23 +- .../Network/ConnectionInfo.cs | 47 +- .../Network/ConnectionState.cs | 49 +- .../Network/DNSLookup.cs | 297 ++- .../Network/DNSLookupCompleteArgs.cs | 41 +- .../Network/DNSLookupRecordArgs.cs | 47 +- .../Network/DNSLookupRecordInfo.cs | 57 +- .../Network/DNSLookupSettings.cs | 33 +- .../Network/DNSServer.cs | 65 +- .../Network/DNSServerConnectionInfoProfile.cs | 47 +- .../Network/DiscoveryProtocol.Protocol.cs | 38 +- .../Network/DiscoveryProtocol.cs | 287 ++- .../Network/DiscoveryProtocolErrorArgs.cs | 43 +- .../Network/DiscoveryProtocolPackageArgs.cs | 43 +- .../Network/DiscoveryProtocolPackageInfo.cs | 125 +- .../Network/DiscoveryProtocolWarningArgs.cs | 43 +- .../Network/HostFoundArgs.cs | 33 +- .../NETworkManager.Models/Network/HostInfo.cs | 43 +- .../Network/HostNotFoundException.cs | 21 +- .../Network/HostRangeHelper.cs | 285 ++- .../Network/IPNetworkInfo.cs | 59 +- .../Network/IPScanner.cs | 281 ++- .../Network/IPScannerCustomCommand.cs | 19 +- .../Network/IPv4Address.cs | 163 +- .../Network/Listener.Protocol.cs | 17 +- .../NETworkManager.Models/Network/Listener.cs | 75 +- .../Network/ListenerInfo.cs | 31 +- .../Network/MaximumHopsReachedArgs.cs | 21 +- .../Network/NetworkInterface.cs | 533 +++-- .../Network/NetworkInterfaceConfig.cs | 29 +- .../Network/NetworkInterfaceInfo.cs | 57 +- Source/NETworkManager.Models/Network/Ping.cs | 231 +-- .../Network/PingExceptionArgs.cs | 19 +- .../NETworkManager.Models/Network/PingInfo.cs | 151 +- .../Network/PingMonitorOptions.cs | 21 +- .../Network/PingReceivedArgs.cs | 117 +- .../NETworkManager.Models/Network/PortInfo.cs | 47 +- .../Network/PortProfile.cs | 35 +- .../Network/PortProfileInfo.cs | 25 +- .../Network/PortScannedArgs.cs | 37 +- .../Network/PortScanner.cs | 227 +- .../Network/PortState.cs | 43 +- .../Network/ProgressChangedArgs.cs | 23 +- .../Network/SNMPReceivedArgs.cs | 25 +- .../Network/SNMPReceivedInfo.cs | 33 +- .../Network/SNTPDateTime.cs | 69 +- .../Network/SNTPLookup.cs | 187 +- .../Network/SNTPLookupErrorArgs.cs | 43 +- .../Network/SNTPLookupResultArgs.cs | 31 +- .../Network/SNTPLookupResultInfo.cs | 37 +- .../Network/SNTPLookupSettings.cs | 17 +- .../Network/SNTPServer.cs | 65 +- .../Network/ServerConnectionInfo.cs | 107 +- .../Network/ServerConnectionInfoProfile.cs | 57 +- .../Network/Subnetmask.cs | 59 +- .../Network/SubnetmaskInfo.cs | 33 +- .../Network/Traceroute.cs | 223 +- .../Network/TracerouteErrorArgs.cs | 21 +- .../Network/TracerouteHopInfo.cs | 61 +- .../Network/TracerouteHopReceivedArgs.cs | 53 +- .../Network/WakeOnLAN.cs | 49 +- .../Network/WakeOnLanInfo.cs | 29 +- Source/NETworkManager.Models/Network/Whois.cs | 97 +- .../Network/WhoisServerInfo.cs | 19 +- Source/NETworkManager.Models/Network/WiFi.cs | 271 ++- .../Network/WiFiAdapterInfo.cs | 17 +- .../Network/WiFiNetworkInfo.cs | 53 +- .../PowerShell/ExecutionPolicy.cs | 19 +- .../PowerShell/PowerShell.cs | 169 +- .../PowerShell/PowerShellSessionInfo.cs | 23 +- .../PuTTY/ConnectionMode.cs | 49 +- Source/NETworkManager.Models/PuTTY/LogMode.cs | 33 +- Source/NETworkManager.Models/PuTTY/PuTTY.cs | 349 ++-- .../PuTTY/PuTTYSessionInfo.cs | 125 +- .../AudioCaptureRedirectionMode.cs | 27 +- .../RemoteDesktop/AudioRedirectionMode.cs | 35 +- .../RemoteDesktop/KeyboardHookMode.cs | 31 +- .../RemoteDesktop/Keystroke.cs | 17 +- .../RemoteDesktop/NetworkConnectionType.cs | 69 +- .../RemoteDesktop/RemoteDesktop.cs | 71 +- .../RemoteDesktopKeystrokeInfo.cs | 25 +- .../RemoteDesktopPerformanceConstants.cs | 47 +- .../RemoteDesktop/RemoteDesktopSessionInfo.cs | 71 +- .../TigerVNC/TigerVNC.cs | 11 +- .../TigerVNC/TigerVNCSessionInfo.cs | 17 +- .../WebConsole/WebConsoleSessionInfo.cs | 13 +- .../EmptyOrAWSRegionExistsValidator.cs | 3 +- 116 files changed, 5253 insertions(+), 5368 deletions(-) diff --git a/Source/NETworkManager.Models/AWS/AWSProfile.cs b/Source/NETworkManager.Models/AWS/AWSProfile.cs index fe24b378d8..f2af61cffa 100644 --- a/Source/NETworkManager.Models/AWS/AWSProfile.cs +++ b/Source/NETworkManager.Models/AWS/AWSProfile.cs @@ -1,16 +1,15 @@ using System.Collections.Generic; -namespace NETworkManager.Models.AWS +namespace NETworkManager.Models.AWS; + +public static class AWSProfile { - public static class AWSProfile + public static List GetDefaultList() { - public static List GetDefaultList() + return new List { - return new List - { - new AWSProfileInfo(false, "default", "eu-central-1"), - new AWSProfileInfo(false, "default", "us-east-1"), - }; - } + new AWSProfileInfo(false, "default", "eu-central-1"), + new AWSProfileInfo(false, "default", "us-east-1"), + }; } } diff --git a/Source/NETworkManager.Models/AWS/AWSProfileInfo.cs b/Source/NETworkManager.Models/AWS/AWSProfileInfo.cs index 2ae81e2857..057cbe601f 100644 --- a/Source/NETworkManager.Models/AWS/AWSProfileInfo.cs +++ b/Source/NETworkManager.Models/AWS/AWSProfileInfo.cs @@ -1,46 +1,45 @@ -namespace NETworkManager.Models.AWS +namespace NETworkManager.Models.AWS; + +/// +/// Class is used to store informations about an AWS profile. +/// +public class AWSProfileInfo { + + /// + /// Indicates if the AWS profile is enabled. + /// + public bool IsEnabled { get; set; } + /// - /// Class is used to store informations about an AWS profile. + /// Name of the profile configured in ~\.aws\credentials. /// - public class AWSProfileInfo + public string Profile { get; set; } + + /// + /// AWS region. + /// + public string Region { get; set; } + + + /// + /// Create an empty instance of . + /// + public AWSProfileInfo() { - /// - /// Indicates if the AWS profile is enabled. - /// - public bool IsEnabled { get; set; } - - /// - /// Name of the profile configured in ~\.aws\credentials. - /// - public string Profile { get; set; } - - /// - /// AWS region. - /// - public string Region { get; set; } - - - /// - /// Create an empty instance of . - /// - public AWSProfileInfo() - { - - } - - /// - /// Create an instance of with parameters. - /// - /// . - /// . - /// . - public AWSProfileInfo(bool isEnabled, string profile, string region) - { - IsEnabled = isEnabled; - Profile = profile; - Region = region; - } + } + + /// + /// Create an instance of with parameters. + /// + /// . + /// . + /// . + public AWSProfileInfo(bool isEnabled, string profile, string region) + { + IsEnabled = isEnabled; + Profile = profile; + Region = region; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/AWS/AWSRegion.cs b/Source/NETworkManager.Models/AWS/AWSRegion.cs index 2562ea392a..855ff43bd5 100644 --- a/Source/NETworkManager.Models/AWS/AWSRegion.cs +++ b/Source/NETworkManager.Models/AWS/AWSRegion.cs @@ -2,21 +2,20 @@ using NETworkManager.Utilities; using System.Collections.Generic; -namespace AWS +namespace NETworkManager.Models.AWS; + +public class AWSRegion : SingletonBase { - public class AWSRegion : SingletonBase - { - private readonly HashSet _regions = new(); + private readonly HashSet _regions = new(); - public AWSRegion() - { - foreach(var region in RegionEndpoint.EnumerableAllRegions) - _regions.Add(region.SystemName); - } + public AWSRegion() + { + foreach(var region in RegionEndpoint.EnumerableAllRegions) + _regions.Add(region.SystemName); + } - public bool RegionExists(string region) - { - return _regions.Contains(region); - } + public bool RegionExists(string region) + { + return _regions.Contains(region); } } diff --git a/Source/NETworkManager.Models/AWS/AWSSessionManager.cs b/Source/NETworkManager.Models/AWS/AWSSessionManager.cs index a957c84c63..49f2d92a33 100644 --- a/Source/NETworkManager.Models/AWS/AWSSessionManager.cs +++ b/Source/NETworkManager.Models/AWS/AWSSessionManager.cs @@ -1,24 +1,23 @@ -namespace NETworkManager.Models.AWS +namespace NETworkManager.Models.AWS; + +public static partial class AWSSessionManager { - public static partial class AWSSessionManager - { - private static string _encodingCommand = "[console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding"; - private static string _setLocationCommand = "Set-Location -Path ~"; - private static string _clearHostCommand = "Clear-Host"; + private static string _encodingCommand = "[console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding"; + private static string _setLocationCommand = "Set-Location -Path ~"; + private static string _clearHostCommand = "Clear-Host"; - public static string BuildCommandLine(AWSSessionManagerSessionInfo sessionInfo) - { - var commandLine = $"-NoExit -NoLogo -NoProfile -Command \"{_encodingCommand}; {_setLocationCommand}; {_clearHostCommand}; aws ssm start-session --target {sessionInfo.InstanceID}"; + public static string BuildCommandLine(AWSSessionManagerSessionInfo sessionInfo) + { + var commandLine = $"-NoExit -NoLogo -NoProfile -Command \"{_encodingCommand}; {_setLocationCommand}; {_clearHostCommand}; aws ssm start-session --target {sessionInfo.InstanceID}"; - // Add profile - if (!string.IsNullOrEmpty(sessionInfo.Profile)) - commandLine += $" --profile {sessionInfo.Profile}"; + // Add profile + if (!string.IsNullOrEmpty(sessionInfo.Profile)) + commandLine += $" --profile {sessionInfo.Profile}"; - // Add region - if (!string.IsNullOrEmpty(sessionInfo.Region)) - commandLine += $" --region {sessionInfo.Region}"; + // Add region + if (!string.IsNullOrEmpty(sessionInfo.Region)) + commandLine += $" --region {sessionInfo.Region}"; - return $"{commandLine}\""; - } + return $"{commandLine}\""; } } diff --git a/Source/NETworkManager.Models/AWS/AWSSessionManagerSessionInfo.cs b/Source/NETworkManager.Models/AWS/AWSSessionManagerSessionInfo.cs index 6c22eb7185..4adfa831f6 100644 --- a/Source/NETworkManager.Models/AWS/AWSSessionManagerSessionInfo.cs +++ b/Source/NETworkManager.Models/AWS/AWSSessionManagerSessionInfo.cs @@ -1,15 +1,14 @@ -namespace NETworkManager.Models.AWS +namespace NETworkManager.Models.AWS; + +public class AWSSessionManagerSessionInfo { - public class AWSSessionManagerSessionInfo - { - public string ApplicationFilePath { get; set; } - public string InstanceID { get; set; } - public string Profile { get; set; } - public string Region { get; set; } + public string ApplicationFilePath { get; set; } + public string InstanceID { get; set; } + public string Profile { get; set; } + public string Region { get; set; } - public AWSSessionManagerSessionInfo() - { + public AWSSessionManagerSessionInfo() + { - } } } diff --git a/Source/NETworkManager.Models/Appearance/AccentColorInfo.cs b/Source/NETworkManager.Models/Appearance/AccentColorInfo.cs index f049728642..5eeb43a6ac 100644 --- a/Source/NETworkManager.Models/Appearance/AccentColorInfo.cs +++ b/Source/NETworkManager.Models/Appearance/AccentColorInfo.cs @@ -1,10 +1,10 @@  -namespace NETworkManager.Models.Appearance +namespace NETworkManager.Models.Appearance; + +/// +/// Class contains informations about MahApps.Metro accents. +/// +public class AccentColorInfo : BaseColorInfo { - /// - /// Class contains informations about MahApps.Metro accents. - /// - public class AccentColorInfo : BaseColorInfo - { - } + } diff --git a/Source/NETworkManager.Models/Appearance/BaseColorInfo.cs b/Source/NETworkManager.Models/Appearance/BaseColorInfo.cs index b8701490ee..7642ade292 100644 --- a/Source/NETworkManager.Models/Appearance/BaseColorInfo.cs +++ b/Source/NETworkManager.Models/Appearance/BaseColorInfo.cs @@ -1,13 +1,12 @@ using System.Windows.Media; -namespace NETworkManager.Models.Appearance +namespace NETworkManager.Models.Appearance; + +/// +/// Base class for MahApps.Metro theme/accent informations. +/// +public abstract class BaseColorInfo { - /// - /// Base class for MahApps.Metro theme/accent informations. - /// - public abstract class BaseColorInfo - { - public string Name { get; set; } - public Brush Color { get; set; } - } + public string Name { get; set; } + public Brush Color { get; set; } } diff --git a/Source/NETworkManager.Models/Appearance/ThemeColorInfo.cs b/Source/NETworkManager.Models/Appearance/ThemeColorInfo.cs index 6951974f3e..fccd39fe78 100644 --- a/Source/NETworkManager.Models/Appearance/ThemeColorInfo.cs +++ b/Source/NETworkManager.Models/Appearance/ThemeColorInfo.cs @@ -1,9 +1,9 @@ -namespace NETworkManager.Models.Appearance +namespace NETworkManager.Models.Appearance; + +/// +/// Class contains informations about MahApps.Metro themes. +/// +public class ThemeColorInfo : BaseColorInfo { - /// - /// Class contains informations about MahApps.Metro themes. - /// - public class ThemeColorInfo : BaseColorInfo - { - } + } diff --git a/Source/NETworkManager.Models/ApplicationInfo.cs b/Source/NETworkManager.Models/ApplicationInfo.cs index 69f619a835..cabd52f53d 100644 --- a/Source/NETworkManager.Models/ApplicationInfo.cs +++ b/Source/NETworkManager.Models/ApplicationInfo.cs @@ -1,77 +1,76 @@ -namespace NETworkManager.Models +namespace NETworkManager.Models; + +/// +/// Stores informations about an application. +/// +public class ApplicationInfo { /// - /// Stores informations about an application. + /// Name of the application. /// - public class ApplicationInfo - { - /// - /// Name of the application. - /// - public ApplicationName Name { get; set; } + public ApplicationName Name { get; set; } - /// - /// Indicates that the application is visible to the user. - /// - public bool IsVisible { get; set; } + /// + /// Indicates that the application is visible to the user. + /// + public bool IsVisible { get; set; } - /// - /// Initializes a new instance of the class. - /// - public ApplicationInfo() - { + /// + /// Initializes a new instance of the class. + /// + public ApplicationInfo() + { - } + } - /// - /// Initializes a new instance of the class and passes the as paramteter. - /// - /// - public ApplicationInfo(ApplicationName name) - { - Name = name; - IsVisible = true; - } + /// + /// Initializes a new instance of the class and passes the as paramteter. + /// + /// + public ApplicationInfo(ApplicationName name) + { + Name = name; + IsVisible = true; + } - /// - /// Method to check if an object is equal to this object. - /// - /// Object to check. - /// Equality as . - public bool Equals(ApplicationInfo info) - { - if (info == null) - return false; + /// + /// Method to check if an object is equal to this object. + /// + /// Object to check. + /// Equality as . + public bool Equals(ApplicationInfo info) + { + if (info == null) + return false; - return Name == info.Name; - } + return Name == info.Name; + } - /// - /// Method to check if an object is equal to this object. - /// - /// Object from type to check. - /// Equality as . - public override bool Equals(object obj) - { - if (obj is null) - return false; + /// + /// Method to check if an object is equal to this object. + /// + /// Object from type to check. + /// Equality as . + public override bool Equals(object obj) + { + if (obj is null) + return false; - if (ReferenceEquals(this, obj)) - return true; + if (ReferenceEquals(this, obj)) + return true; - if (obj.GetType() != GetType()) - return false; + if (obj.GetType() != GetType()) + return false; - return Equals(obj as ApplicationInfo); - } + return Equals(obj as ApplicationInfo); + } - /// - /// Method to return the hash code of this object. - /// - /// Hashcode as . - public override int GetHashCode() - { - return Name.GetHashCode(); - } + /// + /// Method to return the hash code of this object. + /// + /// Hashcode as . + public override int GetHashCode() + { + return Name.GetHashCode(); } } diff --git a/Source/NETworkManager.Models/ApplicationManager.cs b/Source/NETworkManager.Models/ApplicationManager.cs index 0674dc96bc..7df0b48a54 100644 --- a/Source/NETworkManager.Models/ApplicationManager.cs +++ b/Source/NETworkManager.Models/ApplicationManager.cs @@ -4,126 +4,125 @@ using System.Linq; using System.Windows.Controls; -namespace NETworkManager.Models +namespace NETworkManager.Models; + +/// +/// Provides methods to manage networkmanger applications. +/// +public static class ApplicationManager { /// - /// Provides methods to manage networkmanger applications. + /// Method to return all available applications in. + /// + /// All names as array. + public static ApplicationName[] GetNames() => (ApplicationName[])Enum.GetValues(typeof(ApplicationName)); + + /// + /// Method returns a list with all . /// - public static class ApplicationManager + /// IEnumerable with + public static IEnumerable GetList() { - /// - /// Method to return all available applications in. - /// - /// All names as array. - public static ApplicationName[] GetNames() => (ApplicationName[])Enum.GetValues(typeof(ApplicationName)); + var list = new List(); - /// - /// Method returns a list with all . - /// - /// IEnumerable with - public static IEnumerable GetList() - { - var list = new List(); + foreach (var name in GetNames().Where(x => x != ApplicationName.None)) + list.Add(new ApplicationInfo(name)); - foreach (var name in GetNames().Where(x => x != ApplicationName.None)) - list.Add(new ApplicationInfo(name)); + return list; + } - return list; - } + /// + /// Method will return the icon based on . + /// + /// + /// Application icon as . + public static Canvas GetIcon(ApplicationName name) + { + var canvas = new Canvas(); - /// - /// Method will return the icon based on . - /// - /// - /// Application icon as . - public static Canvas GetIcon(ApplicationName name) + switch (name) { - var canvas = new Canvas(); - - switch (name) - { - case ApplicationName.Dashboard: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.ViewDashboardVariant }); - break; - case ApplicationName.NetworkInterface: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Network }); - break; - case ApplicationName.WiFi: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.AccessPointNetwork }); - break; - case ApplicationName.IPScanner: - canvas.Children.Add(new PackIconFontAwesome { Kind = PackIconFontAwesomeKind.NetworkWiredSolid }); - break; - case ApplicationName.PortScanner: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.NetworkPort }); - break; - case ApplicationName.PingMonitor: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.RadarScreen }); - break; - case ApplicationName.Traceroute: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.TransitConnection }); - break; - case ApplicationName.DNSLookup: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.SearchWeb }); - break; - case ApplicationName.RemoteDesktop: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.RemoteDesktop }); - break; - case ApplicationName.PowerShell: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Powershell }); - break; - case ApplicationName.PuTTY: - canvas.Children.Add(new PackIconFontAwesome { Kind = PackIconFontAwesomeKind.TerminalSolid }); - break; - case ApplicationName.AWSSessionManager: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Aws }); - break; - case ApplicationName.TigerVNC: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.EyeOutline }); - break; - case ApplicationName.WebConsole: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Browser }); - break; - case ApplicationName.SNMP: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Switch }); - break; - case ApplicationName.SNTPLookup: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.ClockCheckOutline }); - break; - case ApplicationName.DiscoveryProtocol: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.SwapHorizontal }); - break; - case ApplicationName.WakeOnLAN: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Power }); - break; - case ApplicationName.Whois: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.CloudSearchOutline }); - break; - case ApplicationName.SubnetCalculator: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Calculator }); - break; - case ApplicationName.BitCalculator: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.TypeBit }); - break; - case ApplicationName.Lookup: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.DatabaseSearch }); - break; - case ApplicationName.Connections: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Connect }); - break; - case ApplicationName.Listeners: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Wan }); - break; - case ApplicationName.ARPTable: - canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.TableOfContents }); - break; - case ApplicationName.None: - default: - canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.SmileyFrown }); - break; - } - - return canvas; + case ApplicationName.Dashboard: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.ViewDashboardVariant }); + break; + case ApplicationName.NetworkInterface: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Network }); + break; + case ApplicationName.WiFi: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.AccessPointNetwork }); + break; + case ApplicationName.IPScanner: + canvas.Children.Add(new PackIconFontAwesome { Kind = PackIconFontAwesomeKind.NetworkWiredSolid }); + break; + case ApplicationName.PortScanner: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.NetworkPort }); + break; + case ApplicationName.PingMonitor: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.RadarScreen }); + break; + case ApplicationName.Traceroute: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.TransitConnection }); + break; + case ApplicationName.DNSLookup: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.SearchWeb }); + break; + case ApplicationName.RemoteDesktop: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.RemoteDesktop }); + break; + case ApplicationName.PowerShell: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Powershell }); + break; + case ApplicationName.PuTTY: + canvas.Children.Add(new PackIconFontAwesome { Kind = PackIconFontAwesomeKind.TerminalSolid }); + break; + case ApplicationName.AWSSessionManager: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Aws }); + break; + case ApplicationName.TigerVNC: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.EyeOutline }); + break; + case ApplicationName.WebConsole: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Browser }); + break; + case ApplicationName.SNMP: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Switch }); + break; + case ApplicationName.SNTPLookup: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.ClockCheckOutline }); + break; + case ApplicationName.DiscoveryProtocol: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.SwapHorizontal }); + break; + case ApplicationName.WakeOnLAN: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Power }); + break; + case ApplicationName.Whois: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.CloudSearchOutline }); + break; + case ApplicationName.SubnetCalculator: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Calculator }); + break; + case ApplicationName.BitCalculator: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.TypeBit }); + break; + case ApplicationName.Lookup: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.DatabaseSearch }); + break; + case ApplicationName.Connections: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.Connect }); + break; + case ApplicationName.Listeners: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.Wan }); + break; + case ApplicationName.ARPTable: + canvas.Children.Add(new PackIconMaterial { Kind = PackIconMaterialKind.TableOfContents }); + break; + case ApplicationName.None: + default: + canvas.Children.Add(new PackIconModern { Kind = PackIconModernKind.SmileyFrown }); + break; } + + return canvas; } } diff --git a/Source/NETworkManager.Models/ApplicationName.cs b/Source/NETworkManager.Models/ApplicationName.cs index 1324f518a3..6147eb0224 100644 --- a/Source/NETworkManager.Models/ApplicationName.cs +++ b/Source/NETworkManager.Models/ApplicationName.cs @@ -1,138 +1,137 @@ -namespace NETworkManager.Models +namespace NETworkManager.Models; + +/// +/// Represents all available applications. +/// +public enum ApplicationName { /// - /// Represents all available applications. - /// - public enum ApplicationName - { - /// - /// No application. - /// - None, - - /// - /// Dashboard application. - /// - Dashboard, - - /// - /// Network interface application. - /// - NetworkInterface, - - /// - /// WiFi application. - /// - WiFi, - - /// - /// IP scanner application. - /// - IPScanner, - - /// - /// Port scanner application. - /// - PortScanner, - - /// - /// Ping monitor application. - /// - PingMonitor, - - /// - /// Traceroute application. - /// - Traceroute, - - /// - /// DNS lookup application. - /// - DNSLookup, - - /// - /// Remote Desktop application. - /// - RemoteDesktop, - - /// - /// PowerShell application. - /// - PowerShell, - - /// - /// PuTTY application. - /// - PuTTY, - - /// - /// AWS Systems Manager Session Manager. - /// - AWSSessionManager, - - /// - /// TigerVNC application. - /// - TigerVNC, - - /// - /// WebConsole application. - /// - WebConsole, - - /// - /// SNMP application. - /// - SNMP, - - /// - /// SNTP lookup application. - /// - SNTPLookup, - - /// - /// Discovery protocol application. - /// - DiscoveryProtocol, - - /// - /// Wake on LAN application. - /// - WakeOnLAN, - - /// - /// Whois application. - /// - Whois, - - /// - /// Subnet calculator application. - /// - SubnetCalculator, - - /// - /// Bit calculator application. - /// - BitCalculator, - - /// - /// Lookup application. - /// - Lookup, - - /// - /// Connections application. - /// - Connections, - - /// - /// Listeners application. - /// - Listeners, - - /// - /// ARP table application. - /// - ARPTable - } + /// No application. + /// + None, + + /// + /// Dashboard application. + /// + Dashboard, + + /// + /// Network interface application. + /// + NetworkInterface, + + /// + /// WiFi application. + /// + WiFi, + + /// + /// IP scanner application. + /// + IPScanner, + + /// + /// Port scanner application. + /// + PortScanner, + + /// + /// Ping monitor application. + /// + PingMonitor, + + /// + /// Traceroute application. + /// + Traceroute, + + /// + /// DNS lookup application. + /// + DNSLookup, + + /// + /// Remote Desktop application. + /// + RemoteDesktop, + + /// + /// PowerShell application. + /// + PowerShell, + + /// + /// PuTTY application. + /// + PuTTY, + + /// + /// AWS Systems Manager Session Manager. + /// + AWSSessionManager, + + /// + /// TigerVNC application. + /// + TigerVNC, + + /// + /// WebConsole application. + /// + WebConsole, + + /// + /// SNMP application. + /// + SNMP, + + /// + /// SNTP lookup application. + /// + SNTPLookup, + + /// + /// Discovery protocol application. + /// + DiscoveryProtocol, + + /// + /// Wake on LAN application. + /// + WakeOnLAN, + + /// + /// Whois application. + /// + Whois, + + /// + /// Subnet calculator application. + /// + SubnetCalculator, + + /// + /// Bit calculator application. + /// + BitCalculator, + + /// + /// Lookup application. + /// + Lookup, + + /// + /// Connections application. + /// + Connections, + + /// + /// Listeners application. + /// + Listeners, + + /// + /// ARP table application. + /// + ARPTable } \ No newline at end of file diff --git a/Source/NETworkManager.Models/EventSystem/EventSystem.cs b/Source/NETworkManager.Models/EventSystem/EventSystem.cs index 18e295ac39..a10c55c137 100644 --- a/Source/NETworkManager.Models/EventSystem/EventSystem.cs +++ b/Source/NETworkManager.Models/EventSystem/EventSystem.cs @@ -1,23 +1,22 @@ using System; -namespace NETworkManager.Models.EventSystem +namespace NETworkManager.Models.EventSystem; + +public class EventSystem { - public class EventSystem - { - // This will notify the mail window, to change the view to another application and redirect some data (hostname, ip) - public static event EventHandler OnRedirectDataToApplicationEvent; + // This will notify the mail window, to change the view to another application and redirect some data (hostname, ip) + public static event EventHandler OnRedirectDataToApplicationEvent; - public static void RedirectToApplication(ApplicationName application, string data) - { - OnRedirectDataToApplicationEvent?.Invoke(null, new EventSystemRedirectArgs(application, data)); - } + public static void RedirectToApplication(ApplicationName application, string data) + { + OnRedirectDataToApplicationEvent?.Invoke(null, new EventSystemRedirectArgs(application, data)); + } - // This will notify the main window, to change the view to the settings... - public static event EventHandler OnRedirectToSettingsEvent; + // This will notify the main window, to change the view to the settings... + public static event EventHandler OnRedirectToSettingsEvent; - public static void RedirectToSettings() - { - OnRedirectToSettingsEvent?.Invoke(null, EventArgs.Empty); - } + public static void RedirectToSettings() + { + OnRedirectToSettingsEvent?.Invoke(null, EventArgs.Empty); } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/EventSystem/EventSystemRedirectArgs.cs b/Source/NETworkManager.Models/EventSystem/EventSystemRedirectArgs.cs index 818d99ed50..677e44c060 100644 --- a/Source/NETworkManager.Models/EventSystem/EventSystemRedirectArgs.cs +++ b/Source/NETworkManager.Models/EventSystem/EventSystemRedirectArgs.cs @@ -1,17 +1,16 @@ using System; -namespace NETworkManager.Models.EventSystem +namespace NETworkManager.Models.EventSystem; + +public class EventSystemRedirectArgs : EventArgs { - public class EventSystemRedirectArgs : EventArgs - { - public ApplicationName Application { get; set; } - public string Args { get; set; } + public ApplicationName Application { get; set; } + public string Args { get; set; } - public EventSystemRedirectArgs(ApplicationName application, string args) - { - Application = application; - Args = args; - } + public EventSystemRedirectArgs(ApplicationName application, string args) + { + Application = application; + Args = args; } } diff --git a/Source/NETworkManager.Models/Export/ExportManager.ExportFileType.cs b/Source/NETworkManager.Models/Export/ExportManager.ExportFileType.cs index ed61ef2bd5..301c81cf3d 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.ExportFileType.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.ExportFileType.cs @@ -1,13 +1,12 @@ -namespace NETworkManager.Models.Export +namespace NETworkManager.Models.Export; + +public static partial class ExportManager { - public static partial class ExportManager + public enum ExportFileType { - public enum ExportFileType - { - CSV, - XML, - JSON, - TXT - } + CSV, + XML, + JSON, + TXT } } diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index bb832d40e6..69318fbfac 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -8,1126 +8,1125 @@ using NETworkManager.Models.Lookup; using NETworkManager.Models.Network; -namespace NETworkManager.Models.Export +namespace NETworkManager.Models.Export; + +/// +/// This class will provide methods to export text or objects to files like csv, xml, json or plain text. +/// +public static partial class ExportManager { + #region Variables + /// + /// Default declaration for XML documents. + /// + private static readonly XDeclaration DefaultXDeclaration = new XDeclaration("1.0", "utf-8", "yes"); + #endregion + + #region Methods + + #region Export /// - /// This class will provide methods to export text or objects to files like csv, xml, json or plain text. + /// Method to export objects from type to a file. /// - public static partial class ExportManager + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) { - #region Variables - /// - /// Default declaration for XML documents. - /// - private static readonly XDeclaration DefaultXDeclaration = new XDeclaration("1.0", "utf-8", "yes"); - #endregion - - #region Methods - - #region Export - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + public static void Export(string filePath, ExportFileType fileType, ObservableCollection collection) + { + switch (fileType) { - switch (fileType) - { - case ExportFileType.CSV: - CreateCSV(collection, filePath); - break; - case ExportFileType.XML: - CreateXML(collection, filePath); - break; - case ExportFileType.JSON: - CreateJSON(collection, filePath); - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + case ExportFileType.CSV: + CreateCSV(collection, filePath); + break; + case ExportFileType.XML: + CreateXML(collection, filePath); + break; + case ExportFileType.JSON: + CreateJSON(collection, filePath); + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - /// - /// Method to export text to a file. - /// - /// Path to the export file. - /// Text to export. - public static void Export(string filePath, string content) - { - CreateTXT(content, filePath); - } - #endregion + /// + /// Method to export text to a file. + /// + /// Path to the export file. + /// Text to export. + public static void Export(string filePath, string content) + { + CreateTXT(content, filePath); + } + #endregion - #region CreateCSV - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + #region CreateCSV + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(WiFiNetworkInfo.BSSID)},{nameof(WiFiNetworkInfo.SSID)},{nameof(WiFiNetworkInfo.ChannelCenterFrequencyInKilohertz)},{nameof(WiFiNetworkInfo.SignalBars)},{nameof(WiFiNetworkInfo.IsWiFiDirect)},{nameof(WiFiNetworkInfo.NetworkRssiInDecibelMilliwatts)},{nameof(WiFiNetworkInfo.PhyKind)},{nameof(WiFiNetworkInfo.NetworkKind)},{nameof(WiFiNetworkInfo.AuthenticationType)},{nameof(WiFiNetworkInfo.EncryptionType)},{nameof(WiFiNetworkInfo.BeaconInterval)}.{nameof(WiFiNetworkInfo.Uptime)}"); + stringBuilder.AppendLine($"{nameof(WiFiNetworkInfo.BSSID)},{nameof(WiFiNetworkInfo.SSID)},{nameof(WiFiNetworkInfo.ChannelCenterFrequencyInKilohertz)},{nameof(WiFiNetworkInfo.SignalBars)},{nameof(WiFiNetworkInfo.IsWiFiDirect)},{nameof(WiFiNetworkInfo.NetworkRssiInDecibelMilliwatts)},{nameof(WiFiNetworkInfo.PhyKind)},{nameof(WiFiNetworkInfo.NetworkKind)},{nameof(WiFiNetworkInfo.AuthenticationType)},{nameof(WiFiNetworkInfo.EncryptionType)},{nameof(WiFiNetworkInfo.BeaconInterval)}.{nameof(WiFiNetworkInfo.Uptime)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.BSSID},{info.SSID},{info.ChannelCenterFrequencyInKilohertz},{info.SignalBars},{info.IsWiFiDirect},{info.NetworkRssiInDecibelMilliwatts},{info.PhyKind},{info.NetworkKind},{info.AuthenticationType},{info.EncryptionType},{info.BeaconInterval},{info.Uptime}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.BSSID},{info.SSID},{info.ChannelCenterFrequencyInKilohertz},{info.SignalBars},{info.IsWiFiDirect},{info.NetworkRssiInDecibelMilliwatts},{info.PhyKind},{info.NetworkKind},{info.AuthenticationType},{info.EncryptionType},{info.BeaconInterval},{info.Uptime}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(PingInfo.IPAddress)},{nameof(HostInfo.Hostname)},{nameof(HostInfo.MACAddress)},{nameof(HostInfo.Vendor)},{nameof(PingInfo.Bytes)},{nameof(PingInfo.Time)},{nameof(PingInfo.TTL)},{nameof(PingInfo.Status)}"); + stringBuilder.AppendLine($"{nameof(PingInfo.IPAddress)},{nameof(HostInfo.Hostname)},{nameof(HostInfo.MACAddress)},{nameof(HostInfo.Vendor)},{nameof(PingInfo.Bytes)},{nameof(PingInfo.Time)},{nameof(PingInfo.TTL)},{nameof(PingInfo.Status)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.PingInfo.IPAddress},{info.Hostname},{info.MACAddress},{info.Vendor},{info.PingInfo.Bytes},{Ping.TimeToString(info.PingInfo.Status, info.PingInfo.Time, true)},{info.PingInfo.TTL},{info.PingInfo.Status}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.PingInfo.IPAddress},{info.Hostname},{info.MACAddress},{info.Vendor},{info.PingInfo.Bytes},{Ping.TimeToString(info.PingInfo.Status, info.PingInfo.Time, true)},{info.PingInfo.TTL},{info.PingInfo.Status}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(PortInfo.IPAddress)},{nameof(PortInfo.Hostname)},{nameof(PortInfo.Port)},{nameof(PortLookupInfo.Protocol)},{nameof(PortLookupInfo.Service)},{nameof(PortLookupInfo.Description)},{nameof(PortInfo.State)}"); + stringBuilder.AppendLine($"{nameof(PortInfo.IPAddress)},{nameof(PortInfo.Hostname)},{nameof(PortInfo.Port)},{nameof(PortLookupInfo.Protocol)},{nameof(PortLookupInfo.Service)},{nameof(PortLookupInfo.Description)},{nameof(PortInfo.State)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.IPAddress},{info.Hostname},{info.Port},{info.LookupInfo.Protocol},{info.LookupInfo.Service},{info.LookupInfo.Description},{info.State}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.IPAddress},{info.Hostname},{info.Port},{info.LookupInfo.Protocol},{info.LookupInfo.Service},{info.LookupInfo.Description},{info.State}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(PingInfo.Timestamp)},{nameof(PingInfo.IPAddress)},{nameof(PingInfo.Hostname)},{nameof(PingInfo.Bytes)},{nameof(PingInfo.Time)},{nameof(PingInfo.TTL)},{nameof(PingInfo.Status)}"); + stringBuilder.AppendLine($"{nameof(PingInfo.Timestamp)},{nameof(PingInfo.IPAddress)},{nameof(PingInfo.Hostname)},{nameof(PingInfo.Bytes)},{nameof(PingInfo.Time)},{nameof(PingInfo.TTL)},{nameof(PingInfo.Status)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Timestamp},{info.IPAddress},{info.Hostname},{info.Bytes},{Ping.TimeToString(info.Status, info.Time, true)},{info.TTL},{info.Status}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.Timestamp},{info.IPAddress},{info.Hostname},{info.Bytes},{Ping.TimeToString(info.Status, info.Time, true)},{info.TTL},{info.Status}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(TracerouteHopInfo.Hop)},{nameof(TracerouteHopInfo.Time1)},{nameof(TracerouteHopInfo.Time2)},{nameof(TracerouteHopInfo.Time3)},{nameof(TracerouteHopInfo.IPAddress)},{nameof(TracerouteHopInfo.Hostname)},{nameof(TracerouteHopInfo.Status1)},{nameof(TracerouteHopInfo.Status2)},{nameof(TracerouteHopInfo.Status3)}"); + stringBuilder.AppendLine($"{nameof(TracerouteHopInfo.Hop)},{nameof(TracerouteHopInfo.Time1)},{nameof(TracerouteHopInfo.Time2)},{nameof(TracerouteHopInfo.Time3)},{nameof(TracerouteHopInfo.IPAddress)},{nameof(TracerouteHopInfo.Hostname)},{nameof(TracerouteHopInfo.Status1)},{nameof(TracerouteHopInfo.Status2)},{nameof(TracerouteHopInfo.Status3)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Hop},{Ping.TimeToString(info.Status1, info.Time1, true)},{Ping.TimeToString(info.Status2, info.Time2, true)},{Ping.TimeToString(info.Status3, info.Time3, true)},{info.IPAddress},{info.Hostname},{info.Status1},{info.Status2},{info.Status3}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.Hop},{Ping.TimeToString(info.Status1, info.Time1, true)},{Ping.TimeToString(info.Status2, info.Time2, true)},{Ping.TimeToString(info.Status3, info.Time3, true)},{info.IPAddress},{info.Hostname},{info.Status1},{info.Status2},{info.Status3}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(DNSLookupRecordInfo.DomainName)},{nameof(DNSLookupRecordInfo.TTL)},{nameof(DNSLookupRecordInfo.Class)},{nameof(DNSLookupRecordInfo.Type)},{nameof(DNSLookupRecordInfo.Result)},{nameof(DNSLookupRecordInfo.Server)},{nameof(DNSLookupRecordInfo.IPEndPoint)}"); + stringBuilder.AppendLine($"{nameof(DNSLookupRecordInfo.DomainName)},{nameof(DNSLookupRecordInfo.TTL)},{nameof(DNSLookupRecordInfo.Class)},{nameof(DNSLookupRecordInfo.Type)},{nameof(DNSLookupRecordInfo.Result)},{nameof(DNSLookupRecordInfo.Server)},{nameof(DNSLookupRecordInfo.IPEndPoint)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.DomainName},{info.TTL},{info.Class},{info.Type},{info.Result},{info.Server},{info.IPEndPoint}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.DomainName},{info.TTL},{info.Class},{info.Type},{info.Result},{info.Server},{info.IPEndPoint}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(SNMPReceivedInfo.OID)},{nameof(SNMPReceivedInfo.Data)}"); + stringBuilder.AppendLine($"{nameof(SNMPReceivedInfo.OID)},{nameof(SNMPReceivedInfo.Data)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.OID},{info.Data}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.OID},{info.Data}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(SNTPLookupResultInfo.Server)},{nameof(SNTPLookupResultInfo.IPEndPoint)},{nameof(SNTPLookupResultInfo.DateTime.NetworkTime)},{nameof(SNTPLookupResultInfo.DateTime.LocalStartTime)},{nameof(SNTPLookupResultInfo.DateTime.LocalEndTime)},{nameof(SNTPLookupResultInfo.DateTime.Offset)},{nameof(SNTPLookupResultInfo.DateTime.RoundTripDelay)}"); + stringBuilder.AppendLine($"{nameof(SNTPLookupResultInfo.Server)},{nameof(SNTPLookupResultInfo.IPEndPoint)},{nameof(SNTPLookupResultInfo.DateTime.NetworkTime)},{nameof(SNTPLookupResultInfo.DateTime.LocalStartTime)},{nameof(SNTPLookupResultInfo.DateTime.LocalEndTime)},{nameof(SNTPLookupResultInfo.DateTime.Offset)},{nameof(SNTPLookupResultInfo.DateTime.RoundTripDelay)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Server},{info.IPEndPoint},{info.DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff")},{info.DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff")},{info.DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff")},{info.DateTime.Offset} s,{info.DateTime.RoundTripDelay} ms"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.Server},{info.IPEndPoint},{info.DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff")},{info.DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff")},{info.DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff")},{info.DateTime.Offset} s,{info.DateTime.RoundTripDelay} ms"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(IPNetworkInfo.Network)},{nameof(IPNetworkInfo.Broadcast)},{nameof(IPNetworkInfo.Total)},{nameof(IPNetworkInfo.Netmask)},{nameof(IPNetworkInfo.Cidr)},{nameof(IPNetworkInfo.FirstUsable)},{nameof(IPNetworkInfo.LastUsable)},{nameof(IPNetworkInfo.Usable)}"); + stringBuilder.AppendLine($"{nameof(IPNetworkInfo.Network)},{nameof(IPNetworkInfo.Broadcast)},{nameof(IPNetworkInfo.Total)},{nameof(IPNetworkInfo.Netmask)},{nameof(IPNetworkInfo.Cidr)},{nameof(IPNetworkInfo.FirstUsable)},{nameof(IPNetworkInfo.LastUsable)},{nameof(IPNetworkInfo.Usable)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Network},{info.Broadcast},{info.Total},{info.Netmask},{info.Cidr},{info.FirstUsable},{info.LastUsable},{info.Usable}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.Network},{info.Broadcast},{info.Total},{info.Netmask},{info.Cidr},{info.FirstUsable},{info.LastUsable},{info.Usable}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(OUIInfo.MACAddress)},{nameof(OUIInfo.Vendor)}"); + stringBuilder.AppendLine($"{nameof(OUIInfo.MACAddress)},{nameof(OUIInfo.Vendor)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.MACAddress},{info.Vendor}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.MACAddress},{info.Vendor}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(PortLookupInfo.Number)},{nameof(PortLookupInfo.Protocol)},{nameof(PortLookupInfo.Service)},{nameof(PortLookupInfo.Description)}"); + stringBuilder.AppendLine($"{nameof(PortLookupInfo.Number)},{nameof(PortLookupInfo.Protocol)},{nameof(PortLookupInfo.Service)},{nameof(PortLookupInfo.Description)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Number},{info.Protocol},{info.Service},{info.Description}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.Number},{info.Protocol},{info.Service},{info.Description}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(ConnectionInfo.Protocol)},{nameof(ConnectionInfo.LocalIPAddress)},{nameof(ConnectionInfo.LocalPort)},{nameof(ConnectionInfo.RemoteIPAddress)},{nameof(ConnectionInfo.RemotePort)},{nameof(ConnectionInfo.TcpState)}"); + stringBuilder.AppendLine($"{nameof(ConnectionInfo.Protocol)},{nameof(ConnectionInfo.LocalIPAddress)},{nameof(ConnectionInfo.LocalPort)},{nameof(ConnectionInfo.RemoteIPAddress)},{nameof(ConnectionInfo.RemotePort)},{nameof(ConnectionInfo.TcpState)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Protocol},{info.LocalIPAddress},{info.LocalPort},{info.RemoteIPAddress},{info.RemotePort},{info.TcpState}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.Protocol},{info.LocalIPAddress},{info.LocalPort},{info.RemoteIPAddress},{info.RemotePort},{info.TcpState}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(ListenerInfo.Protocol)},{nameof(ListenerInfo.IPAddress)},{nameof(ListenerInfo.Port)}"); + stringBuilder.AppendLine($"{nameof(ListenerInfo.Protocol)},{nameof(ListenerInfo.IPAddress)},{nameof(ListenerInfo.Port)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Protocol},{info.IPAddress},{info.Port}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.Protocol},{info.IPAddress},{info.Port}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } - private static void CreateCSV(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); + private static void CreateCSV(IEnumerable collection, string filePath) + { + var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine($"{nameof(ARPInfo.IPAddress)},{nameof(ARPInfo.MACAddress)},{nameof(ARPInfo.IsMulticast)}"); + stringBuilder.AppendLine($"{nameof(ARPInfo.IPAddress)},{nameof(ARPInfo.MACAddress)},{nameof(ARPInfo.IsMulticast)}"); - foreach (var info in collection) - stringBuilder.AppendLine($"{info.IPAddress},{info.MACAddress},{info.IsMulticast}"); + foreach (var info in collection) + stringBuilder.AppendLine($"{info.IPAddress},{info.MACAddress},{info.IsMulticast}"); - System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); - } - #endregion + System.IO.File.WriteAllText(filePath, stringBuilder.ToString()); + } + #endregion - #region CreateXML - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, + #region CreateXML + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, + + new XElement(ApplicationName.IPScanner.ToString(), + new XElement(nameof(HostInfo) + "s", + + from info in collection + select + new XElement(nameof(HostInfo), + new XElement(nameof(WiFiNetworkInfo.BSSID), info.BSSID), + new XElement(nameof(WiFiNetworkInfo.SSID), info.SSID), + new XElement(nameof(WiFiNetworkInfo.ChannelCenterFrequencyInKilohertz), info.ChannelCenterFrequencyInKilohertz), + new XElement(nameof(WiFiNetworkInfo.SignalBars), info.SignalBars), + new XElement(nameof(WiFiNetworkInfo.IsWiFiDirect), info.IsWiFiDirect), + new XElement(nameof(WiFiNetworkInfo.NetworkRssiInDecibelMilliwatts), info.NetworkRssiInDecibelMilliwatts), + new XElement(nameof(WiFiNetworkInfo.PhyKind), info.PhyKind), + new XElement(nameof(WiFiNetworkInfo.NetworkKind), info.NetworkKind), + new XElement(nameof(WiFiNetworkInfo.AuthenticationType), info.AuthenticationType), + new XElement(nameof(WiFiNetworkInfo.EncryptionType), info.EncryptionType), + new XElement(nameof(WiFiNetworkInfo.BeaconInterval), info.BeaconInterval), + new XElement(nameof(WiFiNetworkInfo.Uptime), info.Uptime))))); + + document.Save(filePath); + } + + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, + + new XElement(ApplicationName.IPScanner.ToString(), + new XElement(nameof(HostInfo) + "s", + + from info in collection + select + new XElement(nameof(HostInfo), + new XElement(nameof(PingInfo.IPAddress), info.PingInfo.IPAddress), + new XElement(nameof(HostInfo.Hostname), info.Hostname), + new XElement(nameof(HostInfo.MACAddress), info.MACAddress), + new XElement(nameof(HostInfo.Vendor), info.Vendor), + new XElement(nameof(PingInfo.Bytes), info.PingInfo.Bytes), + new XElement(nameof(PingInfo.Time), Ping.TimeToString(info.PingInfo.Status, info.PingInfo.Time, true)), + new XElement(nameof(PingInfo.TTL), info.PingInfo.TTL), + new XElement(nameof(PingInfo.Status), info.PingInfo.Status))))); + + document.Save(filePath); + } + + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.IPScanner.ToString(), - new XElement(nameof(HostInfo) + "s", + new XElement(ApplicationName.PortScanner.ToString(), + new XElement(nameof(PortInfo) + "s", from info in collection select - new XElement(nameof(HostInfo), - new XElement(nameof(WiFiNetworkInfo.BSSID), info.BSSID), - new XElement(nameof(WiFiNetworkInfo.SSID), info.SSID), - new XElement(nameof(WiFiNetworkInfo.ChannelCenterFrequencyInKilohertz), info.ChannelCenterFrequencyInKilohertz), - new XElement(nameof(WiFiNetworkInfo.SignalBars), info.SignalBars), - new XElement(nameof(WiFiNetworkInfo.IsWiFiDirect), info.IsWiFiDirect), - new XElement(nameof(WiFiNetworkInfo.NetworkRssiInDecibelMilliwatts), info.NetworkRssiInDecibelMilliwatts), - new XElement(nameof(WiFiNetworkInfo.PhyKind), info.PhyKind), - new XElement(nameof(WiFiNetworkInfo.NetworkKind), info.NetworkKind), - new XElement(nameof(WiFiNetworkInfo.AuthenticationType), info.AuthenticationType), - new XElement(nameof(WiFiNetworkInfo.EncryptionType), info.EncryptionType), - new XElement(nameof(WiFiNetworkInfo.BeaconInterval), info.BeaconInterval), - new XElement(nameof(WiFiNetworkInfo.Uptime), info.Uptime))))); - - document.Save(filePath); - } + new XElement(nameof(PortInfo), + new XElement(nameof(PortInfo.IPAddress), info.IPAddress), + new XElement(nameof(PortInfo.Hostname), info.Hostname), + new XElement(nameof(PortInfo.Port), info.Port), + new XElement(nameof(PortLookupInfo.Protocol), info.LookupInfo.Protocol), + new XElement(nameof(PortLookupInfo.Service), info.LookupInfo.Service), + new XElement(nameof(PortLookupInfo.Description), info.LookupInfo.Description), + new XElement(nameof(PortInfo.State), info.State))))); + + document.Save(filePath); + } - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.IPScanner.ToString(), - new XElement(nameof(HostInfo) + "s", + new XElement(ApplicationName.PingMonitor.ToString(), + new XElement(nameof(PingInfo) + "s", from info in collection select - new XElement(nameof(HostInfo), - new XElement(nameof(PingInfo.IPAddress), info.PingInfo.IPAddress), - new XElement(nameof(HostInfo.Hostname), info.Hostname), - new XElement(nameof(HostInfo.MACAddress), info.MACAddress), - new XElement(nameof(HostInfo.Vendor), info.Vendor), - new XElement(nameof(PingInfo.Bytes), info.PingInfo.Bytes), - new XElement(nameof(PingInfo.Time), Ping.TimeToString(info.PingInfo.Status, info.PingInfo.Time, true)), - new XElement(nameof(PingInfo.TTL), info.PingInfo.TTL), - new XElement(nameof(PingInfo.Status), info.PingInfo.Status))))); - - document.Save(filePath); - } + new XElement(nameof(PingInfo), + new XElement(nameof(PingInfo.Timestamp), info.Timestamp), + new XElement(nameof(PingInfo.IPAddress), info.IPAddress), + new XElement(nameof(PingInfo.Hostname), info.Hostname), + new XElement(nameof(PingInfo.Bytes), info.Bytes), + new XElement(nameof(PingInfo.Time), Ping.TimeToString(info.Status, info.Time, true)), + new XElement(nameof(PingInfo.TTL), info.TTL), + new XElement(nameof(PingInfo.Status), info.Status))))); + + document.Save(filePath); + } - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - - new XElement(ApplicationName.PortScanner.ToString(), - new XElement(nameof(PortInfo) + "s", - - from info in collection - select - new XElement(nameof(PortInfo), - new XElement(nameof(PortInfo.IPAddress), info.IPAddress), - new XElement(nameof(PortInfo.Hostname), info.Hostname), - new XElement(nameof(PortInfo.Port), info.Port), - new XElement(nameof(PortLookupInfo.Protocol), info.LookupInfo.Protocol), - new XElement(nameof(PortLookupInfo.Service), info.LookupInfo.Service), - new XElement(nameof(PortLookupInfo.Description), info.LookupInfo.Description), - new XElement(nameof(PortInfo.State), info.State))))); - - document.Save(filePath); - } + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - - new XElement(ApplicationName.PingMonitor.ToString(), - new XElement(nameof(PingInfo) + "s", - - from info in collection - select - new XElement(nameof(PingInfo), - new XElement(nameof(PingInfo.Timestamp), info.Timestamp), - new XElement(nameof(PingInfo.IPAddress), info.IPAddress), - new XElement(nameof(PingInfo.Hostname), info.Hostname), - new XElement(nameof(PingInfo.Bytes), info.Bytes), - new XElement(nameof(PingInfo.Time), Ping.TimeToString(info.Status, info.Time, true)), - new XElement(nameof(PingInfo.TTL), info.TTL), - new XElement(nameof(PingInfo.Status), info.Status))))); - - document.Save(filePath); - } + new XElement(ApplicationName.Traceroute.ToString(), + new XElement(nameof(TracerouteHopInfo) + "s", - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - - new XElement(ApplicationName.Traceroute.ToString(), - new XElement(nameof(TracerouteHopInfo) + "s", - - from info in collection - select - new XElement(nameof(TracerouteHopInfo), - new XElement(nameof(TracerouteHopInfo.Hop), info.Hop), - new XElement(nameof(TracerouteHopInfo.Time1), Ping.TimeToString(info.Status1, info.Time1, true)), - new XElement(nameof(TracerouteHopInfo.Time2), Ping.TimeToString(info.Status2, info.Time2, true)), - new XElement(nameof(TracerouteHopInfo.Time3), Ping.TimeToString(info.Status3, info.Time3, true)), - new XElement(nameof(TracerouteHopInfo.IPAddress), info.IPAddress), - new XElement(nameof(TracerouteHopInfo.Hostname), info.Hostname), - new XElement(nameof(TracerouteHopInfo.Status1), info.Status1), - new XElement(nameof(TracerouteHopInfo.Status2), info.Status2), - new XElement(nameof(TracerouteHopInfo.Status3), info.Status3))))); - - document.Save(filePath); - } + from info in collection + select + new XElement(nameof(TracerouteHopInfo), + new XElement(nameof(TracerouteHopInfo.Hop), info.Hop), + new XElement(nameof(TracerouteHopInfo.Time1), Ping.TimeToString(info.Status1, info.Time1, true)), + new XElement(nameof(TracerouteHopInfo.Time2), Ping.TimeToString(info.Status2, info.Time2, true)), + new XElement(nameof(TracerouteHopInfo.Time3), Ping.TimeToString(info.Status3, info.Time3, true)), + new XElement(nameof(TracerouteHopInfo.IPAddress), info.IPAddress), + new XElement(nameof(TracerouteHopInfo.Hostname), info.Hostname), + new XElement(nameof(TracerouteHopInfo.Status1), info.Status1), + new XElement(nameof(TracerouteHopInfo.Status2), info.Status2), + new XElement(nameof(TracerouteHopInfo.Status3), info.Status3))))); + + document.Save(filePath); + } - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - - new XElement(ApplicationName.DNSLookup.ToString(), - new XElement(nameof(DNSLookupRecordInfo) + "s", - - from info in collection - select - new XElement(nameof(DNSLookupRecordInfo), - new XElement(nameof(DNSLookupRecordInfo.DomainName), info.DomainName), - new XElement(nameof(DNSLookupRecordInfo.TTL), info.TTL), - new XElement(nameof(DNSLookupRecordInfo.Class), info.Class), - new XElement(nameof(DNSLookupRecordInfo.Type), info.Type), - new XElement(nameof(DNSLookupRecordInfo.Result), info.Result), - new XElement(nameof(DNSLookupRecordInfo.Server), info.Server), - new XElement(nameof(DNSLookupRecordInfo.IPEndPoint), info.IPEndPoint))))); - - document.Save(filePath); - } + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, + new XElement(ApplicationName.DNSLookup.ToString(), + new XElement(nameof(DNSLookupRecordInfo) + "s", - new XElement(ApplicationName.SNMP.ToString(), - new XElement(nameof(SNMPReceivedInfo) + "s", + from info in collection + select + new XElement(nameof(DNSLookupRecordInfo), + new XElement(nameof(DNSLookupRecordInfo.DomainName), info.DomainName), + new XElement(nameof(DNSLookupRecordInfo.TTL), info.TTL), + new XElement(nameof(DNSLookupRecordInfo.Class), info.Class), + new XElement(nameof(DNSLookupRecordInfo.Type), info.Type), + new XElement(nameof(DNSLookupRecordInfo.Result), info.Result), + new XElement(nameof(DNSLookupRecordInfo.Server), info.Server), + new XElement(nameof(DNSLookupRecordInfo.IPEndPoint), info.IPEndPoint))))); + + document.Save(filePath); + } - from info in collection - select - new XElement(nameof(SNMPReceivedInfo), - new XElement(nameof(SNMPReceivedInfo.OID), info.OID), - new XElement(nameof(SNMPReceivedInfo.Data), info.Data))))); + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - document.Save(filePath); - } + new XElement(ApplicationName.SNMP.ToString(), + new XElement(nameof(SNMPReceivedInfo) + "s", - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - - new XElement(ApplicationName.SNMP.ToString(), - new XElement(nameof(SNTPLookupResultInfo) + "s", - - from info in collection - select - new XElement(nameof(SNTPLookupResultInfo), - new XElement(nameof(SNTPLookupResultInfo.Server), info.Server), - new XElement(nameof(SNTPLookupResultInfo.IPEndPoint), info.IPEndPoint), - new XElement(nameof(SNTPLookupResultInfo.DateTime.NetworkTime), info.DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff")), - new XElement(nameof(SNTPLookupResultInfo.DateTime.LocalStartTime), info.DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff")), - new XElement(nameof(SNTPLookupResultInfo.DateTime.LocalEndTime), info.DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff")), - new XElement(nameof(SNTPLookupResultInfo.DateTime.Offset), $"{info.DateTime.Offset} s"), - new XElement(nameof(SNTPLookupResultInfo.DateTime.RoundTripDelay), $"{info.DateTime.RoundTripDelay} ms"))))); - - document.Save(filePath); - } + from info in collection + select + new XElement(nameof(SNMPReceivedInfo), + new XElement(nameof(SNMPReceivedInfo.OID), info.OID), + new XElement(nameof(SNMPReceivedInfo.Data), info.Data))))); - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - - new XElement(ApplicationName.SNMP.ToString(), - new XElement(nameof(IPNetworkInfo) + "s", - - from info in collection - select - new XElement(nameof(IPNetworkInfo), - new XElement(nameof(IPNetworkInfo.Network), info.Network), - new XElement(nameof(IPNetworkInfo.Broadcast), info.Broadcast), - new XElement(nameof(IPNetworkInfo.Total), info.Total), - new XElement(nameof(IPNetworkInfo.Netmask), info.Netmask), - new XElement(nameof(IPNetworkInfo.Cidr), info.Cidr), - new XElement(nameof(IPNetworkInfo.FirstUsable), info.FirstUsable), - new XElement(nameof(IPNetworkInfo.LastUsable), info.LastUsable), - new XElement(nameof(IPNetworkInfo.Usable), info.Usable))))); - - document.Save(filePath); - } + document.Save(filePath); + } - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.Lookup.ToString(), - new XElement(nameof(OUIInfo) + "s", + new XElement(ApplicationName.SNMP.ToString(), + new XElement(nameof(SNTPLookupResultInfo) + "s", - from info in collection - select - new XElement(nameof(OUIInfo), - new XElement(nameof(OUIInfo.MACAddress), info.MACAddress), - new XElement(nameof(OUIInfo.Vendor), info.Vendor))))); + from info in collection + select + new XElement(nameof(SNTPLookupResultInfo), + new XElement(nameof(SNTPLookupResultInfo.Server), info.Server), + new XElement(nameof(SNTPLookupResultInfo.IPEndPoint), info.IPEndPoint), + new XElement(nameof(SNTPLookupResultInfo.DateTime.NetworkTime), info.DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff")), + new XElement(nameof(SNTPLookupResultInfo.DateTime.LocalStartTime), info.DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff")), + new XElement(nameof(SNTPLookupResultInfo.DateTime.LocalEndTime), info.DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff")), + new XElement(nameof(SNTPLookupResultInfo.DateTime.Offset), $"{info.DateTime.Offset} s"), + new XElement(nameof(SNTPLookupResultInfo.DateTime.RoundTripDelay), $"{info.DateTime.RoundTripDelay} ms"))))); + + document.Save(filePath); + } - document.Save(filePath); - } + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, + new XElement(ApplicationName.SNMP.ToString(), + new XElement(nameof(IPNetworkInfo) + "s", - new XElement(ApplicationName.Lookup.ToString(), - new XElement(nameof(PortLookupInfo) + "s", + from info in collection + select + new XElement(nameof(IPNetworkInfo), + new XElement(nameof(IPNetworkInfo.Network), info.Network), + new XElement(nameof(IPNetworkInfo.Broadcast), info.Broadcast), + new XElement(nameof(IPNetworkInfo.Total), info.Total), + new XElement(nameof(IPNetworkInfo.Netmask), info.Netmask), + new XElement(nameof(IPNetworkInfo.Cidr), info.Cidr), + new XElement(nameof(IPNetworkInfo.FirstUsable), info.FirstUsable), + new XElement(nameof(IPNetworkInfo.LastUsable), info.LastUsable), + new XElement(nameof(IPNetworkInfo.Usable), info.Usable))))); + + document.Save(filePath); + } - from info in collection - select - new XElement(nameof(PortLookupInfo), - new XElement(nameof(PortLookupInfo.Number), info.Number), - new XElement(nameof(PortLookupInfo.Protocol), info.Protocol), - new XElement(nameof(PortLookupInfo.Service), info.Service), - new XElement(nameof(PortLookupInfo.Description), info.Description))))); + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - document.Save(filePath); - } + new XElement(ApplicationName.Lookup.ToString(), + new XElement(nameof(OUIInfo) + "s", - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - - new XElement(ApplicationName.Connections.ToString(), - new XElement(nameof(ConnectionInfo) + "s", - - from info in collection - select - new XElement(nameof(ConnectionInfo), - new XElement(nameof(ConnectionInfo.Protocol), info.Protocol), - new XElement(nameof(ConnectionInfo.LocalIPAddress), info.LocalIPAddress), - new XElement(nameof(ConnectionInfo.LocalPort), info.LocalPort), - new XElement(nameof(ConnectionInfo.RemoteIPAddress), info.RemoteIPAddress), - new XElement(nameof(ConnectionInfo.RemotePort), info.RemotePort), - new XElement(nameof(ConnectionInfo.TcpState), info.TcpState))))); - - document.Save(filePath); - } + from info in collection + select + new XElement(nameof(OUIInfo), + new XElement(nameof(OUIInfo.MACAddress), info.MACAddress), + new XElement(nameof(OUIInfo.Vendor), info.Vendor))))); - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, + document.Save(filePath); + } + + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.Listeners.ToString(), - new XElement(nameof(ListenerInfo) + "s", + new XElement(ApplicationName.Lookup.ToString(), + new XElement(nameof(PortLookupInfo) + "s", - from info in collection - select - new XElement(nameof(ListenerInfo), - new XElement(nameof(ListenerInfo.Protocol), info.Protocol), - new XElement(nameof(ListenerInfo.IPAddress), info.IPAddress), - new XElement(nameof(ListenerInfo.Port), info.Port))))); + from info in collection + select + new XElement(nameof(PortLookupInfo), + new XElement(nameof(PortLookupInfo.Number), info.Number), + new XElement(nameof(PortLookupInfo.Protocol), info.Protocol), + new XElement(nameof(PortLookupInfo.Service), info.Service), + new XElement(nameof(PortLookupInfo.Description), info.Description))))); - document.Save(filePath); - } + document.Save(filePath); + } - public static void CreateXML(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.ARPTable.ToString(), - new XElement(nameof(ARPInfo) + "s", + new XElement(ApplicationName.Connections.ToString(), + new XElement(nameof(ConnectionInfo) + "s", - from info in collection - select - new XElement(nameof(ARPInfo), - new XElement(nameof(ARPInfo.IPAddress), info.IPAddress), - new XElement(nameof(ARPInfo.MACAddress), info.MACAddress), - new XElement(nameof(ARPInfo.IsMulticast), info.IsMulticast))))); + from info in collection + select + new XElement(nameof(ConnectionInfo), + new XElement(nameof(ConnectionInfo.Protocol), info.Protocol), + new XElement(nameof(ConnectionInfo.LocalIPAddress), info.LocalIPAddress), + new XElement(nameof(ConnectionInfo.LocalPort), info.LocalPort), + new XElement(nameof(ConnectionInfo.RemoteIPAddress), info.RemoteIPAddress), + new XElement(nameof(ConnectionInfo.RemotePort), info.RemotePort), + new XElement(nameof(ConnectionInfo.TcpState), info.TcpState))))); + + document.Save(filePath); + } - document.Save(filePath); - } - #endregion + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - #region CreateJSON - // This might be a horror to maintain, but i have no other idea... - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + new XElement(ApplicationName.Listeners.ToString(), + new XElement(nameof(ListenerInfo) + "s", - for (var i = 0; i < collection.Count; i++) - { - jsonData[i] = new - { - collection[i].BSSID, - collection[i].SSID, - ChannelCenterFrequencyInKilohertz = collection[i].SSID.ToString(), - SignalBars = collection[i].SignalBars.ToString(), - IsWiFiDirect = collection[i].IsWiFiDirect.ToString(), - NetworkRssiInDecibelMilliwatts = collection[i].NetworkRssiInDecibelMilliwatts.ToString(), - PhyKind = collection[i].PhyKind.ToString(), - NetworkKind = collection[i].NetworkKind.ToString(), - AuthenticationType = collection[i].AuthenticationType.ToString(), - EncryptionType = collection[i].EncryptionType.ToString(), - BeaconInterval = collection[i].BeaconInterval.ToString(), - Uptime = collection[i].Uptime.ToString() - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); - } + from info in collection + select + new XElement(nameof(ListenerInfo), + new XElement(nameof(ListenerInfo.Protocol), info.Protocol), + new XElement(nameof(ListenerInfo.IPAddress), info.IPAddress), + new XElement(nameof(ListenerInfo.Port), info.Port))))); - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + document.Save(filePath); + } - for (var i = 0; i < collection.Count; i++) - { - jsonData[i] = new - { - IPAddress = collection[i].PingInfo.IPAddress.ToString(), - collection[i].Hostname, - MACAddress = collection[i].MACAddress?.ToString(), - collection[i].Vendor, - collection[i].PingInfo.Bytes, - Time = Ping.TimeToString(collection[i].PingInfo.Status, collection[i].PingInfo.Time, true), - collection[i].PingInfo.TTL, - Status = collection[i].PingInfo.Status.ToString() - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); - } + public static void CreateXML(IEnumerable collection, string filePath) + { + var document = new XDocument(DefaultXDeclaration, - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + new XElement(ApplicationName.ARPTable.ToString(), + new XElement(nameof(ARPInfo) + "s", + + from info in collection + select + new XElement(nameof(ARPInfo), + new XElement(nameof(ARPInfo.IPAddress), info.IPAddress), + new XElement(nameof(ARPInfo.MACAddress), info.MACAddress), + new XElement(nameof(ARPInfo.IsMulticast), info.IsMulticast))))); + + document.Save(filePath); + } + #endregion + + #region CreateJSON + // This might be a horror to maintain, but i have no other idea... + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; - for (var i = 0; i < collection.Count; i++) + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - IPAddress = collection[i].IPAddress.ToString(), - collection[i].Hostname, - collection[i].Port, - Protocol = collection[i].LookupInfo.Protocol.ToString(), - collection[i].LookupInfo.Service, - collection[i].LookupInfo.Description, - Status = collection[i].State.ToString() - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].BSSID, + collection[i].SSID, + ChannelCenterFrequencyInKilohertz = collection[i].SSID.ToString(), + SignalBars = collection[i].SignalBars.ToString(), + IsWiFiDirect = collection[i].IsWiFiDirect.ToString(), + NetworkRssiInDecibelMilliwatts = collection[i].NetworkRssiInDecibelMilliwatts.ToString(), + PhyKind = collection[i].PhyKind.ToString(), + NetworkKind = collection[i].NetworkKind.ToString(), + AuthenticationType = collection[i].AuthenticationType.ToString(), + EncryptionType = collection[i].EncryptionType.ToString(), + BeaconInterval = collection[i].BeaconInterval.ToString(), + Uptime = collection[i].Uptime.ToString() + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } - for (var i = 0; i < collection.Count; i++) + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; + + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - collection[i].Timestamp, - IPAddress = collection[i].IPAddress.ToString(), - collection[i].Hostname, - collection[i].Bytes, - Time = Ping.TimeToString(collection[i].Status, collection[i].Time, true), - collection[i].TTL, - Status = collection[i].Status.ToString() - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + IPAddress = collection[i].PingInfo.IPAddress.ToString(), + collection[i].Hostname, + MACAddress = collection[i].MACAddress?.ToString(), + collection[i].Vendor, + collection[i].PingInfo.Bytes, + Time = Ping.TimeToString(collection[i].PingInfo.Status, collection[i].PingInfo.Time, true), + collection[i].PingInfo.TTL, + Status = collection[i].PingInfo.Status.ToString() + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; - for (var i = 0; i < collection.Count; i++) + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - collection[i].Hop, - Time1 = Ping.TimeToString(collection[i].Status1, collection[i].Time1, true), - Time2 = Ping.TimeToString(collection[i].Status2, collection[i].Time2, true), - Time3 = Ping.TimeToString(collection[i].Status3, collection[i].Time3, true), - IPAddress = collection[i].IPAddress.ToString(), - collection[i].Hostname, - Status1 = collection[i].Status1.ToString(), - Status2 = collection[i].Status2.ToString(), - Status3 = collection[i].Status3.ToString() - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + IPAddress = collection[i].IPAddress.ToString(), + collection[i].Hostname, + collection[i].Port, + Protocol = collection[i].LookupInfo.Protocol.ToString(), + collection[i].LookupInfo.Service, + collection[i].LookupInfo.Description, + Status = collection[i].State.ToString() + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } - for (var i = 0; i < collection.Count; i++) + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; + + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - collection[i].DomainName, - collection[i].TTL, - collection[i].Class, - collection[i].Type, - collection[i].Result, - collection[i].Server, - collection[i].IPEndPoint - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].Timestamp, + IPAddress = collection[i].IPAddress.ToString(), + collection[i].Hostname, + collection[i].Bytes, + Time = Ping.TimeToString(collection[i].Status, collection[i].Time, true), + collection[i].TTL, + Status = collection[i].Status.ToString() + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; - for (var i = 0; i < collection.Count; i++) + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - collection[i].OID, - collection[i].Data - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].Hop, + Time1 = Ping.TimeToString(collection[i].Status1, collection[i].Time1, true), + Time2 = Ping.TimeToString(collection[i].Status2, collection[i].Time2, true), + Time3 = Ping.TimeToString(collection[i].Status3, collection[i].Time3, true), + IPAddress = collection[i].IPAddress.ToString(), + collection[i].Hostname, + Status1 = collection[i].Status1.ToString(), + Status2 = collection[i].Status2.ToString(), + Status3 = collection[i].Status3.ToString() + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } - for (var i = 0; i < collection.Count; i++) + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; + + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - collection[i].Server, - collection[i].IPEndPoint, - NetworkTime = collection[i].DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff"), - LocalStartTime = collection[i].DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff"), - LocalEndTime = collection[i].DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff"), - Offset = $"{collection[i].DateTime.Offset} s", - RoundTripDelay = $"{collection[i].DateTime.RoundTripDelay} ms", - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].DomainName, + collection[i].TTL, + collection[i].Class, + collection[i].Type, + collection[i].Result, + collection[i].Server, + collection[i].IPEndPoint + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } - for (var i = 0; i < collection.Count; i++) + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; + + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - Network = collection[i].Network.ToString(), - Broadcast = collection[i].Broadcast.ToString(), - collection[i].Total, - Netmask = collection[i].Netmask.ToString(), - collection[i].Cidr, - FirstUsable = collection[i].FirstUsable.ToString(), - LastUsable = collection[i].LastUsable.ToString(), - collection[i].Usable - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].OID, + collection[i].Data + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; - for (var i = 0; i < collection.Count; i++) + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - collection[i].MACAddress, - collection[i].Vendor - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].Server, + collection[i].IPEndPoint, + NetworkTime = collection[i].DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff"), + LocalStartTime = collection[i].DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff"), + LocalEndTime = collection[i].DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff"), + Offset = $"{collection[i].DateTime.Offset} s", + RoundTripDelay = $"{collection[i].DateTime.RoundTripDelay} ms", + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; - for (var i = 0; i < collection.Count; i++) + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - collection[i].Number, - Protocol = collection[i].Protocol.ToString(), - collection[i].Service, - collection[i].Description - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Network = collection[i].Network.ToString(), + Broadcast = collection[i].Broadcast.ToString(), + collection[i].Total, + Netmask = collection[i].Netmask.ToString(), + collection[i].Cidr, + FirstUsable = collection[i].FirstUsable.ToString(), + LastUsable = collection[i].LastUsable.ToString(), + collection[i].Usable + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; - for (var i = 0; i < collection.Count; i++) + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - Protocol = collection[i].Protocol.ToString(), - LocalIPAddress = collection[i].LocalIPAddress.ToString(), - collection[i].LocalPort, - RemoteIPAddress = collection[i].RemoteIPAddress.ToString(), - collection[i].RemotePort, - TcpState = collection[i].TcpState.ToString() - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].MACAddress, + collection[i].Vendor + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } - for (var i = 0; i < collection.Count; i++) + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; + + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - Protocol = collection[i].Protocol.ToString(), - IPAddress = collection[i].IPAddress.ToString(), - collection[i].Port - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + collection[i].Number, + Protocol = collection[i].Protocol.ToString(), + collection[i].Service, + collection[i].Description + }; } - public static void CreateJSON(ObservableCollection collection, string filePath) - { - var jsonData = new object[collection.Count]; + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; - for (var i = 0; i < collection.Count; i++) + for (var i = 0; i < collection.Count; i++) + { + jsonData[i] = new { - jsonData[i] = new - { - IPAddress = collection[i].IPAddress.ToString(), - MACAddress = collection[i].MACAddress.ToString(), - collection[i].IsMulticast - }; - } - - System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Protocol = collection[i].Protocol.ToString(), + LocalIPAddress = collection[i].LocalIPAddress.ToString(), + collection[i].LocalPort, + RemoteIPAddress = collection[i].RemoteIPAddress.ToString(), + collection[i].RemotePort, + TcpState = collection[i].TcpState.ToString() + }; } - #endregion - #region CreateTXT + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } - public static void CreateTXT(string content, string filePath) + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; + + for (var i = 0; i < collection.Count; i++) { - System.IO.File.WriteAllText(filePath, content); + jsonData[i] = new + { + Protocol = collection[i].Protocol.ToString(), + IPAddress = collection[i].IPAddress.ToString(), + collection[i].Port + }; } - #endregion - public static string GetFileExtensionAsString(ExportFileType fileExtension) + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + public static void CreateJSON(ObservableCollection collection, string filePath) + { + var jsonData = new object[collection.Count]; + + for (var i = 0; i < collection.Count; i++) { - return fileExtension switch + jsonData[i] = new { - ExportFileType.CSV => "CSV", - ExportFileType.XML => "XML", - ExportFileType.JSON => "JSON", - ExportFileType.TXT => "TXT", - _ => string.Empty, + IPAddress = collection[i].IPAddress.ToString(), + MACAddress = collection[i].MACAddress.ToString(), + collection[i].IsMulticast }; } - #endregion + + System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + #endregion + + #region CreateTXT + + public static void CreateTXT(string content, string filePath) + { + System.IO.File.WriteAllText(filePath, content); + } + #endregion + + public static string GetFileExtensionAsString(ExportFileType fileExtension) + { + return fileExtension switch + { + ExportFileType.CSV => "CSV", + ExportFileType.XML => "XML", + ExportFileType.JSON => "JSON", + ExportFileType.TXT => "TXT", + _ => string.Empty, + }; } + #endregion } diff --git a/Source/NETworkManager.Models/Lookup/OUIInfo.cs b/Source/NETworkManager.Models/Lookup/OUIInfo.cs index d268317500..29d8a0079d 100644 --- a/Source/NETworkManager.Models/Lookup/OUIInfo.cs +++ b/Source/NETworkManager.Models/Lookup/OUIInfo.cs @@ -1,17 +1,16 @@ -namespace NETworkManager.Models.Lookup +namespace NETworkManager.Models.Lookup; + +public class OUIInfo { - public class OUIInfo - { - public string MACAddress { get; set; } - public string Vendor { get; set; } + public string MACAddress { get; set; } + public string Vendor { get; set; } - public string MACAddressString => MACAddress.Replace("-", "").Replace(":", ""); + public string MACAddressString => MACAddress.Replace("-", "").Replace(":", ""); - public OUIInfo(string macAddress, string vendor) - { - MACAddress = macAddress; - Vendor = vendor; - } + public OUIInfo(string macAddress, string vendor) + { + MACAddress = macAddress; + Vendor = vendor; } } diff --git a/Source/NETworkManager.Models/Lookup/OUILookup.cs b/Source/NETworkManager.Models/Lookup/OUILookup.cs index 0448a2fa23..3bf478e5a2 100644 --- a/Source/NETworkManager.Models/Lookup/OUILookup.cs +++ b/Source/NETworkManager.Models/Lookup/OUILookup.cs @@ -7,68 +7,67 @@ using System.Xml; using System.Reflection; -namespace NETworkManager.Models.Lookup +namespace NETworkManager.Models.Lookup; + +public static class OUILookup { - public static class OUILookup + #region Variables + private static readonly string OuiFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Resources", "OUI.xml"); + + private static readonly List OUIInfoList; + private static readonly Lookup OUIInfoLookup; + #endregion + + #region Constructor + static OUILookup() { - #region Variables - private static readonly string OuiFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Resources", "OUI.xml"); + OUIInfoList = new List(); - private static readonly List OUIInfoList; - private static readonly Lookup OUIInfoLookup; - #endregion + var document = new XmlDocument(); + document.Load(OuiFilePath); - #region Constructor - static OUILookup() + foreach (XmlNode node in document.SelectNodes("/OUIs/OUI")) { - OUIInfoList = new List(); - - var document = new XmlDocument(); - document.Load(OuiFilePath); + if (node != null) + OUIInfoList.Add(new OUIInfo(node.SelectSingleNode("MACAddress")?.InnerText, node.SelectSingleNode("Vendor")?.InnerText)); + } - foreach (XmlNode node in document.SelectNodes("/OUIs/OUI")) - { - if (node != null) - OUIInfoList.Add(new OUIInfo(node.SelectSingleNode("MACAddress")?.InnerText, node.SelectSingleNode("Vendor")?.InnerText)); - } + OUIInfoLookup = (Lookup)OUIInfoList.ToLookup(x => x.MACAddress); + } + #endregion - OUIInfoLookup = (Lookup)OUIInfoList.ToLookup(x => x.MACAddress); - } - #endregion + #region Methods + public static Task> LookupAsync(string macAddress) + { + return Task.Run(() => Lookup(macAddress)); + } - #region Methods - public static Task> LookupAsync(string macAddress) - { - return Task.Run(() => Lookup(macAddress)); - } + public static List Lookup(string macAddress) + { + var ouiKey = Regex.Replace(macAddress, "[-|:|.]", "").Substring(0, 6).ToUpper(); - public static List Lookup(string macAddress) - { - var ouiKey = Regex.Replace(macAddress, "[-|:|.]", "").Substring(0, 6).ToUpper(); + return OUIInfoLookup[ouiKey].ToList(); + } - return OUIInfoLookup[ouiKey].ToList(); - } + public static Task> LookupByVendorAsync(List vendors) + { + return Task.Run(() => LookupByVendor(vendors)); + } - public static Task> LookupByVendorAsync(List vendors) - { - return Task.Run(() => LookupByVendor(vendors)); - } + public static List LookupByVendor(List vendors) + { + var list = new List(); - public static List LookupByVendor(List vendors) + foreach (var info in OUIInfoList) { - var list = new List(); - - foreach (var info in OUIInfoList) + foreach (var vendor in vendors) { - foreach (var vendor in vendors) - { - if (info.Vendor.IndexOf(vendor, StringComparison.OrdinalIgnoreCase) > -1) - list.Add(info); - } + if (info.Vendor.IndexOf(vendor, StringComparison.OrdinalIgnoreCase) > -1) + list.Add(info); } - - return list; } - #endregion + + return list; } + #endregion } diff --git a/Source/NETworkManager.Models/Lookup/PortLookup.Protocol.cs b/Source/NETworkManager.Models/Lookup/PortLookup.Protocol.cs index c89fa9942b..34652671e2 100644 --- a/Source/NETworkManager.Models/Lookup/PortLookup.Protocol.cs +++ b/Source/NETworkManager.Models/Lookup/PortLookup.Protocol.cs @@ -1,13 +1,12 @@ -namespace NETworkManager.Models.Lookup +namespace NETworkManager.Models.Lookup; + +public static partial class PortLookup { - public static partial class PortLookup + public enum Protocol { - public enum Protocol - { - Tcp, - Udp, - Sctp, - Dccp - } + Tcp, + Udp, + Sctp, + Dccp } } diff --git a/Source/NETworkManager.Models/Lookup/PortLookup.cs b/Source/NETworkManager.Models/Lookup/PortLookup.cs index ef6cebe03d..fc19829fcf 100644 --- a/Source/NETworkManager.Models/Lookup/PortLookup.cs +++ b/Source/NETworkManager.Models/Lookup/PortLookup.cs @@ -7,73 +7,72 @@ using System.Reflection; using System.Diagnostics; -namespace NETworkManager.Models.Lookup +namespace NETworkManager.Models.Lookup; + +public static partial class PortLookup { - public static partial class PortLookup + #region Variables + private static readonly string PortsFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Resources", "Ports.xml"); + + private static readonly List PortList; + private static readonly Lookup Ports; + #endregion + + #region Constructor + static PortLookup() { - #region Variables - private static readonly string PortsFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Resources", "Ports.xml"); + PortList = new List(); - private static readonly List PortList; - private static readonly Lookup Ports; - #endregion + var document = new XmlDocument(); + document.Load(PortsFilePath); - #region Constructor - static PortLookup() + foreach (XmlNode node in document.SelectNodes("/Ports/Port")) { - PortList = new List(); + if (node == null) + continue; - var document = new XmlDocument(); - document.Load(PortsFilePath); + int.TryParse(node.SelectSingleNode("Number")?.InnerText, out var port); + Enum.TryParse(node.SelectSingleNode("Protocol")?.InnerText, true, out var protocol); - foreach (XmlNode node in document.SelectNodes("/Ports/Port")) - { - if (node == null) - continue; - - int.TryParse(node.SelectSingleNode("Number")?.InnerText, out var port); - Enum.TryParse(node.SelectSingleNode("Protocol")?.InnerText, true, out var protocol); + PortList.Add(new PortLookupInfo(port, protocol, node.SelectSingleNode("Name")?.InnerText, node.SelectSingleNode("Description")?.InnerText)); + } - PortList.Add(new PortLookupInfo(port, protocol, node.SelectSingleNode("Name")?.InnerText, node.SelectSingleNode("Description")?.InnerText)); - } + Ports = (Lookup)PortList.ToLookup(x => x.Number); + } + #endregion - Ports = (Lookup)PortList.ToLookup(x => x.Number); - } - #endregion + #region Methods + public static Task> LookupAsync(int port) + { + return Task.Run(() => Lookup(port)); + } - #region Methods - public static Task> LookupAsync(int port) - { - return Task.Run(() => Lookup(port)); - } + public static List Lookup(int port) + { + return Ports[port].ToList(); + } - public static List Lookup(int port) - { - return Ports[port].ToList(); - } + public static Task> LookupByServiceAsync(List portsByService) + { + return Task.Run(() => LookupByService(portsByService)); + } - public static Task> LookupByServiceAsync(List portsByService) - { - return Task.Run(() => LookupByService(portsByService)); - } + public static List LookupByService(List portsByService) + { + var list = new List(); - public static List LookupByService(List portsByService) + foreach (var info in PortList) { - var list = new List(); - - foreach (var info in PortList) + foreach (var portByService in portsByService) { - foreach (var portByService in portsByService) - { - if (info.Service.IndexOf(portByService, StringComparison.OrdinalIgnoreCase) > -1 || info.Description.IndexOf(portByService, StringComparison.OrdinalIgnoreCase) > -1) - list.Add(info); - } + if (info.Service.IndexOf(portByService, StringComparison.OrdinalIgnoreCase) > -1 || info.Description.IndexOf(portByService, StringComparison.OrdinalIgnoreCase) > -1) + list.Add(info); } + } - return list; + return list; - } + } #endregion - } } diff --git a/Source/NETworkManager.Models/Lookup/PortLookupInfo.cs b/Source/NETworkManager.Models/Lookup/PortLookupInfo.cs index c876b5074c..466b291962 100644 --- a/Source/NETworkManager.Models/Lookup/PortLookupInfo.cs +++ b/Source/NETworkManager.Models/Lookup/PortLookupInfo.cs @@ -1,18 +1,17 @@ -namespace NETworkManager.Models.Lookup +namespace NETworkManager.Models.Lookup; + +public class PortLookupInfo { - public class PortLookupInfo - { - public int Number { get; set; } - public PortLookup.Protocol Protocol { get; set; } - public string Service { get; set; } - public string Description { get; set; } + public int Number { get; set; } + public PortLookup.Protocol Protocol { get; set; } + public string Service { get; set; } + public string Description { get; set; } - public PortLookupInfo(int number, PortLookup.Protocol protocol, string service, string description) - { - Number = number; - Protocol = protocol; - Service = service; - Description = description; - } - } + public PortLookupInfo(int number, PortLookup.Protocol protocol, string service, string description) + { + Number = number; + Protocol = protocol; + Service = service; + Description = description; + } } diff --git a/Source/NETworkManager.Models/Network/ARP.cs b/Source/NETworkManager.Models/Network/ARP.cs index d69e0f753b..347189eb67 100644 --- a/Source/NETworkManager.Models/Network/ARP.cs +++ b/Source/NETworkManager.Models/Network/ARP.cs @@ -10,207 +10,206 @@ using System.Runtime.InteropServices; using System.Threading.Tasks; -namespace NETworkManager.Models.Network -{ - public class ARP +namespace NETworkManager.Models.Network; + +public class ARP +{ + #region Variables + // The max number of physical addresses. + private const int MAXLEN_PHYSADDR = 8; + + // Define the MIB_IPNETROW structure. + [StructLayout(LayoutKind.Sequential)] + private struct MIB_IPNETROW { - #region Variables - // The max number of physical addresses. - private const int MAXLEN_PHYSADDR = 8; + [MarshalAs(UnmanagedType.U4)] + public int dwIndex; + [MarshalAs(UnmanagedType.U4)] + public int dwPhysAddrLen; + [MarshalAs(UnmanagedType.U1)] + public byte mac0; + [MarshalAs(UnmanagedType.U1)] + public byte mac1; + [MarshalAs(UnmanagedType.U1)] + public byte mac2; + [MarshalAs(UnmanagedType.U1)] + public byte mac3; + [MarshalAs(UnmanagedType.U1)] + public byte mac4; + [MarshalAs(UnmanagedType.U1)] + public byte mac5; + [MarshalAs(UnmanagedType.U1)] + public byte mac6; + [MarshalAs(UnmanagedType.U1)] + public byte mac7; + [MarshalAs(UnmanagedType.U4)] + public int dwAddr; + [MarshalAs(UnmanagedType.U4)] + public int dwType; + } - // Define the MIB_IPNETROW structure. - [StructLayout(LayoutKind.Sequential)] - private struct MIB_IPNETROW - { - [MarshalAs(UnmanagedType.U4)] - public int dwIndex; - [MarshalAs(UnmanagedType.U4)] - public int dwPhysAddrLen; - [MarshalAs(UnmanagedType.U1)] - public byte mac0; - [MarshalAs(UnmanagedType.U1)] - public byte mac1; - [MarshalAs(UnmanagedType.U1)] - public byte mac2; - [MarshalAs(UnmanagedType.U1)] - public byte mac3; - [MarshalAs(UnmanagedType.U1)] - public byte mac4; - [MarshalAs(UnmanagedType.U1)] - public byte mac5; - [MarshalAs(UnmanagedType.U1)] - public byte mac6; - [MarshalAs(UnmanagedType.U1)] - public byte mac7; - [MarshalAs(UnmanagedType.U4)] - public int dwAddr; - [MarshalAs(UnmanagedType.U4)] - public int dwType; - } + // Declare the GetIpNetTable function. + [DllImport("IpHlpApi.dll")] + [return: MarshalAs(UnmanagedType.U4)] + static extern int GetIpNetTable(IntPtr pIpNetTable, [MarshalAs(UnmanagedType.U4)] ref int pdwSize, bool bOrder); + + [DllImport("IpHlpApi.dll", SetLastError = true, CharSet = CharSet.Auto)] + internal static extern int FreeMibTable(IntPtr plpNetTable); + + // The insufficient buffer error. + const int ERROR_INSUFFICIENT_BUFFER = 122; + #endregion - // Declare the GetIpNetTable function. - [DllImport("IpHlpApi.dll")] - [return: MarshalAs(UnmanagedType.U4)] - static extern int GetIpNetTable(IntPtr pIpNetTable, [MarshalAs(UnmanagedType.U4)] ref int pdwSize, bool bOrder); + #region Events + public event EventHandler UserHasCanceled; - [DllImport("IpHlpApi.dll", SetLastError = true, CharSet = CharSet.Auto)] - internal static extern int FreeMibTable(IntPtr plpNetTable); + protected virtual void OnUserHasCanceled() + { + UserHasCanceled?.Invoke(this, EventArgs.Empty); + } + #endregion - // The insufficient buffer error. - const int ERROR_INSUFFICIENT_BUFFER = 122; - #endregion + #region Methods + public static Task> GetTableAsync() + { + return Task.Run(() => GetTable()); + } - #region Events - public event EventHandler UserHasCanceled; + public static List GetTable() + { + var list = new List(); - protected virtual void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - #endregion + // The number of bytes needed. + var bytesNeeded = 0; - #region Methods - public static Task> GetTableAsync() + // The result from the API call. + var result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); + + // Call the function, expecting an insufficient buffer. + if (result != ERROR_INSUFFICIENT_BUFFER) { - return Task.Run(() => GetTable()); + // Throw an exception. + throw new Win32Exception(result); } - public static List GetTable() - { - var list = new List(); + // Allocate the memory, do it in a try/finally block, to ensure + // that it is released. + var buffer = IntPtr.Zero; - // The number of bytes needed. - var bytesNeeded = 0; + // Try/finally. + try + { + // Allocate the memory. + buffer = Marshal.AllocCoTaskMem(bytesNeeded); - // The result from the API call. - var result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); + // Make the call again. If it did not succeed, then + // raise an error. + result = GetIpNetTable(buffer, ref bytesNeeded, false); - // Call the function, expecting an insufficient buffer. - if (result != ERROR_INSUFFICIENT_BUFFER) + // If the result is not 0 (no error), then throw an exception. + if (result != 0) { // Throw an exception. throw new Win32Exception(result); } - // Allocate the memory, do it in a try/finally block, to ensure - // that it is released. - var buffer = IntPtr.Zero; + // Now we have the buffer, we have to marshal it. We can read + // the first 4 bytes to get the length of the buffer. + var entries = Marshal.ReadInt32(buffer); + + // Increment the memory pointer by the size of the int. + var currentBuffer = new IntPtr(buffer.ToInt64() + + Marshal.SizeOf(typeof(int))); - // Try/finally. - try + // Allocate an array of entries. + var table = new MIB_IPNETROW[entries]; + + // Cycle through the entries. + for (var i = 0; i < entries; i++) { - // Allocate the memory. - buffer = Marshal.AllocCoTaskMem(bytesNeeded); - - // Make the call again. If it did not succeed, then - // raise an error. - result = GetIpNetTable(buffer, ref bytesNeeded, false); - - // If the result is not 0 (no error), then throw an exception. - if (result != 0) - { - // Throw an exception. - throw new Win32Exception(result); - } - - // Now we have the buffer, we have to marshal it. We can read - // the first 4 bytes to get the length of the buffer. - var entries = Marshal.ReadInt32(buffer); - - // Increment the memory pointer by the size of the int. - var currentBuffer = new IntPtr(buffer.ToInt64() + - Marshal.SizeOf(typeof(int))); - - // Allocate an array of entries. - var table = new MIB_IPNETROW[entries]; - - // Cycle through the entries. - for (var i = 0; i < entries; i++) - { - // Call PtrToStructure, getting the structure information. - table[i] = (MIB_IPNETROW)Marshal.PtrToStructure(new - IntPtr(currentBuffer.ToInt64() + (i * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); - } - - var virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }); - var broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }); - - for (var i = 0; i < entries; i++) - { - var row = table[i]; - - var ipAddress = new IPAddress(BitConverter.GetBytes(row.dwAddr)); - var macAddress = new PhysicalAddress(new[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 }); - - // Filter 0.0.0.0.0.0, 255.255.255.255.255.255 - if (!macAddress.Equals(virtualMAC) && !macAddress.Equals(broadcastMAC)) - list.Add(new ARPInfo(ipAddress, macAddress, ipAddress.IsIPv6Multicast || IPv4Address.IsMulticast(ipAddress))); - } - - return list; + // Call PtrToStructure, getting the structure information. + table[i] = (MIB_IPNETROW)Marshal.PtrToStructure(new + IntPtr(currentBuffer.ToInt64() + (i * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } - finally + + var virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }); + var broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }); + + for (var i = 0; i < entries; i++) { - // Release the memory. - FreeMibTable(buffer); + var row = table[i]; + + var ipAddress = new IPAddress(BitConverter.GetBytes(row.dwAddr)); + var macAddress = new PhysicalAddress(new[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 }); + + // Filter 0.0.0.0.0.0, 255.255.255.255.255.255 + if (!macAddress.Equals(virtualMAC) && !macAddress.Equals(broadcastMAC)) + list.Add(new ARPInfo(ipAddress, macAddress, ipAddress.IsIPv6Multicast || IPv4Address.IsMulticast(ipAddress))); } + + return list; } + finally + { + // Release the memory. + FreeMibTable(buffer); + } + } - private void RunPSCommand(string command) + private void RunPSCommand(string command) + { + try { - try - { - PowerShellHelper.ExecuteCommand(command, true); - } - catch (Win32Exception win32Ex) + PowerShellHelper.ExecuteCommand(command, true); + } + catch (Win32Exception win32Ex) + { + switch (win32Ex.NativeErrorCode) { - switch (win32Ex.NativeErrorCode) - { - case 1223: - OnUserHasCanceled(); - break; - default: - throw; - } + case 1223: + OnUserHasCanceled(); + break; + default: + throw; } } + } - // MAC separated with "-" - public Task AddEntryAsync(string ipAddress, string macAddress) - { - return Task.Run(() => AddEntry(ipAddress, macAddress)); - } + // MAC separated with "-" + public Task AddEntryAsync(string ipAddress, string macAddress) + { + return Task.Run(() => AddEntry(ipAddress, macAddress)); + } - private void AddEntry(string ipAddress, string macAddress) - { - var command = $"arp -s {ipAddress} {macAddress}"; + private void AddEntry(string ipAddress, string macAddress) + { + var command = $"arp -s {ipAddress} {macAddress}"; - RunPSCommand(command); - } + RunPSCommand(command); + } - public Task DeleteEntryAsync(string ipAddress) - { - return Task.Run(() => DeleteEntry(ipAddress)); - } + public Task DeleteEntryAsync(string ipAddress) + { + return Task.Run(() => DeleteEntry(ipAddress)); + } - private void DeleteEntry(string ipAddress) - { - var command = $"arp -d {ipAddress}"; + private void DeleteEntry(string ipAddress) + { + var command = $"arp -d {ipAddress}"; - RunPSCommand(command); - } + RunPSCommand(command); + } - public Task DeleteTableAsync() - { - return Task.Run(() => DeleteTable()); - } + public Task DeleteTableAsync() + { + return Task.Run(() => DeleteTable()); + } - private void DeleteTable() - { - const string command = "netsh interface ip delete arpcache"; + private void DeleteTable() + { + const string command = "netsh interface ip delete arpcache"; - RunPSCommand(command); - } - #endregion + RunPSCommand(command); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/ARPInfo.cs b/Source/NETworkManager.Models/Network/ARPInfo.cs index 4704b2a2e0..cd942f7044 100644 --- a/Source/NETworkManager.Models/Network/ARPInfo.cs +++ b/Source/NETworkManager.Models/Network/ARPInfo.cs @@ -2,27 +2,26 @@ using System.Net; using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class ARPInfo { - public class ARPInfo - { - public IPAddress IPAddress { get; set; } - public PhysicalAddress MACAddress { get; set; } - public bool IsMulticast { get; set; } + public IPAddress IPAddress { get; set; } + public PhysicalAddress MACAddress { get; set; } + public bool IsMulticast { get; set; } - public int IPAddressInt32 => IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; - public string MACAddressString => MACAddress.ToString().Replace("-","").Replace("-",""); + public int IPAddressInt32 => IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; + public string MACAddressString => MACAddress.ToString().Replace("-","").Replace("-",""); - public ARPInfo() - { + public ARPInfo() + { - } + } - public ARPInfo(IPAddress ipAddress, PhysicalAddress macAddress, bool isMulticast) - { - IPAddress = ipAddress; - MACAddress = macAddress; - IsMulticast = isMulticast; - } + public ARPInfo(IPAddress ipAddress, PhysicalAddress macAddress, bool isMulticast) + { + IPAddress = ipAddress; + MACAddress = macAddress; + IsMulticast = isMulticast; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/BandwidthMeter.cs b/Source/NETworkManager.Models/Network/BandwidthMeter.cs index fd834a4f75..e829fc894a 100644 --- a/Source/NETworkManager.Models/Network/BandwidthMeter.cs +++ b/Source/NETworkManager.Models/Network/BandwidthMeter.cs @@ -2,97 +2,96 @@ using System.Linq; using System.Windows.Threading; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class BandwidthMeter { - public class BandwidthMeter + #region Variables + private double _updateInterval = 1000; + public double UpdateInterval { - #region Variables - private double _updateInterval = 1000; - public double UpdateInterval + get => _updateInterval; + set { - get => _updateInterval; - set - { - if (value == _updateInterval) - return; + if (value == _updateInterval) + return; - _timer.Interval = TimeSpan.FromMilliseconds(value); + _timer.Interval = TimeSpan.FromMilliseconds(value); - _updateInterval = value; - } + _updateInterval = value; } - public bool IsRunning => _timer.IsEnabled; - - private DispatcherTimer _timer = new DispatcherTimer(); - private readonly System.Net.NetworkInformation.NetworkInterface _networkInterface; - private long _previousBytesSent; - private long _previousBytesReceived; - private bool _canUpdate; // Collect initial data for correct calculation - #endregion + } + public bool IsRunning => _timer.IsEnabled; - #region Public events - public event EventHandler UpdateSpeed; + private DispatcherTimer _timer = new DispatcherTimer(); + private readonly System.Net.NetworkInformation.NetworkInterface _networkInterface; + private long _previousBytesSent; + private long _previousBytesReceived; + private bool _canUpdate; // Collect initial data for correct calculation + #endregion - protected virtual void OnUpdateSpeed(BandwidthMeterSpeedArgs e) - { - UpdateSpeed?.Invoke(this, e); - } - #endregion + #region Public events + public event EventHandler UpdateSpeed; - #region Constructor - public BandwidthMeter(string id) - { - _timer.Interval = TimeSpan.FromMilliseconds(UpdateInterval); - _timer.Tick += Timer_Tick; + protected virtual void OnUpdateSpeed(BandwidthMeterSpeedArgs e) + { + UpdateSpeed?.Invoke(this, e); + } + #endregion - _networkInterface = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(x => x.Id == id); - } - #endregion + #region Constructor + public BandwidthMeter(string id) + { + _timer.Interval = TimeSpan.FromMilliseconds(UpdateInterval); + _timer.Tick += Timer_Tick; - #region Methods - public void Start() - { - _timer.Start(); - } + _networkInterface = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(x => x.Id == id); + } + #endregion - public void Stop() - { - _timer.Stop(); + #region Methods + public void Start() + { + _timer.Start(); + } - // Reset - _canUpdate = false; - } + public void Stop() + { + _timer.Stop(); - private void Update() - { - var stats = _networkInterface.GetIPv4Statistics(); + // Reset + _canUpdate = false; + } - var totalBytesSent = stats.BytesSent; - var totalBytesReceived = stats.BytesReceived; + private void Update() + { + var stats = _networkInterface.GetIPv4Statistics(); - var byteSentSpeed = totalBytesSent - _previousBytesSent; - var byteReceivedSpeed = totalBytesReceived - _previousBytesReceived; + var totalBytesSent = stats.BytesSent; + var totalBytesReceived = stats.BytesReceived; - _previousBytesSent = stats.BytesSent; - _previousBytesReceived = stats.BytesReceived; + var byteSentSpeed = totalBytesSent - _previousBytesSent; + var byteReceivedSpeed = totalBytesReceived - _previousBytesReceived; - // Need to collect initial data for correct calculation... - if (!_canUpdate) - { - _canUpdate = true; + _previousBytesSent = stats.BytesSent; + _previousBytesReceived = stats.BytesReceived; - return; - } + // Need to collect initial data for correct calculation... + if (!_canUpdate) + { + _canUpdate = true; - OnUpdateSpeed(new BandwidthMeterSpeedArgs(DateTime.Now, totalBytesReceived, totalBytesSent, byteReceivedSpeed, byteSentSpeed)); + return; } - #endregion - #region Events - private void Timer_Tick(object sender, EventArgs e) - { - Update(); - } - #endregion + OnUpdateSpeed(new BandwidthMeterSpeedArgs(DateTime.Now, totalBytesReceived, totalBytesSent, byteReceivedSpeed, byteSentSpeed)); + } + #endregion + + #region Events + private void Timer_Tick(object sender, EventArgs e) + { + Update(); } + #endregion } diff --git a/Source/NETworkManager.Models/Network/BandwidthMeterSpeedArgs.cs b/Source/NETworkManager.Models/Network/BandwidthMeterSpeedArgs.cs index 3ff491db5e..3ee878787b 100644 --- a/Source/NETworkManager.Models/Network/BandwidthMeterSpeedArgs.cs +++ b/Source/NETworkManager.Models/Network/BandwidthMeterSpeedArgs.cs @@ -1,22 +1,21 @@ using System; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class BandwidthMeterSpeedArgs : EventArgs { - public class BandwidthMeterSpeedArgs : EventArgs - { - public DateTime DateTime { get; } - public long TotalBytesReceived { get; } - public long TotalBytesSent { get; } - public long ByteReceivedSpeed { get; } - public long ByteSentSpeed { get; } + public DateTime DateTime { get; } + public long TotalBytesReceived { get; } + public long TotalBytesSent { get; } + public long ByteReceivedSpeed { get; } + public long ByteSentSpeed { get; } - public BandwidthMeterSpeedArgs(DateTime dateTime, long totoTotalBytesReceived, long totalBytesSent, long byteReceivedSpeed, long byteSentSpeed) - { - DateTime = dateTime; - TotalBytesReceived = totoTotalBytesReceived; - TotalBytesSent = totalBytesSent; - ByteReceivedSpeed = byteReceivedSpeed; - ByteSentSpeed = byteSentSpeed; - } + public BandwidthMeterSpeedArgs(DateTime dateTime, long totoTotalBytesReceived, long totalBytesSent, long byteReceivedSpeed, long byteSentSpeed) + { + DateTime = dateTime; + TotalBytesReceived = totoTotalBytesReceived; + TotalBytesSent = totalBytesSent; + ByteReceivedSpeed = byteReceivedSpeed; + ByteSentSpeed = byteSentSpeed; } } diff --git a/Source/NETworkManager.Models/Network/BitCaluclator.cs b/Source/NETworkManager.Models/Network/BitCaluclator.cs index 9d78619428..c40d37e4a4 100644 --- a/Source/NETworkManager.Models/Network/BitCaluclator.cs +++ b/Source/NETworkManager.Models/Network/BitCaluclator.cs @@ -1,67 +1,66 @@ using System; using System.Threading.Tasks; -namespace NETworkManager.Models.Network -{ public static class BitCaluclator - { public static Task CalculateAsync(double input, BitCaluclatorUnit unit, BitCaluclatorNotation notation) - { - return Task.Run(() => Calculate(input, unit, notation)); - } - - public static BitCaluclatorInfo Calculate(double input, BitCaluclatorUnit unit, BitCaluclatorNotation notation) - { - // Get bits from input - int u = GetUnitBase(unit); - int n = GetNotationBase(notation); +namespace NETworkManager.Models.Network; +public static class BitCaluclator +{ public static Task CalculateAsync(double input, BitCaluclatorUnit unit, BitCaluclatorNotation notation) + { + return Task.Run(() => Calculate(input, unit, notation)); + } - double bits; + public static BitCaluclatorInfo Calculate(double input, BitCaluclatorUnit unit, BitCaluclatorNotation notation) + { + // Get bits from input + int u = GetUnitBase(unit); + int n = GetNotationBase(notation); - if (unit.ToString().EndsWith("Bits", StringComparison.OrdinalIgnoreCase)) - bits = input * Math.Pow(n, u); - else - bits = input * 8 * Math.Pow(n, u); + double bits; - // Return caculation - return new BitCaluclatorInfo - { - Bits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Bits)), - Bytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Bytes)), - Kilobits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Kilobits)), - Kilobytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Kilobytes)), - Megabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Megabits)), - Megabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Megabytes)), - Gigabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Gigabits)), - Gigabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Gigabytes)), - Terabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Terabits)), - Terabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Terabytes)), - Petabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Petabits)), - Petabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Petabytes)), - }; - } + if (unit.ToString().EndsWith("Bits", StringComparison.OrdinalIgnoreCase)) + bits = input * Math.Pow(n, u); + else + bits = input * 8 * Math.Pow(n, u); - private static int GetNotationBase(BitCaluclatorNotation notation) + // Return caculation + return new BitCaluclatorInfo { - return notation == BitCaluclatorNotation.Binary ? 1024 : 1000; - } + Bits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Bits)), + Bytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Bytes)), + Kilobits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Kilobits)), + Kilobytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Kilobytes)), + Megabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Megabits)), + Megabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Megabytes)), + Gigabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Gigabits)), + Gigabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Gigabytes)), + Terabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Terabits)), + Terabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Terabytes)), + Petabits = bits / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Petabits)), + Petabytes = bits / 8 / Math.Pow(n, GetUnitBase(BitCaluclatorUnit.Petabytes)), + }; + } + + private static int GetNotationBase(BitCaluclatorNotation notation) + { + return notation == BitCaluclatorNotation.Binary ? 1024 : 1000; + } - private static int GetUnitBase(BitCaluclatorUnit unit) + private static int GetUnitBase(BitCaluclatorUnit unit) + { + return unit switch { - return unit switch - { - BitCaluclatorUnit.Bits => 0, - BitCaluclatorUnit.Bytes => 0, - BitCaluclatorUnit.Kilobits => 1, - BitCaluclatorUnit.Kilobytes => 1, - BitCaluclatorUnit.Megabits => 2, - BitCaluclatorUnit.Megabytes => 2, - BitCaluclatorUnit.Gigabits => 3, - BitCaluclatorUnit.Gigabytes => 3, - BitCaluclatorUnit.Terabits => 4, - BitCaluclatorUnit.Terabytes => 4, - BitCaluclatorUnit.Petabits => 5, - BitCaluclatorUnit.Petabytes => 5, - _ => -1, - }; - } + BitCaluclatorUnit.Bits => 0, + BitCaluclatorUnit.Bytes => 0, + BitCaluclatorUnit.Kilobits => 1, + BitCaluclatorUnit.Kilobytes => 1, + BitCaluclatorUnit.Megabits => 2, + BitCaluclatorUnit.Megabytes => 2, + BitCaluclatorUnit.Gigabits => 3, + BitCaluclatorUnit.Gigabytes => 3, + BitCaluclatorUnit.Terabits => 4, + BitCaluclatorUnit.Terabytes => 4, + BitCaluclatorUnit.Petabits => 5, + BitCaluclatorUnit.Petabytes => 5, + _ => -1, + }; } } diff --git a/Source/NETworkManager.Models/Network/BitCaluclatorInfo.cs b/Source/NETworkManager.Models/Network/BitCaluclatorInfo.cs index d2511b7a15..5e66af0269 100644 --- a/Source/NETworkManager.Models/Network/BitCaluclatorInfo.cs +++ b/Source/NETworkManager.Models/Network/BitCaluclatorInfo.cs @@ -1,51 +1,50 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class BitCaluclatorInfo { - public class BitCaluclatorInfo - { - public double Bits { get; set; } + public double Bits { get; set; } - public double Bytes { get; set; } + public double Bytes { get; set; } - public double Kilobits { get; set; } + public double Kilobits { get; set; } - public double Kilobytes { get; set; } + public double Kilobytes { get; set; } - public double Megabits { get; set; } + public double Megabits { get; set; } - public double Megabytes { get; set; } + public double Megabytes { get; set; } - public double Gigabits { get; set; } + public double Gigabits { get; set; } - public double Gigabytes { get; set; } + public double Gigabytes { get; set; } - public double Terabits { get; set; } + public double Terabits { get; set; } - public double Terabytes { get; set; } + public double Terabytes { get; set; } - public double Petabits { get; set; } + public double Petabits { get; set; } - public double Petabytes { get; set; } + public double Petabytes { get; set; } - public BitCaluclatorInfo() - { + public BitCaluclatorInfo() + { - } + } - public BitCaluclatorInfo(double bits, double bytes, double kilobits, double kilobytes, double megabits, double megabytes, double gigabits, double gigabytes, double terabits, double terabytes, double petabits, double petabytes) - { - Bits = bits; - Bytes = bytes; - Kilobits = kilobits; - Kilobytes = kilobytes; - Megabits = megabits; - Megabytes = megabytes; - Gigabits = gigabits; - Gigabytes = gigabytes; - Terabits = terabits; - Terabytes = terabytes; - Petabits = petabits; - Petabytes = petabytes; - } + public BitCaluclatorInfo(double bits, double bytes, double kilobits, double kilobytes, double megabits, double megabytes, double gigabits, double gigabytes, double terabits, double terabytes, double petabits, double petabytes) + { + Bits = bits; + Bytes = bytes; + Kilobits = kilobits; + Kilobytes = kilobytes; + Megabits = megabits; + Megabytes = megabytes; + Gigabits = gigabits; + Gigabytes = gigabytes; + Terabits = terabits; + Terabytes = terabytes; + Petabits = petabits; + Petabytes = petabytes; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/BitCaluclatorNotation.cs b/Source/NETworkManager.Models/Network/BitCaluclatorNotation.cs index 92efe304d3..3873a5d026 100644 --- a/Source/NETworkManager.Models/Network/BitCaluclatorNotation.cs +++ b/Source/NETworkManager.Models/Network/BitCaluclatorNotation.cs @@ -1,18 +1,17 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Represents the notation which is used to calculate. +/// +public enum BitCaluclatorNotation { /// - /// Represents the notation which is used to calculate. + /// Binary base is 1024. /// - public enum BitCaluclatorNotation - { - /// - /// Binary base is 1024. - /// - Binary, + Binary, - /// - /// Decimal base is 1000. - /// - Decimal - } + /// + /// Decimal base is 1000. + /// + Decimal } diff --git a/Source/NETworkManager.Models/Network/BitCaluclatorUnit.cs b/Source/NETworkManager.Models/Network/BitCaluclatorUnit.cs index c9681381ba..c3bd648cf9 100644 --- a/Source/NETworkManager.Models/Network/BitCaluclatorUnit.cs +++ b/Source/NETworkManager.Models/Network/BitCaluclatorUnit.cs @@ -1,68 +1,67 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Represents the notation which is used to calculate. +/// +public enum BitCaluclatorUnit { /// - /// Represents the notation which is used to calculate. + /// Unit bits. /// - public enum BitCaluclatorUnit - { - /// - /// Unit bits. - /// - Bits, + Bits, - /// - /// Unit bytes. - /// - Bytes, + /// + /// Unit bytes. + /// + Bytes, - /// - /// Unit kilobits - /// - Kilobits, + /// + /// Unit kilobits + /// + Kilobits, - /// - /// Unit kilobytes - /// - Kilobytes, + /// + /// Unit kilobytes + /// + Kilobytes, - /// - /// Unit megabits - /// - Megabits, + /// + /// Unit megabits + /// + Megabits, - /// - /// Unit megabytes - /// - Megabytes, + /// + /// Unit megabytes + /// + Megabytes, - /// - /// Unit gigabits - /// - Gigabits, + /// + /// Unit gigabits + /// + Gigabits, - /// - /// Unit gigabytes - /// - Gigabytes, + /// + /// Unit gigabytes + /// + Gigabytes, - /// - /// Unit terabits - /// - Terabits, + /// + /// Unit terabits + /// + Terabits, - /// - /// Unit terabytes - /// - Terabytes, + /// + /// Unit terabytes + /// + Terabytes, - /// - /// Unit petabits - /// - Petabits, + /// + /// Unit petabits + /// + Petabits, - /// - /// Unit petabytes - /// - Petabytes - } + /// + /// Unit petabytes + /// + Petabytes } diff --git a/Source/NETworkManager.Models/Network/Connection.Protocol.cs b/Source/NETworkManager.Models/Network/Connection.Protocol.cs index d89d2df331..2402c3fa87 100644 --- a/Source/NETworkManager.Models/Network/Connection.Protocol.cs +++ b/Source/NETworkManager.Models/Network/Connection.Protocol.cs @@ -1,10 +1,9 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public partial class Connection { - public partial class Connection + public enum Protocol { - public enum Protocol - { - TCP - } + TCP } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/Connection.cs b/Source/NETworkManager.Models/Network/Connection.cs index d9d714ad4f..b1cf0ccc3d 100644 --- a/Source/NETworkManager.Models/Network/Connection.cs +++ b/Source/NETworkManager.Models/Network/Connection.cs @@ -3,20 +3,19 @@ using System.Net.NetworkInformation; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public partial class Connection { - public partial class Connection + #region Methods + public static Task> GetActiveTcpConnectionsAsync() { - #region Methods - public static Task> GetActiveTcpConnectionsAsync() - { - return Task.Run(() => GetActiveTcpConnections()); - } + return Task.Run(() => GetActiveTcpConnections()); + } - public static List GetActiveTcpConnections() - { - return IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections().Select(tcpInfo => new ConnectionInfo(Protocol.TCP, tcpInfo.LocalEndPoint.Address, tcpInfo.LocalEndPoint.Port, tcpInfo.RemoteEndPoint.Address, tcpInfo.RemoteEndPoint.Port, tcpInfo.State)).ToList(); - } - #endregion + public static List GetActiveTcpConnections() + { + return IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections().Select(tcpInfo => new ConnectionInfo(Protocol.TCP, tcpInfo.LocalEndPoint.Address, tcpInfo.LocalEndPoint.Port, tcpInfo.RemoteEndPoint.Address, tcpInfo.RemoteEndPoint.Port, tcpInfo.State)).ToList(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/ConnectionInfo.cs b/Source/NETworkManager.Models/Network/ConnectionInfo.cs index 3217835dbf..8d08add0e9 100644 --- a/Source/NETworkManager.Models/Network/ConnectionInfo.cs +++ b/Source/NETworkManager.Models/Network/ConnectionInfo.cs @@ -2,33 +2,32 @@ using System.Net.NetworkInformation; using static NETworkManager.Models.Network.Connection; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class ConnectionInfo { - public class ConnectionInfo - { - public Connection.Protocol Protocol { get; set; } - public IPAddress LocalIPAddress { get; set; } - public int LocalPort { get; set; } - public IPAddress RemoteIPAddress { get; set; } - public int RemotePort { get; set; } - public TcpState TcpState { get; set; } + public Connection.Protocol Protocol { get; set; } + public IPAddress LocalIPAddress { get; set; } + public int LocalPort { get; set; } + public IPAddress RemoteIPAddress { get; set; } + public int RemotePort { get; set; } + public TcpState TcpState { get; set; } - public int LocalIPAddressInt32 => LocalIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(LocalIPAddress) : 0; - public int RemoteIPAddressInt32 => LocalIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(RemoteIPAddress) : 0; - - public ConnectionInfo() - { + public int LocalIPAddressInt32 => LocalIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(LocalIPAddress) : 0; + public int RemoteIPAddressInt32 => LocalIPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(RemoteIPAddress) : 0; + + public ConnectionInfo() + { - } + } - public ConnectionInfo(Protocol protocol, IPAddress localIPAddress, int localPort, IPAddress remoteIPAddress, int remotePort, TcpState tcpState) - { - Protocol = protocol; - LocalIPAddress = localIPAddress; - LocalPort = localPort; - RemoteIPAddress = remoteIPAddress; - RemotePort = remotePort; - TcpState = tcpState; - } + public ConnectionInfo(Protocol protocol, IPAddress localIPAddress, int localPort, IPAddress remoteIPAddress, int remotePort, TcpState tcpState) + { + Protocol = protocol; + LocalIPAddress = localIPAddress; + LocalPort = localPort; + RemoteIPAddress = remoteIPAddress; + RemotePort = remotePort; + TcpState = tcpState; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/ConnectionState.cs b/Source/NETworkManager.Models/Network/ConnectionState.cs index 3c73d52043..31e58a714f 100644 --- a/Source/NETworkManager.Models/Network/ConnectionState.cs +++ b/Source/NETworkManager.Models/Network/ConnectionState.cs @@ -1,33 +1,32 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Represents the state of a connection. +/// +public enum ConnectionState { /// - /// Represents the state of a connection. + /// Connection has no state. /// - public enum ConnectionState - { - /// - /// Connection has no state. - /// - None, + None, - /// - /// Connection is OK. - /// - OK, + /// + /// Connection is OK. + /// + OK, - /// - /// Connection is warning. - /// - Warning, + /// + /// Connection is warning. + /// + Warning, - /// - /// Connection is critical. - /// - Critical, + /// + /// Connection is critical. + /// + Critical, - /// - /// Informations. - /// - Info - } + /// + /// Informations. + /// + Info } diff --git a/Source/NETworkManager.Models/Network/DNSLookup.cs b/Source/NETworkManager.Models/Network/DNSLookup.cs index 3a87c62351..248e80b913 100644 --- a/Source/NETworkManager.Models/Network/DNSLookup.cs +++ b/Source/NETworkManager.Models/Network/DNSLookup.cs @@ -7,199 +7,198 @@ using System.Net.NetworkInformation; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class DNSLookup { - public class DNSLookup - { - #region Variables - private readonly DNSLookupSettings _settings; - - private readonly IEnumerable _dnsServers; + #region Variables + private readonly DNSLookupSettings _settings; + + private readonly IEnumerable _dnsServers; - private readonly string _dnsSuffix; + private readonly string _dnsSuffix; - private readonly bool _addSuffix; - #endregion + private readonly bool _addSuffix; + #endregion - #region Constructor - public DNSLookup(DNSLookupSettings settings, IEnumerable dnsServers = null) - { - _settings = settings; + #region Constructor + public DNSLookup(DNSLookupSettings settings, IEnumerable dnsServers = null) + { + _settings = settings; - _dnsServers = GetDnsServer(dnsServers); + _dnsServers = GetDnsServer(dnsServers); - _dnsSuffix = _settings.UseCustomDNSSuffix ? _settings.CustomDNSSuffix : IPGlobalProperties.GetIPGlobalProperties().DomainName; - _addSuffix = _settings.AddDNSSuffix && !string.IsNullOrEmpty(_dnsSuffix); - } - #endregion + _dnsSuffix = _settings.UseCustomDNSSuffix ? _settings.CustomDNSSuffix : IPGlobalProperties.GetIPGlobalProperties().DomainName; + _addSuffix = _settings.AddDNSSuffix && !string.IsNullOrEmpty(_dnsSuffix); + } + #endregion - #region Events - public event EventHandler RecordReceived; + #region Events + public event EventHandler RecordReceived; - protected virtual void OnRecordReceived(DNSLookupRecordArgs e) - { - RecordReceived?.Invoke(this, e); - } + protected virtual void OnRecordReceived(DNSLookupRecordArgs e) + { + RecordReceived?.Invoke(this, e); + } - public event EventHandler LookupError; + public event EventHandler LookupError; - protected virtual void OnLookupError(DNSLookupErrorArgs e) - { - LookupError?.Invoke(this, e); - } + protected virtual void OnLookupError(DNSLookupErrorArgs e) + { + LookupError?.Invoke(this, e); + } - public event EventHandler LookupComplete; + public event EventHandler LookupComplete; - protected virtual void OnLookupComplete() + protected virtual void OnLookupComplete() + { + LookupComplete?.Invoke(this, EventArgs.Empty); + } + #endregion + + #region Methods + /// + /// Get the DNS servers from Windows or get custom DNS servers from . + /// + /// List of DNS servers as . + private IEnumerable GetDnsServer(IEnumerable dnsServers = null) + { + List servers = new(); + + // Use windows dns servers + if(dnsServers == null) { - LookupComplete?.Invoke(this, EventArgs.Empty); + foreach (var dnsServer in NameServer.ResolveNameServers(true, false)) + servers.Add(new IPEndPoint(IPAddress.Parse(dnsServer.Address), dnsServer.Port)); } - #endregion - - #region Methods - /// - /// Get the DNS servers from Windows or get custom DNS servers from . - /// - /// List of DNS servers as . - private IEnumerable GetDnsServer(IEnumerable dnsServers = null) + else { - List servers = new(); + foreach (var dnsServer in dnsServers) + servers.Add(new IPEndPoint(IPAddress.Parse(dnsServer.Server), dnsServer.Port)); + } - // Use windows dns servers - if(dnsServers == null) - { - foreach (var dnsServer in NameServer.ResolveNameServers(true, false)) - servers.Add(new IPEndPoint(IPAddress.Parse(dnsServer.Address), dnsServer.Port)); - } - else - { - foreach (var dnsServer in dnsServers) - servers.Add(new IPEndPoint(IPAddress.Parse(dnsServer.Server), dnsServer.Port)); - } - - return servers; - } + return servers; + } - /// - /// Append DNS suffix to hostname if not set. - /// - /// List of hosts - /// List of host with DNS suffix - private IEnumerable GetHostWithSuffix(IEnumerable hosts) + /// + /// Append DNS suffix to hostname if not set. + /// + /// List of hosts + /// List of host with DNS suffix + private IEnumerable GetHostWithSuffix(IEnumerable hosts) + { + List queries = new(); + + foreach (var host in hosts) { - List queries = new(); - - foreach (var host in hosts) - { - if (_settings.QueryType != QueryType.PTR && !host.Contains('.', StringComparison.OrdinalIgnoreCase)) - queries.Add($"{host}.{_dnsSuffix}"); - } - - return queries; + if (_settings.QueryType != QueryType.PTR && !host.Contains('.', StringComparison.OrdinalIgnoreCase)) + queries.Add($"{host}.{_dnsSuffix}"); } - /// + return queries; + } + + /// /// Resolve hostname, fqdn or ip address. /// /// List of hostnames, FQDNs or ip addresses. public void ResolveAsync(IEnumerable hosts) + { + Task.Run(() => { - Task.Run(() => - { - // Append dns suffix to hostname, if option is set, otherwiese just copy the list - IEnumerable queries = _addSuffix ? GetHostWithSuffix(hosts) : hosts; + // Append dns suffix to hostname, if option is set, otherwiese just copy the list + IEnumerable queries = _addSuffix ? GetHostWithSuffix(hosts) : hosts; - // Foreach dns server - Parallel.ForEach(_dnsServers, dnsServer => + // Foreach dns server + Parallel.ForEach(_dnsServers, dnsServer => + { + // Init each dns server once + LookupClientOptions lookupClientOptions = new(dnsServer) { - // Init each dns server once - LookupClientOptions lookupClientOptions = new(dnsServer) - { - UseTcpOnly = _settings.UseTCPOnly, - UseCache = _settings.UseCache, - Recursion = _settings.Recursion, - Timeout = _settings.Timeout, - Retries = _settings.Retries, - }; + UseTcpOnly = _settings.UseTCPOnly, + UseCache = _settings.UseCache, + Recursion = _settings.Recursion, + Timeout = _settings.Timeout, + Retries = _settings.Retries, + }; - LookupClient lookupClient = new(lookupClientOptions); + LookupClient lookupClient = new(lookupClientOptions); - // Foreach host - Parallel.ForEach(queries, query => + // Foreach host + Parallel.ForEach(queries, query => + { + try { - try + // Resovle A, AAAA, CNAME, PTR, etc. + var dnsResponse = _settings.QueryType == QueryType.PTR ? lookupClient.QueryReverse(IPAddress.Parse(query)) : lookupClient.Query(query, _settings.QueryType, _settings.QueryClass); + + // Pass the error we got from the lookup client (dns server). + if (dnsResponse.HasError) { - // Resovle A, AAAA, CNAME, PTR, etc. - var dnsResponse = _settings.QueryType == QueryType.PTR ? lookupClient.QueryReverse(IPAddress.Parse(query)) : lookupClient.Query(query, _settings.QueryType, _settings.QueryClass); - - // Pass the error we got from the lookup client (dns server). - if (dnsResponse.HasError) - { - OnLookupError(new DNSLookupErrorArgs(query, $"{dnsServer.Address}", $"{dnsServer.Address}:{dnsServer.Port}", dnsResponse.ErrorMessage)); - return; // continue - } - - if (dnsResponse.Answers.Count == 0) - { - var digAdditionalCommand = _settings.QueryType == QueryType.PTR ? " -x " : " "; - OnLookupError(new DNSLookupErrorArgs(query, $"{dnsServer.Address}", $"{dnsServer.Address}:{dnsServer.Port}", $"No DNS resource records received for query \"{query}\" (Query type: \"{_settings.QueryType}\") and the DNS server did not return an error. Try to check your DNS server with: dig @{dnsServer.Address}{digAdditionalCommand}{query}")); - return; // continue - } - - // Process the results... - ProcessDnsAnswers(dnsResponse.Answers, dnsResponse.NameServer); + OnLookupError(new DNSLookupErrorArgs(query, $"{dnsServer.Address}", $"{dnsServer.Address}:{dnsServer.Port}", dnsResponse.ErrorMessage)); + return; // continue } - catch (Exception ex) + + if (dnsResponse.Answers.Count == 0) { - OnLookupError(new DNSLookupErrorArgs(query, $"{dnsServer.Address}", $"{dnsServer.Address}:{dnsServer.Port}", ex.Message)); + var digAdditionalCommand = _settings.QueryType == QueryType.PTR ? " -x " : " "; + OnLookupError(new DNSLookupErrorArgs(query, $"{dnsServer.Address}", $"{dnsServer.Address}:{dnsServer.Port}", $"No DNS resource records received for query \"{query}\" (Query type: \"{_settings.QueryType}\") and the DNS server did not return an error. Try to check your DNS server with: dig @{dnsServer.Address}{digAdditionalCommand}{query}")); + return; // continue } - }); - }); - OnLookupComplete(); + // Process the results... + ProcessDnsAnswers(dnsResponse.Answers, dnsResponse.NameServer); + } + catch (Exception ex) + { + OnLookupError(new DNSLookupErrorArgs(query, $"{dnsServer.Address}", $"{dnsServer.Address}:{dnsServer.Port}", ex.Message)); + } + }); }); - } - /// - /// Process the dns query response. - /// - /// to process. - private void ProcessDnsAnswers(IEnumerable answers, NameServer nameServer) - { - // A - foreach (var record in answers.ARecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, $"{record.Address}", $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + OnLookupComplete(); + }); + } - // AAAA - foreach (var record in answers.AaaaRecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, $"{record.Address}", $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + /// + /// Process the dns query response. + /// + /// to process. + private void ProcessDnsAnswers(IEnumerable answers, NameServer nameServer) + { + // A + foreach (var record in answers.ARecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, $"{record.Address}", $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); - // CNAME - foreach (var record in answers.CnameRecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.CanonicalName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + // AAAA + foreach (var record in answers.AaaaRecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, $"{record.Address}", $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); - // MX - foreach (var record in answers.MxRecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.Exchange, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + // CNAME + foreach (var record in answers.CnameRecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.CanonicalName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); - // NS - foreach (var record in answers.NsRecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.NSDName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + // MX + foreach (var record in answers.MxRecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.Exchange, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); - // PTR - foreach (var record in answers.PtrRecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.PtrDomainName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + // NS + foreach (var record in answers.NsRecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.NSDName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); - // SOA - foreach (var record in answers.SoaRecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.MName + ", " + record.RName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + // PTR + foreach (var record in answers.PtrRecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.PtrDomainName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); - // TXT - foreach (var record in answers.TxtRecords()) - OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, string.Join(", ", record.Text), $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + // SOA + foreach (var record in answers.SoaRecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, record.MName + ", " + record.RName, $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); - // ToDo: implement more - } - #endregion + // TXT + foreach (var record in answers.TxtRecords()) + OnRecordReceived(new DNSLookupRecordArgs(record.DomainName, record.TimeToLive, record.RecordClass, record.RecordType, string.Join(", ", record.Text), $"{nameServer.Address}", $"{nameServer.Address}:{nameServer.Port}")); + + // ToDo: implement more } + #endregion } diff --git a/Source/NETworkManager.Models/Network/DNSLookupCompleteArgs.cs b/Source/NETworkManager.Models/Network/DNSLookupCompleteArgs.cs index 84c1bbed5b..6c6d2d2432 100644 --- a/Source/NETworkManager.Models/Network/DNSLookupCompleteArgs.cs +++ b/Source/NETworkManager.Models/Network/DNSLookupCompleteArgs.cs @@ -1,27 +1,26 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class DNSLookupCompleteArgs : System.EventArgs { - public class DNSLookupCompleteArgs : System.EventArgs - { - public string ServerAndPort { get; set; } - public int QuestionsCount { get; set; } - public int AnswersCount { get; set; } - public int AuthoritiesCount { get; set; } - public int AdditionalsCount { get; set; } - public int MessageSize { get; set; } + public string ServerAndPort { get; set; } + public int QuestionsCount { get; set; } + public int AnswersCount { get; set; } + public int AuthoritiesCount { get; set; } + public int AdditionalsCount { get; set; } + public int MessageSize { get; set; } - public DNSLookupCompleteArgs() - { + public DNSLookupCompleteArgs() + { - } + } - public DNSLookupCompleteArgs(string serverAndPort, int questionsCount, int answersCount, int authoritiesCount, int additionalsCount, int messageSize) - { - ServerAndPort = serverAndPort; - QuestionsCount = questionsCount; - AnswersCount = answersCount; - AuthoritiesCount = authoritiesCount; - AdditionalsCount = additionalsCount; - MessageSize = messageSize; - } + public DNSLookupCompleteArgs(string serverAndPort, int questionsCount, int answersCount, int authoritiesCount, int additionalsCount, int messageSize) + { + ServerAndPort = serverAndPort; + QuestionsCount = questionsCount; + AnswersCount = answersCount; + AuthoritiesCount = authoritiesCount; + AdditionalsCount = additionalsCount; + MessageSize = messageSize; } } diff --git a/Source/NETworkManager.Models/Network/DNSLookupRecordArgs.cs b/Source/NETworkManager.Models/Network/DNSLookupRecordArgs.cs index 20323352d8..2ceafcb08d 100644 --- a/Source/NETworkManager.Models/Network/DNSLookupRecordArgs.cs +++ b/Source/NETworkManager.Models/Network/DNSLookupRecordArgs.cs @@ -1,32 +1,31 @@ using DnsClient; using DnsClient.Protocol; -namespace NETworkManager.Models.Network -{ - public class DNSLookupRecordArgs : System.EventArgs - { - public string DomainName { get; set; } - public int TTL { get; set; } - public QueryClass Class { get; set; } - public ResourceRecordType Type { get; set; } - public string Result { get; set; } - public string Server { get; set; } - public string IPEndPoint { get; set; } +namespace NETworkManager.Models.Network; - public DNSLookupRecordArgs() - { +public class DNSLookupRecordArgs : System.EventArgs +{ + public string DomainName { get; set; } + public int TTL { get; set; } + public QueryClass Class { get; set; } + public ResourceRecordType Type { get; set; } + public string Result { get; set; } + public string Server { get; set; } + public string IPEndPoint { get; set; } - } + public DNSLookupRecordArgs() + { - public DNSLookupRecordArgs(string domainName, int ttl, QueryClass queryClass, ResourceRecordType queryType, string result, string server, string ipEndPoint) - { - DomainName = domainName; - TTL = ttl; - Class = queryClass; - Type = queryType; - Result = result; - Server = server; - IPEndPoint = ipEndPoint; - } + } + + public DNSLookupRecordArgs(string domainName, int ttl, QueryClass queryClass, ResourceRecordType queryType, string result, string server, string ipEndPoint) + { + DomainName = domainName; + TTL = ttl; + Class = queryClass; + Type = queryType; + Result = result; + Server = server; + IPEndPoint = ipEndPoint; } } diff --git a/Source/NETworkManager.Models/Network/DNSLookupRecordInfo.cs b/Source/NETworkManager.Models/Network/DNSLookupRecordInfo.cs index 7fec2c18a8..79279dd28c 100644 --- a/Source/NETworkManager.Models/Network/DNSLookupRecordInfo.cs +++ b/Source/NETworkManager.Models/Network/DNSLookupRecordInfo.cs @@ -1,41 +1,40 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class DNSLookupRecordInfo { - public class DNSLookupRecordInfo - { - public string DomainName { get; set; } - - public int TTL { get; set; } - - public string Class { get; set; } + public string DomainName { get; set; } + + public int TTL { get; set; } + + public string Class { get; set; } - public string Type { get; set; } + public string Type { get; set; } - public string Result { get; set; } + public string Result { get; set; } - public string Server { get; set; } + public string Server { get; set; } - public string IPEndPoint { get; set; } + public string IPEndPoint { get; set; } - public DNSLookupRecordInfo() - { + public DNSLookupRecordInfo() + { - } + } - public DNSLookupRecordInfo(string domainName, int ttl, string xclass, string type, string result, string server, string ipEndPoint) - { - DomainName = domainName; - TTL = ttl; - Class = xclass; - Type = type; - Result = result; - Server = server; - IPEndPoint = ipEndPoint; - } + public DNSLookupRecordInfo(string domainName, int ttl, string xclass, string type, string result, string server, string ipEndPoint) + { + DomainName = domainName; + TTL = ttl; + Class = xclass; + Type = type; + Result = result; + Server = server; + IPEndPoint = ipEndPoint; + } - public static DNSLookupRecordInfo Parse(DNSLookupRecordArgs e) - { - return new DNSLookupRecordInfo(e.DomainName, e.TTL, e.Class.ToString(), e.Type.ToString(), e.Result, e.Server, e.IPEndPoint); - } + public static DNSLookupRecordInfo Parse(DNSLookupRecordArgs e) + { + return new DNSLookupRecordInfo(e.DomainName, e.TTL, e.Class.ToString(), e.Type.ToString(), e.Result, e.Server, e.IPEndPoint); } } diff --git a/Source/NETworkManager.Models/Network/DNSLookupSettings.cs b/Source/NETworkManager.Models/Network/DNSLookupSettings.cs index d7432f4976..ddf15be2ab 100644 --- a/Source/NETworkManager.Models/Network/DNSLookupSettings.cs +++ b/Source/NETworkManager.Models/Network/DNSLookupSettings.cs @@ -1,25 +1,24 @@ using DnsClient; using System; -namespace NETworkManager.Models.Network -{ - public class DNSLookupSettings - { - public bool AddDNSSuffix { get; set; } = true; - public bool UseCustomDNSSuffix { get; set; } = false; - public string CustomDNSSuffix { get; set; } - public QueryClass QueryClass { get; set; } = QueryClass.IN; - public QueryType QueryType { get; set; } = QueryType.ANY; +namespace NETworkManager.Models.Network; - public bool UseCache { get; set; } = false; - public bool Recursion { get; set; } = true; - public bool UseTCPOnly { get; set; } = false; - public int Retries { get; set; } = 3; - public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(2); +public class DNSLookupSettings +{ + public bool AddDNSSuffix { get; set; } = true; + public bool UseCustomDNSSuffix { get; set; } = false; + public string CustomDNSSuffix { get; set; } + public QueryClass QueryClass { get; set; } = QueryClass.IN; + public QueryType QueryType { get; set; } = QueryType.ANY; - public DNSLookupSettings() - { + public bool UseCache { get; set; } = false; + public bool Recursion { get; set; } = true; + public bool UseTCPOnly { get; set; } = false; + public int Retries { get; set; } = 3; + public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(2); + + public DNSLookupSettings() + { - } } } diff --git a/Source/NETworkManager.Models/Network/DNSServer.cs b/Source/NETworkManager.Models/Network/DNSServer.cs index e4313243dd..1724d20508 100644 --- a/Source/NETworkManager.Models/Network/DNSServer.cs +++ b/Source/NETworkManager.Models/Network/DNSServer.cs @@ -1,40 +1,39 @@ using System.Collections.Generic; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class provides static informations about dns servers. +/// +public static class DNSServer { /// - /// Class provides static informations about dns servers. + /// Method will return a default list of common dns servers. /// - public static class DNSServer + /// List of common dns servers. + public static List GetDefaultList() => new() { - /// - /// Method will return a default list of common dns servers. - /// - /// List of common dns servers. - public static List GetDefaultList() => new() - { - new DNSServerConnectionInfoProfile(), // Windows DNS server - new DNSServerConnectionInfoProfile("Cloudflare", new() { - new ServerConnectionInfo("1.1.1.1", 53, TransportProtocol.UDP), - new ServerConnectionInfo("1.0.0.1", 53, TransportProtocol.UDP) - }), - new DNSServerConnectionInfoProfile("DNS.Watch", new() - { new ServerConnectionInfo("84.200.69.80", 53, TransportProtocol.UDP), - new ServerConnectionInfo("84.200.70.40", 53, TransportProtocol.UDP) - }), - new DNSServerConnectionInfoProfile("Google Public DNS", new() { - new ServerConnectionInfo("8.8.8.8", 53, TransportProtocol.UDP), - new ServerConnectionInfo("8.8.4.4", 53, TransportProtocol.UDP) - }), - new DNSServerConnectionInfoProfile("Level3", new(){ - new ServerConnectionInfo("209.244.0.3", 53, TransportProtocol.UDP), - new ServerConnectionInfo("209.244.0.4", 53, TransportProtocol.UDP) - }), - new DNSServerConnectionInfoProfile("Verisign", new() - { - new ServerConnectionInfo("64.6.64.6", 53, TransportProtocol.UDP), - new ServerConnectionInfo("64.6.65.6", 53, TransportProtocol.UDP) - }) - }; - } + new DNSServerConnectionInfoProfile(), // Windows DNS server + new DNSServerConnectionInfoProfile("Cloudflare", new() { + new ServerConnectionInfo("1.1.1.1", 53, TransportProtocol.UDP), + new ServerConnectionInfo("1.0.0.1", 53, TransportProtocol.UDP) + }), + new DNSServerConnectionInfoProfile("DNS.Watch", new() + { new ServerConnectionInfo("84.200.69.80", 53, TransportProtocol.UDP), + new ServerConnectionInfo("84.200.70.40", 53, TransportProtocol.UDP) + }), + new DNSServerConnectionInfoProfile("Google Public DNS", new() { + new ServerConnectionInfo("8.8.8.8", 53, TransportProtocol.UDP), + new ServerConnectionInfo("8.8.4.4", 53, TransportProtocol.UDP) + }), + new DNSServerConnectionInfoProfile("Level3", new(){ + new ServerConnectionInfo("209.244.0.3", 53, TransportProtocol.UDP), + new ServerConnectionInfo("209.244.0.4", 53, TransportProtocol.UDP) + }), + new DNSServerConnectionInfoProfile("Verisign", new() + { + new ServerConnectionInfo("64.6.64.6", 53, TransportProtocol.UDP), + new ServerConnectionInfo("64.6.65.6", 53, TransportProtocol.UDP) + }) + }; } diff --git a/Source/NETworkManager.Models/Network/DNSServerConnectionInfoProfile.cs b/Source/NETworkManager.Models/Network/DNSServerConnectionInfoProfile.cs index e124c5b3e2..b7af4e040b 100644 --- a/Source/NETworkManager.Models/Network/DNSServerConnectionInfoProfile.cs +++ b/Source/NETworkManager.Models/Network/DNSServerConnectionInfoProfile.cs @@ -1,34 +1,33 @@ using System.Collections.Generic; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class is used to store informations about a DNS server profile. +/// +public class DNSServerConnectionInfoProfile : ServerConnectionInfoProfile { /// - /// Class is used to store informations about a DNS server profile. + /// Use the DNS server from Windows. /// - public class DNSServerConnectionInfoProfile : ServerConnectionInfoProfile - { - /// - /// Use the DNS server from Windows. - /// - public bool UseWindowsDNSServer { get; set; } + public bool UseWindowsDNSServer { get; set; } - /// - /// Create an instance of . This will use the - /// default DNS server from Windows (=true). - /// - public DNSServerConnectionInfoProfile() - { - UseWindowsDNSServer = true; - } + /// + /// Create an instance of . This will use the + /// default DNS server from Windows (=true). + /// + public DNSServerConnectionInfoProfile() + { + UseWindowsDNSServer = true; + } - /// - /// Create an instance of with parameters. - /// - /// Name of the profile. - /// List of servers as . - public DNSServerConnectionInfoProfile(string name, List servers) : base(name, servers) - { + /// + /// Create an instance of with parameters. + /// + /// Name of the profile. + /// List of servers as . + public DNSServerConnectionInfoProfile(string name, List servers) : base(name, servers) + { - } } } diff --git a/Source/NETworkManager.Models/Network/DiscoveryProtocol.Protocol.cs b/Source/NETworkManager.Models/Network/DiscoveryProtocol.Protocol.cs index 8c635e68bb..9803aebcbb 100644 --- a/Source/NETworkManager.Models/Network/DiscoveryProtocol.Protocol.cs +++ b/Source/NETworkManager.Models/Network/DiscoveryProtocol.Protocol.cs @@ -1,30 +1,28 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class to capture network discovery protocol packages. +/// +public partial class DiscoveryProtocol { /// - /// Class to capture network discovery protocol packages. + /// Represents all discovery protocols. /// - public partial class DiscoveryProtocol + public enum Protocol { /// - /// Represents all discovery protocols. + /// Link layer and Cisco discovery protocol. /// - public enum Protocol - { - /// - /// Link layer and Cisco discovery protocol. - /// - LLDP_CDP, + LLDP_CDP, - /// - /// Link layer discovery protocol. - /// - LLDP, + /// + /// Link layer discovery protocol. + /// + LLDP, - /// - /// Cisco discovery protocol. - /// - CDP - } + /// + /// Cisco discovery protocol. + /// + CDP } - } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/DiscoveryProtocol.cs b/Source/NETworkManager.Models/Network/DiscoveryProtocol.cs index 50d22a7edb..62a85ec6a8 100644 --- a/Source/NETworkManager.Models/Network/DiscoveryProtocol.cs +++ b/Source/NETworkManager.Models/Network/DiscoveryProtocol.cs @@ -7,184 +7,183 @@ using System.Text; using System.Collections.Generic; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class to capture network discovery protocol packages. +/// +public partial class DiscoveryProtocol { /// - /// Class to capture network discovery protocol packages. + /// Holds the PowerShell script which is loaded when the class is initialized. /// - public partial class DiscoveryProtocol + private readonly string PSDiscoveryProtocolModule = string.Empty; + + /// + /// Is triggerd when a network package with a discovery protocol is received. + /// + public event EventHandler PackageReceived; + + /// + /// Triggers the event. + /// + /// Passes to the event. + protected virtual void OnPackageReceived(DiscoveryProtocolPackageArgs e) { - /// - /// Holds the PowerShell script which is loaded when the class is initialized. - /// - private readonly string PSDiscoveryProtocolModule = string.Empty; - - /// - /// Is triggerd when a network package with a discovery protocol is received. - /// - public event EventHandler PackageReceived; - - /// - /// Triggers the event. - /// - /// Passes to the event. - protected virtual void OnPackageReceived(DiscoveryProtocolPackageArgs e) - { - PackageReceived?.Invoke(this, e); - } + PackageReceived?.Invoke(this, e); + } - /// - /// Is triggered when an error occurs during the capturing. - /// - public event EventHandler ErrorReceived; + /// + /// Is triggered when an error occurs during the capturing. + /// + public event EventHandler ErrorReceived; - /// - /// Triggers the event. - /// - /// Passes to the event. - protected virtual void OnErrorReceived(DiscoveryProtocolErrorArgs e) - { - ErrorReceived?.Invoke(this, e); - } - - /// - /// Is triggered when a warning occurs during the capturing. - /// - public event EventHandler WarningReceived; - - /// - /// Triggers the event. - /// - /// Passes to the event. - protected virtual void OnWarningReceived(DiscoveryProtocolWarningArgs e) - { - WarningReceived?.Invoke(this, e); - } - - /// - /// Is triggered when the capturing is completed. - /// - public event EventHandler Complete; - - /// - /// Triggers the event. - /// - protected virtual void OnComplete() - { - Complete?.Invoke(this, EventArgs.Empty); - } + /// + /// Triggers the event. + /// + /// Passes to the event. + protected virtual void OnErrorReceived(DiscoveryProtocolErrorArgs e) + { + ErrorReceived?.Invoke(this, e); + } - /// - /// Initializes a new instance of the class. - /// - public DiscoveryProtocol() - { - using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NETworkManager.Models.Resources.PSDiscoveryProtocol.psm1"); + /// + /// Is triggered when a warning occurs during the capturing. + /// + public event EventHandler WarningReceived; + + /// + /// Triggers the event. + /// + /// Passes to the event. + protected virtual void OnWarningReceived(DiscoveryProtocolWarningArgs e) + { + WarningReceived?.Invoke(this, e); + } + + /// + /// Is triggered when the capturing is completed. + /// + public event EventHandler Complete; + + /// + /// Triggers the event. + /// + protected virtual void OnComplete() + { + Complete?.Invoke(this, EventArgs.Empty); + } - using StreamReader reader = new(stream); + /// + /// Initializes a new instance of the class. + /// + public DiscoveryProtocol() + { + using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NETworkManager.Models.Resources.PSDiscoveryProtocol.psm1"); - PSDiscoveryProtocolModule = reader.ReadToEnd(); - } + using StreamReader reader = new(stream); - #region Methods - /// - /// Captures the network packets on the network adapter asynchronously for a certain period of time and filters the packets according to the protocol. - /// - /// Duration in seconds. - /// to filter on. - public void CaptureAsync(int duration, Protocol protocol) + PSDiscoveryProtocolModule = reader.ReadToEnd(); + } + + #region Methods + /// + /// Captures the network packets on the network adapter asynchronously for a certain period of time and filters the packets according to the protocol. + /// + /// Duration in seconds. + /// to filter on. + public void CaptureAsync(int duration, Protocol protocol) + { + Task.Run(() => { - Task.Run(() => + using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create()) { - using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create()) - { - - powerShell.AddScript("Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process"); - powerShell.AddScript("Import-Module NetAdapter"); - powerShell.AddScript(PSDiscoveryProtocolModule); - powerShell.AddScript($"Invoke-DiscoveryProtocolCapture -Duration {duration}" + (protocol != Protocol.LLDP_CDP ? $" -Type {protocol}" : "") + " -Force | Get-DiscoveryProtocolData"); - Collection PSOutput = powerShell.Invoke(); + powerShell.AddScript("Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process"); + powerShell.AddScript("Import-Module NetAdapter"); + powerShell.AddScript(PSDiscoveryProtocolModule); + powerShell.AddScript($"Invoke-DiscoveryProtocolCapture -Duration {duration}" + (protocol != Protocol.LLDP_CDP ? $" -Type {protocol}" : "") + " -Force | Get-DiscoveryProtocolData"); - if (powerShell.Streams.Error.Count > 0) - { - StringBuilder stringBuilder = new(); + Collection PSOutput = powerShell.Invoke(); - foreach (var error in powerShell.Streams.Error) - { - if (string.IsNullOrEmpty(stringBuilder.ToString())) - stringBuilder.Append(Environment.NewLine); + if (powerShell.Streams.Error.Count > 0) + { + StringBuilder stringBuilder = new(); - stringBuilder.Append(error.Exception.Message); - } + foreach (var error in powerShell.Streams.Error) + { + if (string.IsNullOrEmpty(stringBuilder.ToString())) + stringBuilder.Append(Environment.NewLine); - OnErrorReceived(new DiscoveryProtocolErrorArgs(stringBuilder.ToString())); + stringBuilder.Append(error.Exception.Message); } - if (powerShell.Streams.Warning.Count > 0) - { - StringBuilder stringBuilder = new(); - foreach (var warning in powerShell.Streams.Warning) - { - if (string.IsNullOrEmpty(stringBuilder.ToString())) - stringBuilder.Append(Environment.NewLine); + OnErrorReceived(new DiscoveryProtocolErrorArgs(stringBuilder.ToString())); + } + if (powerShell.Streams.Warning.Count > 0) + { + StringBuilder stringBuilder = new(); - stringBuilder.Append(warning.Message); - } + foreach (var warning in powerShell.Streams.Warning) + { + if (string.IsNullOrEmpty(stringBuilder.ToString())) + stringBuilder.Append(Environment.NewLine); - OnWarningReceived(new DiscoveryProtocolWarningArgs(stringBuilder.ToString())); + stringBuilder.Append(warning.Message); } - foreach (PSObject outputItem in PSOutput) - { - if (outputItem == null) - continue; + OnWarningReceived(new DiscoveryProtocolWarningArgs(stringBuilder.ToString())); + } + + foreach (PSObject outputItem in PSOutput) + { + if (outputItem == null) + continue; - List ipAddresses = new(); + List ipAddresses = new(); - if (outputItem.Properties["IPAddress"] != null) + if (outputItem.Properties["IPAddress"] != null) + { + foreach (var ipAddress in outputItem.Properties["IPAddress"].Value as List) { - foreach (var ipAddress in outputItem.Properties["IPAddress"].Value as List) - { - ipAddresses.Add(ipAddress); - } + ipAddresses.Add(ipAddress); } + } - List managements = new(); + List managements = new(); - if (outputItem.Properties["Management"] != null) + if (outputItem.Properties["Management"] != null) + { + foreach (var management in outputItem.Properties["Management"].Value as List) { - foreach (var management in outputItem.Properties["Management"].Value as List) - { - managements.Add(management); - } + managements.Add(management); } - - var packageInfo = new DiscoveryProtocolPackageInfo - { - Device = outputItem.Properties["Device"]?.Value.ToString(), - DeviceDescription = outputItem.Properties["SystemDescription"]?.Value.ToString(), - Port = outputItem.Properties["Port"]?.Value.ToString(), - PortDescription = outputItem.Properties["PortDescription"]?.Value.ToString(), - Model = outputItem.Properties["Model"]?.Value.ToString(), - IPAddress = string.Join("; ", ipAddresses), - VLAN = outputItem.Properties["VLAN"]?.Value.ToString(), - Protocol = outputItem.Properties["Type"]?.Value.ToString(), - TimeToLive = outputItem.Properties["TimeToLive"]?.Value.ToString(), - Management = string.Join("; ", managements), - ChassisId = outputItem.Properties["ChassisId"]?.Value.ToString(), - LocalConnection = outputItem.Properties["Connection"]?.Value.ToString(), - LocalInterface = outputItem.Properties["Interface"]?.Value.ToString(), - }; - - OnPackageReceived(new DiscoveryProtocolPackageArgs(packageInfo)); } + + var packageInfo = new DiscoveryProtocolPackageInfo + { + Device = outputItem.Properties["Device"]?.Value.ToString(), + DeviceDescription = outputItem.Properties["SystemDescription"]?.Value.ToString(), + Port = outputItem.Properties["Port"]?.Value.ToString(), + PortDescription = outputItem.Properties["PortDescription"]?.Value.ToString(), + Model = outputItem.Properties["Model"]?.Value.ToString(), + IPAddress = string.Join("; ", ipAddresses), + VLAN = outputItem.Properties["VLAN"]?.Value.ToString(), + Protocol = outputItem.Properties["Type"]?.Value.ToString(), + TimeToLive = outputItem.Properties["TimeToLive"]?.Value.ToString(), + Management = string.Join("; ", managements), + ChassisId = outputItem.Properties["ChassisId"]?.Value.ToString(), + LocalConnection = outputItem.Properties["Connection"]?.Value.ToString(), + LocalInterface = outputItem.Properties["Interface"]?.Value.ToString(), + }; + + OnPackageReceived(new DiscoveryProtocolPackageArgs(packageInfo)); } + } - OnComplete(); - }); - } - #endregion + OnComplete(); + }); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/DiscoveryProtocolErrorArgs.cs b/Source/NETworkManager.Models/Network/DiscoveryProtocolErrorArgs.cs index f85f8df083..2da5767943 100644 --- a/Source/NETworkManager.Models/Network/DiscoveryProtocolErrorArgs.cs +++ b/Source/NETworkManager.Models/Network/DiscoveryProtocolErrorArgs.cs @@ -1,30 +1,29 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Event arguments when an Error message is returned. +/// +public class DiscoveryProtocolErrorArgs : System.EventArgs { /// - /// Event arguments when an Error message is returned. + /// Error message. /// - public class DiscoveryProtocolErrorArgs : System.EventArgs - { - /// - /// Error message. - /// - public string Message { get; private set; } + public string Message { get; private set; } - /// - /// Initializes a new instance of the class. - /// - public DiscoveryProtocolErrorArgs() - { + /// + /// Initializes a new instance of the class. + /// + public DiscoveryProtocolErrorArgs() + { - } + } - /// - /// Initializes a new instance of the class with an error . - /// - /// Error message. - public DiscoveryProtocolErrorArgs(string message) - { - Message = message; - } + /// + /// Initializes a new instance of the class with an error . + /// + /// Error message. + public DiscoveryProtocolErrorArgs(string message) + { + Message = message; } } diff --git a/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageArgs.cs b/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageArgs.cs index 5050f8c986..ae44764461 100644 --- a/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageArgs.cs +++ b/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageArgs.cs @@ -1,30 +1,29 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Event arguments when a discovery protocol package is returned. +/// +public class DiscoveryProtocolPackageArgs : System.EventArgs { /// - /// Event arguments when a discovery protocol package is returned. + /// Contains the which is returned. /// - public class DiscoveryProtocolPackageArgs : System.EventArgs - { - /// - /// Contains the which is returned. - /// - public DiscoveryProtocolPackageInfo PackageInfo { get; set; } + public DiscoveryProtocolPackageInfo PackageInfo { get; set; } - /// - /// Initializes a new instance of the class. - /// - public DiscoveryProtocolPackageArgs() - { + /// + /// Initializes a new instance of the class. + /// + public DiscoveryProtocolPackageArgs() + { - } + } - /// - /// Initializes a new instance of the class with a discovery protocol package (). - /// - /// Discovery protocol package information - public DiscoveryProtocolPackageArgs(DiscoveryProtocolPackageInfo packageInfo) - { - PackageInfo = packageInfo; - } + /// + /// Initializes a new instance of the class with a discovery protocol package (). + /// + /// Discovery protocol package information + public DiscoveryProtocolPackageArgs(DiscoveryProtocolPackageInfo packageInfo) + { + PackageInfo = packageInfo; } } diff --git a/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageInfo.cs b/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageInfo.cs index d62e77fe24..9fc6969d15 100644 --- a/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageInfo.cs +++ b/Source/NETworkManager.Models/Network/DiscoveryProtocolPackageInfo.cs @@ -1,81 +1,80 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class contains discovery protocol package informations. +/// +public class DiscoveryProtocolPackageInfo { /// - /// Class contains discovery protocol package informations. + /// Device name. /// - public class DiscoveryProtocolPackageInfo - { - /// - /// Device name. - /// - public string Device { get; set; } + public string Device { get; set; } - /// - /// Device description. - /// - public string DeviceDescription { get; set; } + /// + /// Device description. + /// + public string DeviceDescription { get; set; } - /// - /// Port name or number. - /// - public string Port { get; set; } + /// + /// Port name or number. + /// + public string Port { get; set; } - /// - /// Port description. - /// - public string PortDescription { get; set; } - - /// - /// Device model. - /// - public string Model { get; set; } + /// + /// Port description. + /// + public string PortDescription { get; set; } + + /// + /// Device model. + /// + public string Model { get; set; } - /// - /// Management VLAN. - /// - public string VLAN { get; set; } + /// + /// Management VLAN. + /// + public string VLAN { get; set; } - /// - /// IP address(es) of the device. - /// - public string IPAddress { get; set; } + /// + /// IP address(es) of the device. + /// + public string IPAddress { get; set; } - /// - /// Protocol type. - /// - public string Protocol { get; set; } + /// + /// Protocol type. + /// + public string Protocol { get; set; } - /// - /// Time to live of the LLDP/CDP package. - /// - public string TimeToLive { get; set; } + /// + /// Time to live of the LLDP/CDP package. + /// + public string TimeToLive { get; set; } - /// - /// Device Management. - /// - public string Management { get; set; } + /// + /// Device Management. + /// + public string Management { get; set; } - /// - /// Device Chassis ID. - /// - public string ChassisId { get; set; } + /// + /// Device Chassis ID. + /// + public string ChassisId { get; set; } - /// - /// Local connection used to capture the LLDP/CDP package. - /// - public string LocalConnection { get; set; } + /// + /// Local connection used to capture the LLDP/CDP package. + /// + public string LocalConnection { get; set; } - /// - /// Local interface used to capture the LLDP/CDP package. - /// - public string LocalInterface { get; set; } + /// + /// Local interface used to capture the LLDP/CDP package. + /// + public string LocalInterface { get; set; } - /// - /// Initializes a new instance of the class. - /// - public DiscoveryProtocolPackageInfo() - { + /// + /// Initializes a new instance of the class. + /// + public DiscoveryProtocolPackageInfo() + { - } } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/DiscoveryProtocolWarningArgs.cs b/Source/NETworkManager.Models/Network/DiscoveryProtocolWarningArgs.cs index ef64fb433c..80bfd892c0 100644 --- a/Source/NETworkManager.Models/Network/DiscoveryProtocolWarningArgs.cs +++ b/Source/NETworkManager.Models/Network/DiscoveryProtocolWarningArgs.cs @@ -1,30 +1,29 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Event arguments when a Warning message is returned. +/// +public class DiscoveryProtocolWarningArgs : System.EventArgs { /// - /// Event arguments when a Warning message is returned. + /// Warning message. /// - public class DiscoveryProtocolWarningArgs : System.EventArgs - { - /// - /// Warning message. - /// - public string Message { get; private set; } + public string Message { get; private set; } - /// - /// Initializes a new instance of the class. - /// - public DiscoveryProtocolWarningArgs() - { + /// + /// Initializes a new instance of the class. + /// + public DiscoveryProtocolWarningArgs() + { - } + } - /// - /// Initializes a new instance of the class with a warning . - /// - /// Warning message. - public DiscoveryProtocolWarningArgs(string message) - { - Message = message; - } + /// + /// Initializes a new instance of the class with a warning . + /// + /// Warning message. + public DiscoveryProtocolWarningArgs(string message) + { + Message = message; } } diff --git a/Source/NETworkManager.Models/Network/HostFoundArgs.cs b/Source/NETworkManager.Models/Network/HostFoundArgs.cs index acb2277a08..83f9c61d05 100644 --- a/Source/NETworkManager.Models/Network/HostFoundArgs.cs +++ b/Source/NETworkManager.Models/Network/HostFoundArgs.cs @@ -1,25 +1,24 @@ using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class HostFoundArgs : System.EventArgs { - public class HostFoundArgs : System.EventArgs - { - public PingInfo PingInfo { get; set; } - public string Hostname { get; set; } - public PhysicalAddress MACAddress { get; set; } - public string Vendor { get; set; } + public PingInfo PingInfo { get; set; } + public string Hostname { get; set; } + public PhysicalAddress MACAddress { get; set; } + public string Vendor { get; set; } - public HostFoundArgs() - { + public HostFoundArgs() + { - } + } - public HostFoundArgs(PingInfo pingInfo, string hostname, PhysicalAddress macAddress, string vendor) - { - PingInfo = pingInfo; - Hostname = hostname; - MACAddress = macAddress; - Vendor = vendor; - } + public HostFoundArgs(PingInfo pingInfo, string hostname, PhysicalAddress macAddress, string vendor) + { + PingInfo = pingInfo; + Hostname = hostname; + MACAddress = macAddress; + Vendor = vendor; } } diff --git a/Source/NETworkManager.Models/Network/HostInfo.cs b/Source/NETworkManager.Models/Network/HostInfo.cs index a0918d31f9..7694922007 100644 --- a/Source/NETworkManager.Models/Network/HostInfo.cs +++ b/Source/NETworkManager.Models/Network/HostInfo.cs @@ -1,32 +1,31 @@ using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class HostInfo { - public class HostInfo - { - public PingInfo PingInfo { get; set; } - public string Hostname { get; set; } - public PhysicalAddress MACAddress { get; set; } - public string Vendor { get; set; } + public PingInfo PingInfo { get; set; } + public string Hostname { get; set; } + public PhysicalAddress MACAddress { get; set; } + public string Vendor { get; set; } - public string MACAddressString => MACAddress?.ToString(); + public string MACAddressString => MACAddress?.ToString(); - public HostInfo() - { + public HostInfo() + { - } + } - public HostInfo(PingInfo pingInfo, string hostname, PhysicalAddress macAddress, string vendor) - { - PingInfo = pingInfo; - Hostname = hostname; - MACAddress = macAddress; - Vendor = vendor; - } + public HostInfo(PingInfo pingInfo, string hostname, PhysicalAddress macAddress, string vendor) + { + PingInfo = pingInfo; + Hostname = hostname; + MACAddress = macAddress; + Vendor = vendor; + } - public static HostInfo Parse(HostFoundArgs e) - { - return new HostInfo(e.PingInfo, e.Hostname, e.MACAddress, e.Vendor); - } + public static HostInfo Parse(HostFoundArgs e) + { + return new HostInfo(e.PingInfo, e.Hostname, e.MACAddress, e.Vendor); } } diff --git a/Source/NETworkManager.Models/Network/HostNotFoundException.cs b/Source/NETworkManager.Models/Network/HostNotFoundException.cs index 21c379e93a..ad3f8999a5 100644 --- a/Source/NETworkManager.Models/Network/HostNotFoundException.cs +++ b/Source/NETworkManager.Models/Network/HostNotFoundException.cs @@ -1,22 +1,21 @@ using System; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class HostNotFoundException : Exception { - public class HostNotFoundException : Exception + public HostNotFoundException() { - public HostNotFoundException() - { - } + } - public HostNotFoundException(string message) : base(message) - { + public HostNotFoundException(string message) : base(message) + { - } + } - public HostNotFoundException(string message, Exception innerException) : base(message, innerException) - { + public HostNotFoundException(string message, Exception innerException) : base(message, innerException) + { - } } } diff --git a/Source/NETworkManager.Models/Network/HostRangeHelper.cs b/Source/NETworkManager.Models/Network/HostRangeHelper.cs index b989221977..bba8cdc1dc 100644 --- a/Source/NETworkManager.Models/Network/HostRangeHelper.cs +++ b/Source/NETworkManager.Models/Network/HostRangeHelper.cs @@ -10,196 +10,195 @@ using System.Threading; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public static class HostRangeHelper { - public static class HostRangeHelper + public static Task CreateIPAddressesFromIPRangesAsync(string[] ipRanges, CancellationToken cancellationToken) { - public static Task CreateIPAddressesFromIPRangesAsync(string[] ipRanges, CancellationToken cancellationToken) - { - return Task.Run(() => CreateIPAddressesFromIPRanges(ipRanges, cancellationToken), cancellationToken); - } + return Task.Run(() => CreateIPAddressesFromIPRanges(ipRanges, cancellationToken), cancellationToken); + } + + public static IPAddress[] CreateIPAddressesFromIPRanges(string[] ipRanges, CancellationToken cancellationToken) + { + var bag = new ConcurrentBag(); - public static IPAddress[] CreateIPAddressesFromIPRanges(string[] ipRanges, CancellationToken cancellationToken) + var parallelOptions = new ParallelOptions { - var bag = new ConcurrentBag(); + CancellationToken = cancellationToken + }; - var parallelOptions = new ParallelOptions + foreach (var ipOrRange in ipRanges) + { + switch (ipOrRange) { - CancellationToken = cancellationToken - }; + // 192.168.0.1 or 2001:db8:85a3::8a2e:370:7334 + case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRegex) || Regex.IsMatch(ipOrRange, RegexHelper.IPv6AddressRegex): + bag.Add(IPAddress.Parse(ipOrRange)); + break; - foreach (var ipOrRange in ipRanges) - { - switch (ipOrRange) - { - // 192.168.0.1 or 2001:db8:85a3::8a2e:370:7334 - case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRegex) || Regex.IsMatch(ipOrRange, RegexHelper.IPv6AddressRegex): - bag.Add(IPAddress.Parse(ipOrRange)); - break; - - // 192.168.0.0/24 or 192.168.0.0/255.255.255.0 - case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressCidrRegex) || Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSubnetmaskRegex): - var network = IPNetwork.Parse(ipOrRange); - - Parallel.For(IPv4Address.ToInt32(network.Network), IPv4Address.ToInt32(network.Broadcast) + 1, parallelOptions, i => - { - bag.Add(IPv4Address.FromInt32(i)); + // 192.168.0.0/24 or 192.168.0.0/255.255.255.0 + case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressCidrRegex) || Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSubnetmaskRegex): + var network = IPNetwork.Parse(ipOrRange); - parallelOptions.CancellationToken.ThrowIfCancellationRequested(); - }); + Parallel.For(IPv4Address.ToInt32(network.Network), IPv4Address.ToInt32(network.Broadcast) + 1, parallelOptions, i => + { + bag.Add(IPv4Address.FromInt32(i)); - break; + parallelOptions.CancellationToken.ThrowIfCancellationRequested(); + }); - // 192.168.0.0 - 192.168.0.100 - case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRangeRegex): - var range = ipOrRange.Split('-'); + break; - Parallel.For(IPv4Address.ToInt32(IPAddress.Parse(range[0])), IPv4Address.ToInt32(IPAddress.Parse(range[1])) + 1, parallelOptions, i => - { - bag.Add(IPv4Address.FromInt32(i)); + // 192.168.0.0 - 192.168.0.100 + case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRangeRegex): + var range = ipOrRange.Split('-'); - parallelOptions.CancellationToken.ThrowIfCancellationRequested(); - }); + Parallel.For(IPv4Address.ToInt32(IPAddress.Parse(range[0])), IPv4Address.ToInt32(IPAddress.Parse(range[1])) + 1, parallelOptions, i => + { + bag.Add(IPv4Address.FromInt32(i)); - break; + parallelOptions.CancellationToken.ThrowIfCancellationRequested(); + }); - // 192.168.[50-100,200].1 --> 192.168.50.1, 192.168.51.1, 192.168.52.1, {..}, 192.168.200.1 - case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSpecialRangeRegex): - var octets = ipOrRange.Split('.'); + break; - var list = new List>(); + // 192.168.[50-100,200].1 --> 192.168.50.1, 192.168.51.1, 192.168.52.1, {..}, 192.168.200.1 + case var _ when Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSpecialRangeRegex): + var octets = ipOrRange.Split('.'); - // Go through each octet... - foreach (var octet in octets) - { - var innerList = new List(); + var list = new List>(); + + // Go through each octet... + foreach (var octet in octets) + { + var innerList = new List(); - // Create a range for each octet - if (Regex.IsMatch(octet, RegexHelper.SpecialRangeRegex)) + // Create a range for each octet + if (Regex.IsMatch(octet, RegexHelper.SpecialRangeRegex)) + { + foreach (var numberOrRange in octet[1..^1].Split(',')) { - foreach (var numberOrRange in octet[1..^1].Split(',')) + // 50-100 + if (numberOrRange.Contains('-')) { - // 50-100 - if (numberOrRange.Contains('-')) - { - var rangeNumbers = numberOrRange.Split('-'); - - for (var i = int.Parse(rangeNumbers[0]); i < (int.Parse(rangeNumbers[1]) + 1); i++) - { - innerList.Add(i); - } - } // 200 - else + var rangeNumbers = numberOrRange.Split('-'); + + for (var i = int.Parse(rangeNumbers[0]); i < (int.Parse(rangeNumbers[1]) + 1); i++) { - innerList.Add(int.Parse(numberOrRange)); + innerList.Add(i); } + } // 200 + else + { + innerList.Add(int.Parse(numberOrRange)); } } - else - { - innerList.Add(int.Parse(octet)); - } - - list.Add(innerList); } + else + { + innerList.Add(int.Parse(octet)); + } + + list.Add(innerList); + } - // Build the new ipv4 - foreach (var i in list[0]) + // Build the new ipv4 + foreach (var i in list[0]) + { + foreach (var j in list[1]) { - foreach (var j in list[1]) + foreach (var k in list[2]) { - foreach (var k in list[2]) + foreach (var h in list[3]) { - foreach (var h in list[3]) - { - bag.Add(IPAddress.Parse($"{i}.{j}.{k}.{h}")); - } + bag.Add(IPAddress.Parse($"{i}.{j}.{k}.{h}")); } } } + } - break; - } - } - - return bag.ToArray(); + break; + } } - public static Task> ResolveHostnamesInIPRangesAsync(string[] ipRanges, bool dnsResolveHostnamePreferIPv4, CancellationToken cancellationToken) - { - return Task.Run(() => ResolveHostnamesInIPRanges(ipRanges, dnsResolveHostnamePreferIPv4, cancellationToken), cancellationToken); - } + return bag.ToArray(); + } - public static List ResolveHostnamesInIPRanges(string[] ipRanges, bool dnsResolveHostnamePreferIPv4, CancellationToken cancellationToken) - { - var bag = new ConcurrentBag(); + public static Task> ResolveHostnamesInIPRangesAsync(string[] ipRanges, bool dnsResolveHostnamePreferIPv4, CancellationToken cancellationToken) + { + return Task.Run(() => ResolveHostnamesInIPRanges(ipRanges, dnsResolveHostnamePreferIPv4, cancellationToken), cancellationToken); + } + + public static List ResolveHostnamesInIPRanges(string[] ipRanges, bool dnsResolveHostnamePreferIPv4, CancellationToken cancellationToken) + { + var bag = new ConcurrentBag(); - var exceptions = new ConcurrentQueue(); + var exceptions = new ConcurrentQueue(); - Parallel.ForEach(ipRanges, new ParallelOptions { CancellationToken = cancellationToken }, ipHostOrRange => + Parallel.ForEach(ipRanges, new ParallelOptions { CancellationToken = cancellationToken }, ipHostOrRange => + { + switch (ipHostOrRange) { - switch (ipHostOrRange) - { - // 192.168.0.1 - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRegex): - // 192.168.0.0/24 - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressCidrRegex): - // 192.168.0.0/255.255.255.0 - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSubnetmaskRegex): - // 192.168.0.0 - 192.168.0.100 - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRangeRegex): - // 192.168.[50-100].1 - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSpecialRangeRegex): - // 2001:db8:85a3::8a2e:370:7334 - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv6AddressRegex): - bag.Add(ipHostOrRange); - break; + // 192.168.0.1 + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRegex): + // 192.168.0.0/24 + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressCidrRegex): + // 192.168.0.0/255.255.255.0 + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSubnetmaskRegex): + // 192.168.0.0 - 192.168.0.100 + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRangeRegex): + // 192.168.[50-100].1 + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSpecialRangeRegex): + // 2001:db8:85a3::8a2e:370:7334 + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.IPv6AddressRegex): + bag.Add(ipHostOrRange); + break; + + // example.com + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameRegex): + using (var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(ipHostOrRange, dnsResolveHostnamePreferIPv4)) + { + // Wait for task inside a Parallel.Foreach + dnsResolverTask.Wait(); + + if (!dnsResolverTask.Result.HasError) + bag.Add($"{dnsResolverTask.Result.Value}"); + else + exceptions.Enqueue(new HostNotFoundException(ipHostOrRange)); + } + + break; - // example.com - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameRegex): - using (var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(ipHostOrRange, dnsResolveHostnamePreferIPv4)) - { - // Wait for task inside a Parallel.Foreach - dnsResolverTask.Wait(); - - if (!dnsResolverTask.Result.HasError) - bag.Add($"{dnsResolverTask.Result.Value}"); - else - exceptions.Enqueue(new HostNotFoundException(ipHostOrRange)); - } + // example.com/24 or example.com/255.255.255.128 + case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameCidrRegex) || Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameSubnetmaskRegex): + var hostAndSubnet = ipHostOrRange.Split('/'); - break; - - // example.com/24 or example.com/255.255.255.128 - case var _ when Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameCidrRegex) || Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameSubnetmaskRegex): - var hostAndSubnet = ipHostOrRange.Split('/'); + // Only support IPv4 + using (var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(hostAndSubnet[0], true)) + { + // Wait for task inside a Parallel.Foreach + dnsResolverTask.Wait(); - // Only support IPv4 - using (var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(hostAndSubnet[0], true)) + if (!dnsResolverTask.Result.HasError) { - // Wait for task inside a Parallel.Foreach - dnsResolverTask.Wait(); - - if (!dnsResolverTask.Result.HasError) - { - // Only support IPv4 for ranges for now - if (dnsResolverTask.Result.Value.AddressFamily == AddressFamily.InterNetwork) - bag.Add($"{dnsResolverTask.Result.Value}/{hostAndSubnet[1]}"); - else - exceptions.Enqueue(new HostNotFoundException(hostAndSubnet[0])); - } + // Only support IPv4 for ranges for now + if (dnsResolverTask.Result.Value.AddressFamily == AddressFamily.InterNetwork) + bag.Add($"{dnsResolverTask.Result.Value}/{hostAndSubnet[1]}"); else exceptions.Enqueue(new HostNotFoundException(hostAndSubnet[0])); } + else + exceptions.Enqueue(new HostNotFoundException(hostAndSubnet[0])); + } - break; - } - }); + break; + } + }); - if (!exceptions.IsEmpty) - throw new AggregateException(exceptions); + if (!exceptions.IsEmpty) + throw new AggregateException(exceptions); - return bag.ToList(); - } + return bag.ToList(); } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/IPNetworkInfo.cs b/Source/NETworkManager.Models/Network/IPNetworkInfo.cs index c0debf394f..f77ec29c30 100644 --- a/Source/NETworkManager.Models/Network/IPNetworkInfo.cs +++ b/Source/NETworkManager.Models/Network/IPNetworkInfo.cs @@ -1,40 +1,39 @@ using System.Net; using System.Numerics; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class IPNetworkInfo { - public class IPNetworkInfo - { - public IPAddress Network { get; set; } - public IPAddress Broadcast { get; set; } - public BigInteger Total { get; set; } - public IPAddress Netmask { get; set; } - public int Cidr { get; set; } - public IPAddress FirstUsable { get; set; } - public IPAddress LastUsable { get; set; } - public BigInteger Usable { get; set; } + public IPAddress Network { get; set; } + public IPAddress Broadcast { get; set; } + public BigInteger Total { get; set; } + public IPAddress Netmask { get; set; } + public int Cidr { get; set; } + public IPAddress FirstUsable { get; set; } + public IPAddress LastUsable { get; set; } + public BigInteger Usable { get; set; } - public int NetworkInt32 => Network.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(Network) : 0; - public int BroadcastInt32 => Broadcast.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(Broadcast) : 0; - public int NetmaskInt32 => Netmask.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(Netmask) : 0; - public int FirstUsableInt32 => FirstUsable.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(FirstUsable) : 0; - public int LastUsableInt32 => LastUsable.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(LastUsable) : 0; + public int NetworkInt32 => Network.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(Network) : 0; + public int BroadcastInt32 => Broadcast.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(Broadcast) : 0; + public int NetmaskInt32 => Netmask.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(Netmask) : 0; + public int FirstUsableInt32 => FirstUsable.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(FirstUsable) : 0; + public int LastUsableInt32 => LastUsable.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(LastUsable) : 0; - public IPNetworkInfo() - { + public IPNetworkInfo() + { - } + } - public IPNetworkInfo(IPNetwork ipNetwork) - { - Network = ipNetwork.Network; - Broadcast = ipNetwork.Broadcast; - Total = ipNetwork.Total; - Netmask = ipNetwork.Netmask; - Cidr = ipNetwork.Cidr; - FirstUsable = ipNetwork.FirstUsable; - LastUsable = ipNetwork.LastUsable; - Usable = ipNetwork.Usable; - } + public IPNetworkInfo(IPNetwork ipNetwork) + { + Network = ipNetwork.Network; + Broadcast = ipNetwork.Broadcast; + Total = ipNetwork.Total; + Netmask = ipNetwork.Netmask; + Cidr = ipNetwork.Cidr; + FirstUsable = ipNetwork.FirstUsable; + LastUsable = ipNetwork.LastUsable; + Usable = ipNetwork.Usable; } } diff --git a/Source/NETworkManager.Models/Network/IPScanner.cs b/Source/NETworkManager.Models/Network/IPScanner.cs index 3ab87eed0c..ef8d3e4cf1 100644 --- a/Source/NETworkManager.Models/Network/IPScanner.cs +++ b/Source/NETworkManager.Models/Network/IPScanner.cs @@ -7,188 +7,187 @@ using System.Threading; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class IPScanner { - public class IPScanner - { - #region Variables - private int _progressValue; + #region Variables + private int _progressValue; - public int Threads = 256; - public int ICMPTimeout = 4000; - public byte[] ICMPBuffer = new byte[32]; - public int ICMPAttempts = 2; - public bool ResolveHostname = true; - public bool DNSShowErrorMessage = false; + public int Threads = 256; + public int ICMPTimeout = 4000; + public byte[] ICMPBuffer = new byte[32]; + public int ICMPAttempts = 2; + public bool ResolveHostname = true; + public bool DNSShowErrorMessage = false; - public bool ResolveMACAddress = false; - public bool ShowScanResultForAllIPAddresses = false; - #endregion + public bool ResolveMACAddress = false; + public bool ShowScanResultForAllIPAddresses = false; + #endregion - #region Events - public event EventHandler HostFound; + #region Events + public event EventHandler HostFound; - protected virtual void OnHostFound(HostFoundArgs e) - { - HostFound?.Invoke(this, e); - } + protected virtual void OnHostFound(HostFoundArgs e) + { + HostFound?.Invoke(this, e); + } - public event EventHandler ScanComplete; + public event EventHandler ScanComplete; - protected virtual void OnScanComplete() - { - ScanComplete?.Invoke(this, EventArgs.Empty); - } + protected virtual void OnScanComplete() + { + ScanComplete?.Invoke(this, EventArgs.Empty); + } - public event EventHandler ProgressChanged; + public event EventHandler ProgressChanged; - protected virtual void OnProgressChanged() - { - ProgressChanged?.Invoke(this, new ProgressChangedArgs(_progressValue)); - } + protected virtual void OnProgressChanged() + { + ProgressChanged?.Invoke(this, new ProgressChangedArgs(_progressValue)); + } - public event EventHandler UserHasCanceled; + public event EventHandler UserHasCanceled; - protected virtual void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - #endregion + protected virtual void OnUserHasCanceled() + { + UserHasCanceled?.Invoke(this, EventArgs.Empty); + } + #endregion - #region Methods - public void ScanAsync(IPAddress[] ipAddresses, CancellationToken cancellationToken) + #region Methods + public void ScanAsync(IPAddress[] ipAddresses, CancellationToken cancellationToken) + { + // Start the scan in a separat task + Task.Run(() => { - // Start the scan in a separat task - Task.Run(() => - { - _progressValue = 0; + _progressValue = 0; - // Modify the ThreadPool for better performance - ThreadPool.GetMinThreads(out var workerThreads, out var completionPortThreads); - ThreadPool.SetMinThreads(workerThreads + Threads, completionPortThreads + Threads); + // Modify the ThreadPool for better performance + ThreadPool.GetMinThreads(out var workerThreads, out var completionPortThreads); + ThreadPool.SetMinThreads(workerThreads + Threads, completionPortThreads + Threads); - try + try + { + var parallelOptions = new ParallelOptions { - var parallelOptions = new ParallelOptions - { - CancellationToken = cancellationToken, - MaxDegreeOfParallelism = Threads - }; + CancellationToken = cancellationToken, + MaxDegreeOfParallelism = Threads + }; - Parallel.ForEach(ipAddresses, parallelOptions, ipAddress => - { - var pingInfo = new PingInfo(); - var pingable = false; + Parallel.ForEach(ipAddresses, parallelOptions, ipAddress => + { + var pingInfo = new PingInfo(); + var pingable = false; - // PING - using (var ping = new System.Net.NetworkInformation.Ping()) + // PING + using (var ping = new System.Net.NetworkInformation.Ping()) + { + for (var i = 0; i < ICMPAttempts; i++) { - for (var i = 0; i < ICMPAttempts; i++) + try { - try - { - var pingReply = ping.Send(ipAddress, ICMPTimeout, ICMPBuffer); - - if (pingReply != null && IPStatus.Success == pingReply.Status) - { - if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) - pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status); - else - pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Status); + var pingReply = ping.Send(ipAddress, ICMPTimeout, ICMPBuffer); - pingable = true; - break; // Continue with the next checks... - } + if (pingReply != null && IPStatus.Success == pingReply.Status) + { + if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status); + else + pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Status); - if (pingReply != null) - pingInfo = new PingInfo(ipAddress, pingReply.Status); + pingable = true; + break; // Continue with the next checks... } - catch (PingException) - { } - // Don't scan again, if the user has canceled (when more than 1 attempt) - if (cancellationToken.IsCancellationRequested) - break; + if (pingReply != null) + pingInfo = new PingInfo(ipAddress, pingReply.Status); } + catch (PingException) + { } + + // Don't scan again, if the user has canceled (when more than 1 attempt) + if (cancellationToken.IsCancellationRequested) + break; } + } - if (pingable || ShowScanResultForAllIPAddresses) - { - // DNS - var hostname = string.Empty; + if (pingable || ShowScanResultForAllIPAddresses) + { + // DNS + var hostname = string.Empty; - if (ResolveHostname) - { - // Don't use await in Paralle.ForEach, this will break - var dnsResolverTask = DNSClient.GetInstance().ResolvePtrAsync(ipAddress); + if (ResolveHostname) + { + // Don't use await in Paralle.ForEach, this will break + var dnsResolverTask = DNSClient.GetInstance().ResolvePtrAsync(ipAddress); - // Wait for task inside a Parallel.Foreach - dnsResolverTask.Wait(); + // Wait for task inside a Parallel.Foreach + dnsResolverTask.Wait(); - if (!dnsResolverTask.Result.HasError) - hostname = dnsResolverTask.Result.Value; - else - hostname = DNSShowErrorMessage ? dnsResolverTask.Result.ErrorMessage : string.Empty; - } + if (!dnsResolverTask.Result.HasError) + hostname = dnsResolverTask.Result.Value; + else + hostname = DNSShowErrorMessage ? dnsResolverTask.Result.ErrorMessage : string.Empty; + } - // ARP - PhysicalAddress macAddress = null; - var vendor = string.Empty; + // ARP + PhysicalAddress macAddress = null; + var vendor = string.Empty; - if (ResolveMACAddress) - { - // Get info from arp table - var arpTableInfo = ARP.GetTable().FirstOrDefault(p => p.IPAddress.ToString() == ipAddress.ToString()); + if (ResolveMACAddress) + { + // Get info from arp table + var arpTableInfo = ARP.GetTable().FirstOrDefault(p => p.IPAddress.ToString() == ipAddress.ToString()); - if (arpTableInfo != null) - macAddress = arpTableInfo.MACAddress; + if (arpTableInfo != null) + macAddress = arpTableInfo.MACAddress; - // Check if it is the local mac - if (macAddress == null) - { - var networkInferfaceInfo = NetworkInterface.GetNetworkInterfaces().FirstOrDefault(p => p.IPv4Address.Any(x => x.Item1.Equals(ipAddress))); + // Check if it is the local mac + if (macAddress == null) + { + var networkInferfaceInfo = NetworkInterface.GetNetworkInterfaces().FirstOrDefault(p => p.IPv4Address.Any(x => x.Item1.Equals(ipAddress))); - if (networkInferfaceInfo != null) - macAddress = networkInferfaceInfo.PhysicalAddress; - } + if (networkInferfaceInfo != null) + macAddress = networkInferfaceInfo.PhysicalAddress; + } - // Vendor lookup - if (macAddress != null) - { - var info = OUILookup.Lookup(macAddress.ToString()).FirstOrDefault(); + // Vendor lookup + if (macAddress != null) + { + var info = OUILookup.Lookup(macAddress.ToString()).FirstOrDefault(); - if (info != null) - vendor = info.Vendor; - } + if (info != null) + vendor = info.Vendor; } - - OnHostFound(new HostFoundArgs(pingInfo, hostname, macAddress, vendor)); } - IncreaseProgess(); - }); - } - catch (OperationCanceledException) // If user has canceled - { - OnUserHasCanceled(); - } - finally - { - // Reset the ThreadPool to default - ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); - ThreadPool.SetMinThreads(workerThreads - Threads, completionPortThreads - Threads); + OnHostFound(new HostFoundArgs(pingInfo, hostname, macAddress, vendor)); + } - OnScanComplete(); - } - }, cancellationToken); - } + IncreaseProgess(); + }); + } + catch (OperationCanceledException) // If user has canceled + { + OnUserHasCanceled(); + } + finally + { + // Reset the ThreadPool to default + ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); + ThreadPool.SetMinThreads(workerThreads - Threads, completionPortThreads - Threads); - private void IncreaseProgess() - { - // Increase the progress - Interlocked.Increment(ref _progressValue); - OnProgressChanged(); - } - #endregion + OnScanComplete(); + } + }, cancellationToken); + } + + private void IncreaseProgess() + { + // Increase the progress + Interlocked.Increment(ref _progressValue); + OnProgressChanged(); } + #endregion } diff --git a/Source/NETworkManager.Models/Network/IPScannerCustomCommand.cs b/Source/NETworkManager.Models/Network/IPScannerCustomCommand.cs index 1a3fcb6905..d87285d0fd 100644 --- a/Source/NETworkManager.Models/Network/IPScannerCustomCommand.cs +++ b/Source/NETworkManager.Models/Network/IPScannerCustomCommand.cs @@ -2,18 +2,17 @@ using System; using System.Collections.Generic; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public static class IPScannerCustomCommand { - public static class IPScannerCustomCommand + public static List GetDefaultList() { - public static List GetDefaultList() + return new List { - return new List - { - new CustomCommandInfo(Guid.NewGuid(), "Internet Explorer", "iexplore.exe", @"http://$$ipaddress$$/"), - new CustomCommandInfo(Guid.NewGuid(), "Internet Explorer (https)", "iexplore.exe", @"https://$$ipaddress$$/"), - new CustomCommandInfo(Guid.NewGuid(), "Windows Explorer (c$)", "explorer.exe", @"\\$$ipaddress$$\c$") - }; - } + new CustomCommandInfo(Guid.NewGuid(), "Internet Explorer", "iexplore.exe", @"http://$$ipaddress$$/"), + new CustomCommandInfo(Guid.NewGuid(), "Internet Explorer (https)", "iexplore.exe", @"https://$$ipaddress$$/"), + new CustomCommandInfo(Guid.NewGuid(), "Windows Explorer (c$)", "explorer.exe", @"\\$$ipaddress$$\c$") + }; } } diff --git a/Source/NETworkManager.Models/Network/IPv4Address.cs b/Source/NETworkManager.Models/Network/IPv4Address.cs index ac307049e6..e8f870bb04 100644 --- a/Source/NETworkManager.Models/Network/IPv4Address.cs +++ b/Source/NETworkManager.Models/Network/IPv4Address.cs @@ -3,91 +3,90 @@ using System.Linq; using System.Net; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class provides static methods to convert an IPv4 address. +/// +public static class IPv4Address { /// - /// Class provides static methods to convert an IPv4 address. + /// First possible IPv4 multicast address. + /// + private const int IPv4MulticastStart = -536870912; + + /// + /// Last possible IPv4 multicast address. + /// + private const int IPv4MulticastEnd = -268435457; + + /// + /// Method to convert a IPv4 address binary string ("11000000.10101000.00000001.00000001") to human readable string ("192.168.1.1"). + /// + /// IPv4 address as binary string ("11111111111111111111111100000000"). + /// Converted IPv4 address as human readable string ("255.255.255.0"). + public static string ToHumanString(string binaryString) + { + var ipv4AddressBinary = binaryString.Replace(".", ""); + + var ipv4AddressOctets = new List(); + + for (var i = 0; i < ipv4AddressBinary.Length; i += 8) + ipv4AddressOctets.Add(Convert.ToInt32(ipv4AddressBinary.Substring(i, 8), 2).ToString()); + + return string.Join(".", ipv4AddressOctets); + } + + /// + /// Method to convert an human readable IPv4 address ("192.168.1.1") to binary string ("11000000.10101000.00000001.00000001"). /// - public static class IPv4Address + /// IPv4 address as human readable string ("192.168.1.1"). + /// Converted IPv4-Address as binary string ("11000000.10101000.00000001.00000001"). + public static string ToBinaryString(string humanString) { - /// - /// First possible IPv4 multicast address. - /// - private const int IPv4MulticastStart = -536870912; - - /// - /// Last possible IPv4 multicast address. - /// - private const int IPv4MulticastEnd = -268435457; - - /// - /// Method to convert a IPv4 address binary string ("11000000.10101000.00000001.00000001") to human readable string ("192.168.1.1"). - /// - /// IPv4 address as binary string ("11111111111111111111111100000000"). - /// Converted IPv4 address as human readable string ("255.255.255.0"). - public static string ToHumanString(string binaryString) - { - var ipv4AddressBinary = binaryString.Replace(".", ""); - - var ipv4AddressOctets = new List(); - - for (var i = 0; i < ipv4AddressBinary.Length; i += 8) - ipv4AddressOctets.Add(Convert.ToInt32(ipv4AddressBinary.Substring(i, 8), 2).ToString()); - - return string.Join(".", ipv4AddressOctets); - } - - /// - /// Method to convert an human readable IPv4 address ("192.168.1.1") to binary string ("11000000.10101000.00000001.00000001"). - /// - /// IPv4 address as human readable string ("192.168.1.1"). - /// Converted IPv4-Address as binary string ("11000000.10101000.00000001.00000001"). - public static string ToBinaryString(string humanString) - { - return string.Join(".", humanString.Split('.').Select(x => Convert.ToString(int.Parse(x), 2).PadLeft(8, '0')).ToArray()); - } - - /// - /// Method to convert an to . - /// - /// . - /// IP address as - - public static int ToInt32(IPAddress ipAddress) - { - var bytes = ipAddress.GetAddressBytes(); - - if (BitConverter.IsLittleEndian) - Array.Reverse(bytes); - - return BitConverter.ToInt32(bytes, 0); - } - - /// - /// Method to convert an to an . - /// - /// IP address as . - /// Converted . - public static IPAddress FromInt32(int i) - { - var bytes = BitConverter.GetBytes(i); - - if (BitConverter.IsLittleEndian) - Array.Reverse(bytes); - - return new IPAddress(bytes); - } - - /// - /// Method to check if an IPv4 address is a multicast address. - /// - /// IPv4 address as . - /// True if it is a multicast address. False if not. - public static bool IsMulticast(IPAddress ipAddress) - { - var ip = ToInt32(ipAddress); - - return (ip >= IPv4MulticastStart && ip <= IPv4MulticastEnd); - } + return string.Join(".", humanString.Split('.').Select(x => Convert.ToString(int.Parse(x), 2).PadLeft(8, '0')).ToArray()); + } + + /// + /// Method to convert an to . + /// + /// . + /// IP address as + + public static int ToInt32(IPAddress ipAddress) + { + var bytes = ipAddress.GetAddressBytes(); + + if (BitConverter.IsLittleEndian) + Array.Reverse(bytes); + + return BitConverter.ToInt32(bytes, 0); + } + + /// + /// Method to convert an to an . + /// + /// IP address as . + /// Converted . + public static IPAddress FromInt32(int i) + { + var bytes = BitConverter.GetBytes(i); + + if (BitConverter.IsLittleEndian) + Array.Reverse(bytes); + + return new IPAddress(bytes); + } + + /// + /// Method to check if an IPv4 address is a multicast address. + /// + /// IPv4 address as . + /// True if it is a multicast address. False if not. + public static bool IsMulticast(IPAddress ipAddress) + { + var ip = ToInt32(ipAddress); + + return (ip >= IPv4MulticastStart && ip <= IPv4MulticastEnd); } } diff --git a/Source/NETworkManager.Models/Network/Listener.Protocol.cs b/Source/NETworkManager.Models/Network/Listener.Protocol.cs index 49d4daaa15..726702f37c 100644 --- a/Source/NETworkManager.Models/Network/Listener.Protocol.cs +++ b/Source/NETworkManager.Models/Network/Listener.Protocol.cs @@ -1,11 +1,10 @@ -namespace NETworkManager.Models.Network -{ - public partial class Listener - { - public enum Protocol - { - TCP, - UDP - } +namespace NETworkManager.Models.Network; + +public partial class Listener +{ + public enum Protocol + { + TCP, + UDP } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/Listener.cs b/Source/NETworkManager.Models/Network/Listener.cs index b03d1b8883..1d8b9f632f 100644 --- a/Source/NETworkManager.Models/Network/Listener.cs +++ b/Source/NETworkManager.Models/Network/Listener.cs @@ -3,57 +3,56 @@ using System.Net.NetworkInformation; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public partial class Listener { - public partial class Listener + #region Methods + public static Task> GetAllActiveListenersAsync() { - #region Methods - public static Task> GetAllActiveListenersAsync() - { - return Task.Run(() => GetAllActiveListeners()); - - } + return Task.Run(() => GetAllActiveListeners()); - public static List GetAllActiveListeners() - { - List list = new List(); + } - list.AddRange(GetActiveTcpListeners()); - list.AddRange(GetActiveUdpListeners()); + public static List GetAllActiveListeners() + { + List list = new List(); - return list; - } + list.AddRange(GetActiveTcpListeners()); + list.AddRange(GetActiveUdpListeners()); - public static Task> GetActiveTcpListenersAsync() - { - return Task.Run(() => GetActiveTcpListeners()); - } + return list; + } - public static List GetActiveTcpListeners() - { - List list = new List(); + public static Task> GetActiveTcpListenersAsync() + { + return Task.Run(() => GetActiveTcpListeners()); + } - foreach (IPEndPoint ipEndPoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()) - list.Add(new ListenerInfo(Protocol.TCP, ipEndPoint.Address, ipEndPoint.Port)); + public static List GetActiveTcpListeners() + { + List list = new List(); - return list; - } + foreach (IPEndPoint ipEndPoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()) + list.Add(new ListenerInfo(Protocol.TCP, ipEndPoint.Address, ipEndPoint.Port)); - public static Task> GetActiveUdpListenersAsync() - { - return Task.Run(() => GetActiveUdpListeners()); - } + return list; + } - public static List GetActiveUdpListeners() - { - List list = new List(); + public static Task> GetActiveUdpListenersAsync() + { + return Task.Run(() => GetActiveUdpListeners()); + } - foreach (IPEndPoint ipEndPoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners()) - list.Add(new ListenerInfo(Protocol.UDP, ipEndPoint.Address, ipEndPoint.Port)); + public static List GetActiveUdpListeners() + { + List list = new List(); - return list; - } + foreach (IPEndPoint ipEndPoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners()) + list.Add(new ListenerInfo(Protocol.UDP, ipEndPoint.Address, ipEndPoint.Port)); - #endregion + return list; } + + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/ListenerInfo.cs b/Source/NETworkManager.Models/Network/ListenerInfo.cs index cf84b1d589..8251775760 100644 --- a/Source/NETworkManager.Models/Network/ListenerInfo.cs +++ b/Source/NETworkManager.Models/Network/ListenerInfo.cs @@ -2,26 +2,25 @@ using System.Net; using static NETworkManager.Models.Network.Listener; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class ListenerInfo { - public class ListenerInfo - { - public Listener.Protocol Protocol { get; set; } - public IPAddress IPAddress { get; set; } - public int Port { get; set; } + public Listener.Protocol Protocol { get; set; } + public IPAddress IPAddress { get; set; } + public int Port { get; set; } - public int IPAddressInt32 => IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; + public int IPAddressInt32 => IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; - public ListenerInfo() - { + public ListenerInfo() + { - } + } - public ListenerInfo(Listener.Protocol protocol, IPAddress ipddress, int port) - { - Protocol = protocol; - IPAddress = ipddress; - Port = port; - } + public ListenerInfo(Listener.Protocol protocol, IPAddress ipddress, int port) + { + Protocol = protocol; + IPAddress = ipddress; + Port = port; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/MaximumHopsReachedArgs.cs b/Source/NETworkManager.Models/Network/MaximumHopsReachedArgs.cs index 816e1fc2b0..dac185aa93 100644 --- a/Source/NETworkManager.Models/Network/MaximumHopsReachedArgs.cs +++ b/Source/NETworkManager.Models/Network/MaximumHopsReachedArgs.cs @@ -1,17 +1,16 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class MaximumHopsReachedArgs : System.EventArgs { - public class MaximumHopsReachedArgs : System.EventArgs + public int Hops { get; set; } + + public MaximumHopsReachedArgs() { - public int Hops { get; set; } - - public MaximumHopsReachedArgs() - { - } + } - public MaximumHopsReachedArgs(int hops) - { - Hops = hops; - } + public MaximumHopsReachedArgs(int hops) + { + Hops = hops; } } diff --git a/Source/NETworkManager.Models/Network/NetworkInterface.cs b/Source/NETworkManager.Models/Network/NetworkInterface.cs index e4479eed18..3a48c7f140 100644 --- a/Source/NETworkManager.Models/Network/NetworkInterface.cs +++ b/Source/NETworkManager.Models/Network/NetworkInterface.cs @@ -9,340 +9,339 @@ using System.Net.Sockets; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public partial class NetworkInterface { - public partial class NetworkInterface + #region Events + public event EventHandler UserHasCanceled; + + protected virtual void OnUserHasCanceled() { - #region Events - public event EventHandler UserHasCanceled; + UserHasCanceled?.Invoke(this, EventArgs.Empty); + } + #endregion - protected virtual void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - #endregion + #region Methods + public static Task> GetNetworkInterfacesAsync() + { + return Task.Run(() => GetNetworkInterfaces()); + } - #region Methods - public static Task> GetNetworkInterfacesAsync() - { - return Task.Run(() => GetNetworkInterfaces()); - } + public static List GetNetworkInterfaces() + { + var listNetworkInterfaceInfo = new List(); - public static List GetNetworkInterfaces() + foreach (var networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { - var listNetworkInterfaceInfo = new List(); - - foreach (var networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) - { - // NetworkInterfaceType 53 is proprietary virtual/internal interface - // https://docs.microsoft.com/en-us/windows-hardware/drivers/network/ndis-interface-types - if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && (int)networkInterface.NetworkInterfaceType != 53) - continue; + // NetworkInterfaceType 53 is proprietary virtual/internal interface + // https://docs.microsoft.com/en-us/windows-hardware/drivers/network/ndis-interface-types + if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && (int)networkInterface.NetworkInterfaceType != 53) + continue; - var listIPv4Address = new List>(); - var listIPv6AddressLinkLocal = new List(); - var listIPv6Address = new List(); + var listIPv4Address = new List>(); + var listIPv6AddressLinkLocal = new List(); + var listIPv6Address = new List(); - var dhcpLeaseObtained = new DateTime(); - var dhcpLeaseExpires = new DateTime(); + var dhcpLeaseObtained = new DateTime(); + var dhcpLeaseExpires = new DateTime(); - var ipProperties = networkInterface.GetIPProperties(); + var ipProperties = networkInterface.GetIPProperties(); - foreach (var unicastIPAddrInfo in ipProperties.UnicastAddresses) + foreach (var unicastIPAddrInfo in ipProperties.UnicastAddresses) + { + switch (unicastIPAddrInfo.Address.AddressFamily) { - switch (unicastIPAddrInfo.Address.AddressFamily) - { - case AddressFamily.InterNetwork: - - listIPv4Address.Add(new Tuple(unicastIPAddrInfo.Address, unicastIPAddrInfo.IPv4Mask)); - dhcpLeaseExpires = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressPreferredLifetime)).ToLocalTime(); - dhcpLeaseObtained = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressValidLifetime) - TimeSpan.FromSeconds(unicastIPAddrInfo.DhcpLeaseLifetime)).ToLocalTime(); - break; - case AddressFamily.InterNetworkV6 when unicastIPAddrInfo.Address.IsIPv6LinkLocal: - listIPv6AddressLinkLocal.Add(unicastIPAddrInfo.Address); - break; - case AddressFamily.InterNetworkV6: - listIPv6Address.Add(unicastIPAddrInfo.Address); - break; - } - } + case AddressFamily.InterNetwork: - var listIPv4Gateway = new List(); - var listIPv6Gateway = new List(); - - foreach (var gatewayIPAddrInfo in ipProperties.GatewayAddresses) - { - switch (gatewayIPAddrInfo.Address.AddressFamily) - { - case AddressFamily.InterNetwork: - listIPv4Gateway.Add(gatewayIPAddrInfo.Address); - break; - case AddressFamily.InterNetworkV6: - listIPv6Gateway.Add(gatewayIPAddrInfo.Address); - break; - } + listIPv4Address.Add(new Tuple(unicastIPAddrInfo.Address, unicastIPAddrInfo.IPv4Mask)); + dhcpLeaseExpires = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressPreferredLifetime)).ToLocalTime(); + dhcpLeaseObtained = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressValidLifetime) - TimeSpan.FromSeconds(unicastIPAddrInfo.DhcpLeaseLifetime)).ToLocalTime(); + break; + case AddressFamily.InterNetworkV6 when unicastIPAddrInfo.Address.IsIPv6LinkLocal: + listIPv6AddressLinkLocal.Add(unicastIPAddrInfo.Address); + break; + case AddressFamily.InterNetworkV6: + listIPv6Address.Add(unicastIPAddrInfo.Address); + break; } + } - var listDhcpServer = new List(); + var listIPv4Gateway = new List(); + var listIPv6Gateway = new List(); - foreach (var dhcpServerIPAddress in ipProperties.DhcpServerAddresses) + foreach (var gatewayIPAddrInfo in ipProperties.GatewayAddresses) + { + switch (gatewayIPAddrInfo.Address.AddressFamily) { - if (dhcpServerIPAddress.AddressFamily == AddressFamily.InterNetwork) - listDhcpServer.Add(dhcpServerIPAddress); + case AddressFamily.InterNetwork: + listIPv4Gateway.Add(gatewayIPAddrInfo.Address); + break; + case AddressFamily.InterNetworkV6: + listIPv6Gateway.Add(gatewayIPAddrInfo.Address); + break; } + } - // Check if autoconfiguration for DNS is enabled (only via registry key) - var nameServerKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{networkInterface.Id}"); - var dnsAutoconfigurationEnabled = nameServerKey?.GetValue("NameServer") != null && string.IsNullOrEmpty(nameServerKey.GetValue("NameServer").ToString()); + var listDhcpServer = new List(); - var listDNSServer = new List(); + foreach (var dhcpServerIPAddress in ipProperties.DhcpServerAddresses) + { + if (dhcpServerIPAddress.AddressFamily == AddressFamily.InterNetwork) + listDhcpServer.Add(dhcpServerIPAddress); + } - foreach (var dnsServerIPAddress in ipProperties.DnsAddresses) - { - listDNSServer.Add(dnsServerIPAddress); - } + // Check if autoconfiguration for DNS is enabled (only via registry key) + var nameServerKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{networkInterface.Id}"); + var dnsAutoconfigurationEnabled = nameServerKey?.GetValue("NameServer") != null && string.IsNullOrEmpty(nameServerKey.GetValue("NameServer").ToString()); - // Check if IPv4 protocol is available - var ipv4ProtocolAvailable = true; - IPv4InterfaceProperties ipv4Properties = null; + var listDNSServer = new List(); - try - { - ipv4Properties = ipProperties.GetIPv4Properties(); - } - catch (NetworkInformationException) - { - ipv4ProtocolAvailable = false; - } + foreach (var dnsServerIPAddress in ipProperties.DnsAddresses) + { + listDNSServer.Add(dnsServerIPAddress); + } - // Check if IPv6 protocol is available - var ipv6ProtocolAvailable = true; - IPv6InterfaceProperties ipv6Properties = null; + // Check if IPv4 protocol is available + var ipv4ProtocolAvailable = true; + IPv4InterfaceProperties ipv4Properties = null; - try - { - ipv6Properties = ipProperties.GetIPv6Properties(); - } - catch (NetworkInformationException) - { - ipv6ProtocolAvailable = false; - } + try + { + ipv4Properties = ipProperties.GetIPv4Properties(); + } + catch (NetworkInformationException) + { + ipv4ProtocolAvailable = false; + } - listNetworkInterfaceInfo.Add(new NetworkInterfaceInfo - { - Id = networkInterface.Id, - Name = networkInterface.Name, - Description = networkInterface.Description, - Type = networkInterface.NetworkInterfaceType.ToString(), - PhysicalAddress = networkInterface.GetPhysicalAddress(), - Status = networkInterface.OperationalStatus, - IsOperational = networkInterface.OperationalStatus == OperationalStatus.Up, - Speed = networkInterface.Speed, - IPv4ProtocolAvailable = ipv4ProtocolAvailable, - IPv4Address = listIPv4Address.ToArray(), - IPv4Gateway = listIPv4Gateway.ToArray(), - DhcpEnabled = ipv4Properties != null && ipv4Properties.IsDhcpEnabled, - DhcpServer = listDhcpServer.ToArray(), - DhcpLeaseObtained = dhcpLeaseObtained, - DhcpLeaseExpires = dhcpLeaseExpires, - IPv6ProtocolAvailable = ipv6ProtocolAvailable, - IPv6AddressLinkLocal = listIPv6AddressLinkLocal.ToArray(), - IPv6Address = listIPv6Address.ToArray(), - IPv6Gateway = listIPv6Gateway.ToArray(), - DNSAutoconfigurationEnabled = dnsAutoconfigurationEnabled, - DNSSuffix = ipProperties.DnsSuffix, - DNSServer = listDNSServer.ToArray() - }); + // Check if IPv6 protocol is available + var ipv6ProtocolAvailable = true; + IPv6InterfaceProperties ipv6Properties = null; + + try + { + ipv6Properties = ipProperties.GetIPv6Properties(); + } + catch (NetworkInformationException) + { + ipv6ProtocolAvailable = false; } - return listNetworkInterfaceInfo; + listNetworkInterfaceInfo.Add(new NetworkInterfaceInfo + { + Id = networkInterface.Id, + Name = networkInterface.Name, + Description = networkInterface.Description, + Type = networkInterface.NetworkInterfaceType.ToString(), + PhysicalAddress = networkInterface.GetPhysicalAddress(), + Status = networkInterface.OperationalStatus, + IsOperational = networkInterface.OperationalStatus == OperationalStatus.Up, + Speed = networkInterface.Speed, + IPv4ProtocolAvailable = ipv4ProtocolAvailable, + IPv4Address = listIPv4Address.ToArray(), + IPv4Gateway = listIPv4Gateway.ToArray(), + DhcpEnabled = ipv4Properties != null && ipv4Properties.IsDhcpEnabled, + DhcpServer = listDhcpServer.ToArray(), + DhcpLeaseObtained = dhcpLeaseObtained, + DhcpLeaseExpires = dhcpLeaseExpires, + IPv6ProtocolAvailable = ipv6ProtocolAvailable, + IPv6AddressLinkLocal = listIPv6AddressLinkLocal.ToArray(), + IPv6Address = listIPv6Address.ToArray(), + IPv6Gateway = listIPv6Gateway.ToArray(), + DNSAutoconfigurationEnabled = dnsAutoconfigurationEnabled, + DNSSuffix = ipProperties.DnsSuffix, + DNSServer = listDNSServer.ToArray() + }); } - public static Task DetectLocalIPAddressBasedOnRoutingAsync(IPAddress remoteIPAddress) - { - return Task.Run(() => DetectLocalIPAddressBasedOnRouting(remoteIPAddress)); - } + return listNetworkInterfaceInfo; + } - public static IPAddress DetectLocalIPAddressBasedOnRouting(IPAddress remoteIPAddress) - { - bool isIPv4 = remoteIPAddress.AddressFamily == AddressFamily.InterNetwork; + public static Task DetectLocalIPAddressBasedOnRoutingAsync(IPAddress remoteIPAddress) + { + return Task.Run(() => DetectLocalIPAddressBasedOnRouting(remoteIPAddress)); + } - using var socket = new Socket(isIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); + public static IPAddress DetectLocalIPAddressBasedOnRouting(IPAddress remoteIPAddress) + { + bool isIPv4 = remoteIPAddress.AddressFamily == AddressFamily.InterNetwork; - // return null on error... - try - { - socket.Bind(new IPEndPoint(isIPv4 ? IPAddress.Any : IPAddress.IPv6Any, 0)); - socket.Connect(new IPEndPoint(remoteIPAddress, 0)); + using var socket = new Socket(isIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); - if (socket.LocalEndPoint is IPEndPoint ipAddress) - return ipAddress.Address; - } - catch (SocketException) { } + // return null on error... + try + { + socket.Bind(new IPEndPoint(isIPv4 ? IPAddress.Any : IPAddress.IPv6Any, 0)); + socket.Connect(new IPEndPoint(remoteIPAddress, 0)); - return null; + if (socket.LocalEndPoint is IPEndPoint ipAddress) + return ipAddress.Address; } + catch (SocketException) { } - public static Task DetectGatewayBasedOnLocalIPAddressAsync(IPAddress localIPAddress) - { - return Task.Run(() => DetectGatewayBasedOnLocalIPAddress(localIPAddress)); - } + return null; + } - public static IPAddress DetectGatewayBasedOnLocalIPAddress(IPAddress localIPAddress) + public static Task DetectGatewayBasedOnLocalIPAddressAsync(IPAddress localIPAddress) + { + return Task.Run(() => DetectGatewayBasedOnLocalIPAddress(localIPAddress)); + } + + public static IPAddress DetectGatewayBasedOnLocalIPAddress(IPAddress localIPAddress) + { + foreach (var networkInterface in GetNetworkInterfaces()) { - foreach (var networkInterface in GetNetworkInterfaces()) + if (localIPAddress.AddressFamily == AddressFamily.InterNetwork) { - if (localIPAddress.AddressFamily == AddressFamily.InterNetwork) + if (networkInterface.IPv4Address.Any(x => x.Item1.Equals(localIPAddress))) { - if (networkInterface.IPv4Address.Any(x => x.Item1.Equals(localIPAddress))) - { - return networkInterface.IPv4Gateway.FirstOrDefault(); - } + return networkInterface.IPv4Gateway.FirstOrDefault(); } - else if (localIPAddress.AddressFamily == AddressFamily.InterNetworkV6) - { - if (networkInterface.IPv6Address.Contains(localIPAddress)) - { - return networkInterface.IPv6Gateway.FirstOrDefault(); - } - } - else + } + else if (localIPAddress.AddressFamily == AddressFamily.InterNetworkV6) + { + if (networkInterface.IPv6Address.Contains(localIPAddress)) { - throw new Exception("IPv4 or IPv6 address is required to detect the gateway."); + return networkInterface.IPv6Gateway.FirstOrDefault(); } } - - return null; + else + { + throw new Exception("IPv4 or IPv6 address is required to detect the gateway."); + } } - public Task ConfigureNetworkInterfaceAsync(NetworkInterfaceConfig config) - { - return Task.Run(() => ConfigureNetworkInterface(config)); - } + return null; + } - public void ConfigureNetworkInterface(NetworkInterfaceConfig config) - { - // IP - var command = @"netsh interface ipv4 set address name='" + config.Name + @"'"; - command += config.EnableStaticIPAddress ? @" source=static address=" + config.IPAddress + @" mask=" + config.Subnetmask + @" gateway=" + config.Gateway : @" source=dhcp"; + public Task ConfigureNetworkInterfaceAsync(NetworkInterfaceConfig config) + { + return Task.Run(() => ConfigureNetworkInterface(config)); + } - // DNS - command += @";netsh interface ipv4 set DNSservers name='" + config.Name + @"'"; - command += config.EnableStaticDNS ? @" source=static address=" + config.PrimaryDNSServer + @" register=primary validate=no" : @" source=dhcp"; - command += (config.EnableStaticDNS && !string.IsNullOrEmpty(config.SecondaryDNSServer)) ? @";netsh interface ipv4 add DNSservers name='" + config.Name + @"' address=" + config.SecondaryDNSServer + @" index=2 validate=no" : ""; + public void ConfigureNetworkInterface(NetworkInterfaceConfig config) + { + // IP + var command = @"netsh interface ipv4 set address name='" + config.Name + @"'"; + command += config.EnableStaticIPAddress ? @" source=static address=" + config.IPAddress + @" mask=" + config.Subnetmask + @" gateway=" + config.Gateway : @" source=dhcp"; - try - { - PowerShellHelper.ExecuteCommand(command, true); - } - catch (Win32Exception win32Ex) + // DNS + command += @";netsh interface ipv4 set DNSservers name='" + config.Name + @"'"; + command += config.EnableStaticDNS ? @" source=static address=" + config.PrimaryDNSServer + @" register=primary validate=no" : @" source=dhcp"; + command += (config.EnableStaticDNS && !string.IsNullOrEmpty(config.SecondaryDNSServer)) ? @";netsh interface ipv4 add DNSservers name='" + config.Name + @"' address=" + config.SecondaryDNSServer + @" index=2 validate=no" : ""; + + try + { + PowerShellHelper.ExecuteCommand(command, true); + } + catch (Win32Exception win32Ex) + { + switch (win32Ex.NativeErrorCode) { - switch (win32Ex.NativeErrorCode) - { - case 1223: - OnUserHasCanceled(); - break; - default: - throw; - } + case 1223: + OnUserHasCanceled(); + break; + default: + throw; } } + } - /// - /// Flush the DNS cache asynchronously. - /// - /// Running task. - public static Task FlushDnsAsync() - { - return Task.Run(() => FlushDns()); - } + /// + /// Flush the DNS cache asynchronously. + /// + /// Running task. + public static Task FlushDnsAsync() + { + return Task.Run(() => FlushDns()); + } - /// - /// Flush the DNS cache. - /// - public static void FlushDns() - { - const string command = @"ipconfig /flushdns"; + /// + /// Flush the DNS cache. + /// + public static void FlushDns() + { + const string command = @"ipconfig /flushdns"; - PowerShellHelper.ExecuteCommand(command); - } + PowerShellHelper.ExecuteCommand(command); + } - /// - /// Release or renew the IP address of the specified network adapter asynchronously. - /// - /// ipconfig.exe modes which are used like /release(6) or /renew(6) - /// Name of the ethernet adapter. - /// Running task. - public static Task ReleaseRenewAsync(IPConfigReleaseRenewMode mode, string adapterName) - { - return Task.Run(() => ReleaseRenew(mode, adapterName)); - } + /// + /// Release or renew the IP address of the specified network adapter asynchronously. + /// + /// ipconfig.exe modes which are used like /release(6) or /renew(6) + /// Name of the ethernet adapter. + /// Running task. + public static Task ReleaseRenewAsync(IPConfigReleaseRenewMode mode, string adapterName) + { + return Task.Run(() => ReleaseRenew(mode, adapterName)); + } - /// - /// Release or renew the IP address of the specified network adapter. - /// - /// ipconfig.exe modes which are used like /release(6) or /renew(6) - /// Name of the ethernet adapter. - public static void ReleaseRenew(IPConfigReleaseRenewMode mode, string adapterName) - { - string command = string.Empty; + /// + /// Release or renew the IP address of the specified network adapter. + /// + /// ipconfig.exe modes which are used like /release(6) or /renew(6) + /// Name of the ethernet adapter. + public static void ReleaseRenew(IPConfigReleaseRenewMode mode, string adapterName) + { + string command = string.Empty; - if (mode == IPConfigReleaseRenewMode.ReleaseRenew || mode == IPConfigReleaseRenewMode.Release) - command += @"ipconfig /release '" + adapterName + "';"; + if (mode == IPConfigReleaseRenewMode.ReleaseRenew || mode == IPConfigReleaseRenewMode.Release) + command += @"ipconfig /release '" + adapterName + "';"; - if (mode == IPConfigReleaseRenewMode.ReleaseRenew || mode == IPConfigReleaseRenewMode.Renew) - command += @"ipconfig /renew '" + adapterName + "';"; + if (mode == IPConfigReleaseRenewMode.ReleaseRenew || mode == IPConfigReleaseRenewMode.Renew) + command += @"ipconfig /renew '" + adapterName + "';"; - if (mode == IPConfigReleaseRenewMode.ReleaseRenew6 || mode == IPConfigReleaseRenewMode.Release6) - command += @"ipconfig /release6 '" + adapterName + "';"; + if (mode == IPConfigReleaseRenewMode.ReleaseRenew6 || mode == IPConfigReleaseRenewMode.Release6) + command += @"ipconfig /release6 '" + adapterName + "';"; - if (mode == IPConfigReleaseRenewMode.ReleaseRenew6 || mode == IPConfigReleaseRenewMode.Renew6) - command += @"ipconfig /renew6 '" + adapterName + "';"; + if (mode == IPConfigReleaseRenewMode.ReleaseRenew6 || mode == IPConfigReleaseRenewMode.Renew6) + command += @"ipconfig /renew6 '" + adapterName + "';"; - PowerShellHelper.ExecuteCommand(command); - } + PowerShellHelper.ExecuteCommand(command); + } - /// - /// Add an IP address to a network interface asynchronously. - /// - /// Ethernet adapter name, IP address and subnetmask. - /// Running task. - public static Task AddIPAddressToNetworkInterfaceAsync(NetworkInterfaceConfig config) - { - return Task.Run(() => AddIPAddressToNetworkInterface(config)); - } + /// + /// Add an IP address to a network interface asynchronously. + /// + /// Ethernet adapter name, IP address and subnetmask. + /// Running task. + public static Task AddIPAddressToNetworkInterfaceAsync(NetworkInterfaceConfig config) + { + return Task.Run(() => AddIPAddressToNetworkInterface(config)); + } - /// - /// Add an IP address to a network interface. - /// - /// Ethernet adapter name, IP address and subnetmask. - public static void AddIPAddressToNetworkInterface(NetworkInterfaceConfig config) - { - var command = @"netsh interface ipv4 add address '" + config.Name + @"' " + config.IPAddress + @" " + config.Subnetmask; + /// + /// Add an IP address to a network interface. + /// + /// Ethernet adapter name, IP address and subnetmask. + public static void AddIPAddressToNetworkInterface(NetworkInterfaceConfig config) + { + var command = @"netsh interface ipv4 add address '" + config.Name + @"' " + config.IPAddress + @" " + config.Subnetmask; - PowerShellHelper.ExecuteCommand(command, true); - } + PowerShellHelper.ExecuteCommand(command, true); + } - /// - /// Remove an IP address from a network interface asynchronously. - /// - /// Ethernet adapter name, IP address - /// Running task. - public static Task RemoveIPAddressFromNetworkInterfaceAsync(NetworkInterfaceConfig config) - { - return Task.Run(() => RemoveIPAddressFromNetworkInterface(config)); - } + /// + /// Remove an IP address from a network interface asynchronously. + /// + /// Ethernet adapter name, IP address + /// Running task. + public static Task RemoveIPAddressFromNetworkInterfaceAsync(NetworkInterfaceConfig config) + { + return Task.Run(() => RemoveIPAddressFromNetworkInterface(config)); + } - /// - /// Remove an IP address from a network interface. - /// - /// Ethernet adapter name, IP address - public static void RemoveIPAddressFromNetworkInterface(NetworkInterfaceConfig config) - { - var command = @"netsh interface ipv4 delete address '" + config.Name + @"' " + config.IPAddress; + /// + /// Remove an IP address from a network interface. + /// + /// Ethernet adapter name, IP address + public static void RemoveIPAddressFromNetworkInterface(NetworkInterfaceConfig config) + { + var command = @"netsh interface ipv4 delete address '" + config.Name + @"' " + config.IPAddress; - PowerShellHelper.ExecuteCommand(command, true); - } - #endregion + PowerShellHelper.ExecuteCommand(command, true); } + #endregion } diff --git a/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs b/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs index a5bdb33a7a..734f61ccdd 100644 --- a/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs +++ b/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs @@ -1,19 +1,18 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class NetworkInterfaceConfig { - public class NetworkInterfaceConfig - { - public string Name { get; set; } - public bool EnableStaticIPAddress { get; set; } - public string IPAddress { get; set; } - public string Subnetmask { get; set; } - public string Gateway { get; set; } - public bool EnableStaticDNS { get; set; } - public string PrimaryDNSServer { get; set; } - public string SecondaryDNSServer { get; set; } + public string Name { get; set; } + public bool EnableStaticIPAddress { get; set; } + public string IPAddress { get; set; } + public string Subnetmask { get; set; } + public string Gateway { get; set; } + public bool EnableStaticDNS { get; set; } + public string PrimaryDNSServer { get; set; } + public string SecondaryDNSServer { get; set; } - public NetworkInterfaceConfig() - { + public NetworkInterfaceConfig() + { - } - } + } } diff --git a/Source/NETworkManager.Models/Network/NetworkInterfaceInfo.cs b/Source/NETworkManager.Models/Network/NetworkInterfaceInfo.cs index 95b8fabbc3..f8eb132cc3 100644 --- a/Source/NETworkManager.Models/Network/NetworkInterfaceInfo.cs +++ b/Source/NETworkManager.Models/Network/NetworkInterfaceInfo.cs @@ -3,36 +3,35 @@ using System.Net; using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class NetworkInterfaceInfo { - public class NetworkInterfaceInfo - { - public string Id { get; set; } - public string Name { get; set; } - public string Description { get; set; } - public string Type { get; set; } - public PhysicalAddress PhysicalAddress { get; set; } - public OperationalStatus Status { get; set; } - public bool IsOperational { get; set; } - public long Speed { get; set; } - public bool IPv4ProtocolAvailable { get; set; } - public Tuple[] IPv4Address {get;set;} - public IPAddress[] IPv4Gateway { get; set; } - public bool DhcpEnabled { get; set; } - public IPAddress[] DhcpServer { get; set; } - public DateTime DhcpLeaseObtained { get; set; } - public DateTime DhcpLeaseExpires { get; set; } - public bool IPv6ProtocolAvailable { get; set; } - public IPAddress[] IPv6Address { get; set; } - public IPAddress[] IPv6AddressLinkLocal { get; set; } - public IPAddress[] IPv6Gateway { get; set; } - public bool DNSAutoconfigurationEnabled { get; set; } - public string DNSSuffix { get; set; } - public IPAddress[] DNSServer { get; set; } + public string Id { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public string Type { get; set; } + public PhysicalAddress PhysicalAddress { get; set; } + public OperationalStatus Status { get; set; } + public bool IsOperational { get; set; } + public long Speed { get; set; } + public bool IPv4ProtocolAvailable { get; set; } + public Tuple[] IPv4Address {get;set;} + public IPAddress[] IPv4Gateway { get; set; } + public bool DhcpEnabled { get; set; } + public IPAddress[] DhcpServer { get; set; } + public DateTime DhcpLeaseObtained { get; set; } + public DateTime DhcpLeaseExpires { get; set; } + public bool IPv6ProtocolAvailable { get; set; } + public IPAddress[] IPv6Address { get; set; } + public IPAddress[] IPv6AddressLinkLocal { get; set; } + public IPAddress[] IPv6Gateway { get; set; } + public bool DNSAutoconfigurationEnabled { get; set; } + public string DNSSuffix { get; set; } + public IPAddress[] DNSServer { get; set; } - public NetworkInterfaceInfo() - { - - } + public NetworkInterfaceInfo() + { + } } diff --git a/Source/NETworkManager.Models/Network/Ping.cs b/Source/NETworkManager.Models/Network/Ping.cs index 4d085504a7..ff27a2169a 100644 --- a/Source/NETworkManager.Models/Network/Ping.cs +++ b/Source/NETworkManager.Models/Network/Ping.cs @@ -6,150 +6,149 @@ using System.Threading; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class Ping { - public class Ping + #region Varaibles + public int WaitTime = 1000; + public int Timeout = 4000; + public byte[] Buffer = new byte[32]; + public int TTL = 64; + public bool DontFragment = true; + public int ExceptionCancelCount = 3; + public string Hostname = string.Empty; + #endregion + + #region Events + public event EventHandler PingReceived; + + protected virtual void OnPingReceived(PingReceivedArgs e) { - #region Varaibles - public int WaitTime = 1000; - public int Timeout = 4000; - public byte[] Buffer = new byte[32]; - public int TTL = 64; - public bool DontFragment = true; - public int ExceptionCancelCount = 3; - public string Hostname = string.Empty; - #endregion - - #region Events - public event EventHandler PingReceived; - - protected virtual void OnPingReceived(PingReceivedArgs e) - { - PingReceived?.Invoke(this, e); - } + PingReceived?.Invoke(this, e); + } - public event EventHandler PingCompleted; + public event EventHandler PingCompleted; - protected virtual void OnPingCompleted() - { - PingCompleted?.Invoke(this, EventArgs.Empty); - } + protected virtual void OnPingCompleted() + { + PingCompleted?.Invoke(this, EventArgs.Empty); + } - public event EventHandler PingException; + public event EventHandler PingException; - protected virtual void OnPingException(PingExceptionArgs e) - { - PingException?.Invoke(this, e); - } + protected virtual void OnPingException(PingExceptionArgs e) + { + PingException?.Invoke(this, e); + } - public event EventHandler UserHasCanceled; + public event EventHandler UserHasCanceled; - protected virtual void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - #endregion + protected virtual void OnUserHasCanceled() + { + UserHasCanceled?.Invoke(this, EventArgs.Empty); + } + #endregion - #region Methods - public void SendAsync(IPAddress ipAddress, CancellationToken cancellationToken) + #region Methods + public void SendAsync(IPAddress ipAddress, CancellationToken cancellationToken) + { + Task.Run(async () => { - Task.Run(async () => - { - var hostname = Hostname; + var hostname = Hostname; - // Try to resolve PTR - if (string.IsNullOrEmpty(hostname)) - { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(ipAddress); + // Try to resolve PTR + if (string.IsNullOrEmpty(hostname)) + { + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(ipAddress); - if (!dnsResult.HasError) - hostname = dnsResult.Value; - } + if (!dnsResult.HasError) + hostname = dnsResult.Value; + } - var pingTotal = 0; - var errorCount = 0; + var pingTotal = 0; + var errorCount = 0; - var options = new PingOptions - { - Ttl = TTL, - DontFragment = DontFragment - }; + var options = new PingOptions + { + Ttl = TTL, + DontFragment = DontFragment + }; - using (var ping = new System.Net.NetworkInformation.Ping()) + using (var ping = new System.Net.NetworkInformation.Ping()) + { + do { - do + try { - try + // Get timestamp + var timestamp = DateTime.Now; + + // Send ping + var pingReply = ping.Send(ipAddress, Timeout, Buffer, options); + + // Reset the error count (if no exception was thrown) + errorCount = 0; + + if (pingReply == null || pingReply.Status != IPStatus.Success) { - // Get timestamp - var timestamp = DateTime.Now; - - // Send ping - var pingReply = ping.Send(ipAddress, Timeout, Buffer, options); - - // Reset the error count (if no exception was thrown) - errorCount = 0; - - if (pingReply == null || pingReply.Status != IPStatus.Success) - { - if (pingReply != null && pingReply.Address == null) - OnPingReceived(new PingReceivedArgs(timestamp, ipAddress, hostname, pingReply.Status)); - else if (pingReply != null) - OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, pingReply.Status)); - } - else - { - if (ipAddress.AddressFamily == AddressFamily.InterNetwork) - OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, - pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status)); - else - OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, - pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Status)); - } + if (pingReply != null && pingReply.Address == null) + OnPingReceived(new PingReceivedArgs(timestamp, ipAddress, hostname, pingReply.Status)); + else if (pingReply != null) + OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, pingReply.Status)); } - catch (PingException ex) + else { - errorCount++; + if (ipAddress.AddressFamily == AddressFamily.InterNetwork) + OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, + pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status)); + else + OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, + pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Status)); + } + } + catch (PingException ex) + { + errorCount++; - if (errorCount == ExceptionCancelCount) - { - OnPingException(new PingExceptionArgs(ex.Message, ex.InnerException)); + if (errorCount == ExceptionCancelCount) + { + OnPingException(new PingExceptionArgs(ex.Message, ex.InnerException)); - break; - } + break; } + } - pingTotal++; + pingTotal++; - // If ping is canceled... dont wait for example 5 seconds - for (var i = 0; i < WaitTime; i += 100) - { - Thread.Sleep(100); + // If ping is canceled... dont wait for example 5 seconds + for (var i = 0; i < WaitTime; i += 100) + { + Thread.Sleep(100); + + if (cancellationToken.IsCancellationRequested) + break; + } + } while (!cancellationToken.IsCancellationRequested); + } + + if (cancellationToken.IsCancellationRequested) + OnUserHasCanceled(); + else + OnPingCompleted(); + }, cancellationToken); + } - if (cancellationToken.IsCancellationRequested) - break; - } - } while (!cancellationToken.IsCancellationRequested); - } - - if (cancellationToken.IsCancellationRequested) - OnUserHasCanceled(); - else - OnPingCompleted(); - }, cancellationToken); - } - - // Param: disableSpecialChar --> ExportManager --> "<" this char cannot be displayed in xml - public static string TimeToString(IPStatus status, long time, bool disableSpecialChar = false) - { - if (status != IPStatus.Success && status != IPStatus.TtlExpired) - return "-/-"; + // Param: disableSpecialChar --> ExportManager --> "<" this char cannot be displayed in xml + public static string TimeToString(IPStatus status, long time, bool disableSpecialChar = false) + { + if (status != IPStatus.Success && status != IPStatus.TtlExpired) + return "-/-"; - _ = long.TryParse(time.ToString(), out var t); + _ = long.TryParse(time.ToString(), out var t); - return disableSpecialChar ? $"{t} ms" : t == 0 ? "<1 ms" : $"{t} ms"; - } - #endregion + return disableSpecialChar ? $"{t} ms" : t == 0 ? "<1 ms" : $"{t} ms"; } + #endregion } diff --git a/Source/NETworkManager.Models/Network/PingExceptionArgs.cs b/Source/NETworkManager.Models/Network/PingExceptionArgs.cs index ca3004fa47..9cf088e174 100644 --- a/Source/NETworkManager.Models/Network/PingExceptionArgs.cs +++ b/Source/NETworkManager.Models/Network/PingExceptionArgs.cs @@ -1,16 +1,15 @@ using System; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class PingExceptionArgs : EventArgs { - public class PingExceptionArgs : EventArgs - { - public string Message { get; set; } - public Exception InnerException { get; set; } + public string Message { get; set; } + public Exception InnerException { get; set; } - public PingExceptionArgs(string message, Exception innerException) - { - Message = message; - InnerException = innerException; - } + public PingExceptionArgs(string message, Exception innerException) + { + Message = message; + InnerException = innerException; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/PingInfo.cs b/Source/NETworkManager.Models/Network/PingInfo.cs index f5851bc6ac..5cabca8070 100644 --- a/Source/NETworkManager.Models/Network/PingInfo.cs +++ b/Source/NETworkManager.Models/Network/PingInfo.cs @@ -2,94 +2,93 @@ using System.Net; using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class PingInfo { - public class PingInfo - { - public DateTime Timestamp { get; set; } - public IPAddress IPAddress { get; set; } - public string Hostname { get; set; } - public int Bytes { get; set; } - public long Time { get; set; } - public int TTL { get; set; } - public IPStatus Status { get; set; } + public DateTime Timestamp { get; set; } + public IPAddress IPAddress { get; set; } + public string Hostname { get; set; } + public int Bytes { get; set; } + public long Time { get; set; } + public int TTL { get; set; } + public IPStatus Status { get; set; } - public int IPAddressInt32 => IPAddress != null && IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; + public int IPAddressInt32 => IPAddress != null && IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; - public PingInfo() - { + public PingInfo() + { - } + } - public PingInfo(IPAddress ipAddress, IPStatus ipStatus) - { - IPAddress = ipAddress; - Status = ipStatus; - } + public PingInfo(IPAddress ipAddress, IPStatus ipStatus) + { + IPAddress = ipAddress; + Status = ipStatus; + } - public PingInfo(DateTime timestamp, IPAddress ipAddress, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Status = status; - } + public PingInfo(DateTime timestamp, IPAddress ipAddress, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Status = status; + } - public PingInfo(DateTime timestamp, IPAddress ipAddress, int bytes, long time, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Bytes = bytes; - Time = time; - Status = status; - } + public PingInfo(DateTime timestamp, IPAddress ipAddress, int bytes, long time, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Bytes = bytes; + Time = time; + Status = status; + } - public PingInfo(DateTime timestamp, IPAddress ipAddress, int bytes, long time, int ttl, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Bytes = bytes; - Time = time; - TTL = ttl; - Status = status; - } + public PingInfo(DateTime timestamp, IPAddress ipAddress, int bytes, long time, int ttl, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Bytes = bytes; + Time = time; + TTL = ttl; + Status = status; + } - public PingInfo(DateTime timestamp, IPAddress ipAddress, string hostname, int bytes, long time, int ttl, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Hostname = hostname; - Bytes = bytes; - Time = time; - TTL = ttl; - Status = status; - } + public PingInfo(DateTime timestamp, IPAddress ipAddress, string hostname, int bytes, long time, int ttl, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Hostname = hostname; + Bytes = bytes; + Time = time; + TTL = ttl; + Status = status; + } - public PingInfo(DateTime timestamp, long time) - { - Timestamp = timestamp; - Time = time; - } + public PingInfo(DateTime timestamp, long time) + { + Timestamp = timestamp; + Time = time; + } - public PingInfo(IPAddress ipAddress, int bytes, long time, int ttl, IPStatus status) - { - IPAddress = ipAddress; - Bytes = bytes; - Time = time; - TTL = ttl; - Status = status; - } + public PingInfo(IPAddress ipAddress, int bytes, long time, int ttl, IPStatus status) + { + IPAddress = ipAddress; + Bytes = bytes; + Time = time; + TTL = ttl; + Status = status; + } - public PingInfo(IPAddress ipAddress, int bytes, long time, IPStatus status) - { - IPAddress = ipAddress; - Bytes = bytes; - Time = time; - Status = status; - } + public PingInfo(IPAddress ipAddress, int bytes, long time, IPStatus status) + { + IPAddress = ipAddress; + Bytes = bytes; + Time = time; + Status = status; + } - public static PingInfo Parse(PingReceivedArgs e) - { - return new PingInfo(e.Timestamp, e.IPAddress, e.Hostname, e.Bytes, e.Time, e.TTL, e.Status); - } + public static PingInfo Parse(PingReceivedArgs e) + { + return new PingInfo(e.Timestamp, e.IPAddress, e.Hostname, e.Bytes, e.Time, e.TTL, e.Status); } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/PingMonitorOptions.cs b/Source/NETworkManager.Models/Network/PingMonitorOptions.cs index c9e70b87bb..9de14c3fb5 100644 --- a/Source/NETworkManager.Models/Network/PingMonitorOptions.cs +++ b/Source/NETworkManager.Models/Network/PingMonitorOptions.cs @@ -1,16 +1,15 @@ using System.Net; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class PingMonitorOptions { - public class PingMonitorOptions - { - public string Host { get; set; } - public IPAddress IPAddress { get; set; } + public string Host { get; set; } + public IPAddress IPAddress { get; set; } - public PingMonitorOptions(string host, IPAddress ipAddress) - { - Host = host; - IPAddress = ipAddress; - } - } + public PingMonitorOptions(string host, IPAddress ipAddress) + { + Host = host; + IPAddress = ipAddress; + } } diff --git a/Source/NETworkManager.Models/Network/PingReceivedArgs.cs b/Source/NETworkManager.Models/Network/PingReceivedArgs.cs index a715de922c..07c1a5b6c6 100644 --- a/Source/NETworkManager.Models/Network/PingReceivedArgs.cs +++ b/Source/NETworkManager.Models/Network/PingReceivedArgs.cs @@ -2,71 +2,70 @@ using System.Net; using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class PingReceivedArgs : EventArgs { - public class PingReceivedArgs : EventArgs + public DateTime Timestamp { get; set; } + public IPAddress IPAddress { get; set; } + public string Hostname { get; set; } + public int Bytes { get; set; } + public long Time { get; set; } + public int TTL { get; set; } + public IPStatus Status { get; set; } + + public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, IPStatus status) { - public DateTime Timestamp { get; set; } - public IPAddress IPAddress { get; set; } - public string Hostname { get; set; } - public int Bytes { get; set; } - public long Time { get; set; } - public int TTL { get; set; } - public IPStatus Status { get; set; } - - public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Status = status; - } + Timestamp = timestamp; + IPAddress = ipAddress; + Status = status; + } - public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, string hostname, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Hostname = hostname; - Status = status; - } + public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, string hostname, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Hostname = hostname; + Status = status; + } - public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, int bytes, long time, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Bytes = bytes; - Time = time; - Status = status; - } + public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, int bytes, long time, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Bytes = bytes; + Time = time; + Status = status; + } - public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, string hostname, int bytes, long time, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Hostname = hostname; - Bytes = bytes; - Time = time; - Status = status; - } + public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, string hostname, int bytes, long time, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Hostname = hostname; + Bytes = bytes; + Time = time; + Status = status; + } - public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, int bytes, long time, int ttl, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Bytes = bytes; - Time = time; - TTL = ttl; - Status = status; - } + public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, int bytes, long time, int ttl, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Bytes = bytes; + Time = time; + TTL = ttl; + Status = status; + } - public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, string hostname, int bytes, long time, int ttl, IPStatus status) - { - Timestamp = timestamp; - IPAddress = ipAddress; - Hostname = hostname; - Bytes = bytes; - Time = time; - TTL = ttl; - Status = status; - } + public PingReceivedArgs(DateTime timestamp, IPAddress ipAddress, string hostname, int bytes, long time, int ttl, IPStatus status) + { + Timestamp = timestamp; + IPAddress = ipAddress; + Hostname = hostname; + Bytes = bytes; + Time = time; + TTL = ttl; + Status = status; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/PortInfo.cs b/Source/NETworkManager.Models/Network/PortInfo.cs index 5cacc9b152..007371ad8f 100644 --- a/Source/NETworkManager.Models/Network/PortInfo.cs +++ b/Source/NETworkManager.Models/Network/PortInfo.cs @@ -1,35 +1,34 @@ using NETworkManager.Models.Lookup; using System.Net; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public partial class PortInfo { - public partial class PortInfo - { - public IPAddress IPAddress { get; set; } - public string Hostname { get; set; } - public int Port { get; set; } - public PortLookupInfo LookupInfo { get; set; } - public PortState State { get; set; } + public IPAddress IPAddress { get; set; } + public string Hostname { get; set; } + public int Port { get; set; } + public PortLookupInfo LookupInfo { get; set; } + public PortState State { get; set; } - public int IPAddressInt32 => IPAddress != null && IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; + public int IPAddressInt32 => IPAddress != null && IPAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? IPv4Address.ToInt32(IPAddress) : 0; - public PortInfo() - { + public PortInfo() + { - } + } - public PortInfo(IPAddress ipAddress, string hostname, int port, PortLookupInfo lookupInfo, PortState status) - { - IPAddress = ipAddress; - Hostname = hostname; - Port = port; - LookupInfo = lookupInfo; - State = status; - } + public PortInfo(IPAddress ipAddress, string hostname, int port, PortLookupInfo lookupInfo, PortState status) + { + IPAddress = ipAddress; + Hostname = hostname; + Port = port; + LookupInfo = lookupInfo; + State = status; + } - public static PortInfo Parse(PortScannedArgs e) - { - return new PortInfo(e.IPAddress, e.Hostname, e.Port, e.LookupInfo, e.State); - } + public static PortInfo Parse(PortScannedArgs e) + { + return new PortInfo(e.IPAddress, e.Hostname, e.Port, e.LookupInfo, e.State); } } diff --git a/Source/NETworkManager.Models/Network/PortProfile.cs b/Source/NETworkManager.Models/Network/PortProfile.cs index 46378bd5ca..6b29e38f92 100644 --- a/Source/NETworkManager.Models/Network/PortProfile.cs +++ b/Source/NETworkManager.Models/Network/PortProfile.cs @@ -1,25 +1,24 @@ using System.Collections.Generic; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public static class PortProfile { - public static class PortProfile + public static List GetDefaultList() { - public static List GetDefaultList() + return new List { - return new List - { - new PortProfileInfo("DNS (via TCP)", "53"), - new PortProfileInfo("NTP (via TCP)", "123"), - new PortProfileInfo("Webserver", "80; 443"), - new PortProfileInfo("Webserver (Other)", "80; 443; 8080; 8443"), - new PortProfileInfo("Remote access", "22; 23; 3389; 5900"), - new PortProfileInfo("Mailserver", "25; 110; 143; 465; 587; 993; 995"), - new PortProfileInfo("Filetransfer", "20-21; 22; 989-990; 2049"), - new PortProfileInfo("Database", "1433-1434; 1521; 1830; 3306; 5432"), - new PortProfileInfo("SMB", "139; 445"), - new PortProfileInfo("LDAP", "389; 636"), - new PortProfileInfo("HTTP proxy", "3128") - }; - } + new PortProfileInfo("DNS (via TCP)", "53"), + new PortProfileInfo("NTP (via TCP)", "123"), + new PortProfileInfo("Webserver", "80; 443"), + new PortProfileInfo("Webserver (Other)", "80; 443; 8080; 8443"), + new PortProfileInfo("Remote access", "22; 23; 3389; 5900"), + new PortProfileInfo("Mailserver", "25; 110; 143; 465; 587; 993; 995"), + new PortProfileInfo("Filetransfer", "20-21; 22; 989-990; 2049"), + new PortProfileInfo("Database", "1433-1434; 1521; 1830; 3306; 5432"), + new PortProfileInfo("SMB", "139; 445"), + new PortProfileInfo("LDAP", "389; 636"), + new PortProfileInfo("HTTP proxy", "3128") + }; } } diff --git a/Source/NETworkManager.Models/Network/PortProfileInfo.cs b/Source/NETworkManager.Models/Network/PortProfileInfo.cs index afbdcf5632..0b15dce2d3 100644 --- a/Source/NETworkManager.Models/Network/PortProfileInfo.cs +++ b/Source/NETworkManager.Models/Network/PortProfileInfo.cs @@ -1,19 +1,18 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class PortProfileInfo { - public class PortProfileInfo - { - public string Name { get; set; } - public string Ports { get; set; } + public string Name { get; set; } + public string Ports { get; set; } - public PortProfileInfo() - { + public PortProfileInfo() + { - } + } - public PortProfileInfo(string name, string ports) - { - Name = name; - Ports = ports; - } + public PortProfileInfo(string name, string ports) + { + Name = name; + Ports = ports; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/PortScannedArgs.cs b/Source/NETworkManager.Models/Network/PortScannedArgs.cs index 68e624990d..9fc13a2d71 100644 --- a/Source/NETworkManager.Models/Network/PortScannedArgs.cs +++ b/Source/NETworkManager.Models/Network/PortScannedArgs.cs @@ -2,28 +2,27 @@ using System; using System.Net; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class PortScannedArgs : EventArgs { - public class PortScannedArgs : EventArgs - { - public IPAddress IPAddress { get; set; } - public string Hostname { get; set; } - public int Port { get; set; } - public PortLookupInfo LookupInfo { get; set; } - public PortState State { get; set; } + public IPAddress IPAddress { get; set; } + public string Hostname { get; set; } + public int Port { get; set; } + public PortLookupInfo LookupInfo { get; set; } + public PortState State { get; set; } - public PortScannedArgs() - { + public PortScannedArgs() + { - } + } - public PortScannedArgs(IPAddress ipAddres, string hostname, int port, PortLookupInfo lookupInfo, PortState state) - { - IPAddress = ipAddres; - Hostname = hostname; - Port = port; - LookupInfo = lookupInfo; - State = state; - } + public PortScannedArgs(IPAddress ipAddres, string hostname, int port, PortLookupInfo lookupInfo, PortState state) + { + IPAddress = ipAddres; + Hostname = hostname; + Port = port; + LookupInfo = lookupInfo; + State = state; } } diff --git a/Source/NETworkManager.Models/Network/PortScanner.cs b/Source/NETworkManager.Models/Network/PortScanner.cs index 30ed0cf2f4..826f81f20f 100644 --- a/Source/NETworkManager.Models/Network/PortScanner.cs +++ b/Source/NETworkManager.Models/Network/PortScanner.cs @@ -7,147 +7,146 @@ using System.Threading; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class PortScanner { - public class PortScanner - { - #region Variables - private int _progressValue; + #region Variables + private int _progressValue; - public bool ResolveHostname = true; - public int HostThreads = 5; - public int PortThreads = 100; - public bool ShowClosed = false; - public int Timeout = 4000; - #endregion + public bool ResolveHostname = true; + public int HostThreads = 5; + public int PortThreads = 100; + public bool ShowClosed = false; + public int Timeout = 4000; + #endregion - #region Events - public event EventHandler PortScanned; + #region Events + public event EventHandler PortScanned; - protected virtual void OnPortScanned(PortScannedArgs e) - { - PortScanned?.Invoke(this, e); - } + protected virtual void OnPortScanned(PortScannedArgs e) + { + PortScanned?.Invoke(this, e); + } - public event EventHandler ScanComplete; + public event EventHandler ScanComplete; - protected virtual void OnScanComplete() - { - ScanComplete?.Invoke(this, EventArgs.Empty); - } + protected virtual void OnScanComplete() + { + ScanComplete?.Invoke(this, EventArgs.Empty); + } - public event EventHandler ProgressChanged; + public event EventHandler ProgressChanged; - public virtual void OnProgressChanged() - { - ProgressChanged?.Invoke(this, new ProgressChangedArgs(_progressValue)); - } + public virtual void OnProgressChanged() + { + ProgressChanged?.Invoke(this, new ProgressChangedArgs(_progressValue)); + } - public event EventHandler UserHasCanceled; + public event EventHandler UserHasCanceled; - protected virtual void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - #endregion + protected virtual void OnUserHasCanceled() + { + UserHasCanceled?.Invoke(this, EventArgs.Empty); + } + #endregion - #region Methods - public void ScanAsync(IPAddress[] ipAddresses, int[] ports, CancellationToken cancellationToken) - { - _progressValue = 0; + #region Methods + public void ScanAsync(IPAddress[] ipAddresses, int[] ports, CancellationToken cancellationToken) + { + _progressValue = 0; - // Modify the ThreadPool for better performance - ThreadPool.GetMinThreads(out var workerThreads, out var completionPortThreads); - ThreadPool.SetMinThreads(workerThreads + HostThreads + PortThreads, completionPortThreads + HostThreads + PortThreads); + // Modify the ThreadPool for better performance + ThreadPool.GetMinThreads(out var workerThreads, out var completionPortThreads); + ThreadPool.SetMinThreads(workerThreads + HostThreads + PortThreads, completionPortThreads + HostThreads + PortThreads); - Task.Run(() => + Task.Run(() => + { + try { - try + var hostParallelOptions = new ParallelOptions { - var hostParallelOptions = new ParallelOptions - { - CancellationToken = cancellationToken, - MaxDegreeOfParallelism = HostThreads - }; + CancellationToken = cancellationToken, + MaxDegreeOfParallelism = HostThreads + }; - var portParallelOptions = new ParallelOptions - { - CancellationToken = cancellationToken, - MaxDegreeOfParallelism = PortThreads / HostThreads - }; + var portParallelOptions = new ParallelOptions + { + CancellationToken = cancellationToken, + MaxDegreeOfParallelism = PortThreads / HostThreads + }; - Parallel.ForEach(ipAddresses, hostParallelOptions, ipAddress => - { - // Resolve Hostname (PTR) - var hostname = string.Empty; + Parallel.ForEach(ipAddresses, hostParallelOptions, ipAddress => + { + // Resolve Hostname (PTR) + var hostname = string.Empty; - if (ResolveHostname) - { - // Don't use await in Paralle.ForEach, this will break - var dnsResolverTask = DNSClient.GetInstance().ResolvePtrAsync(ipAddress); + if (ResolveHostname) + { + // Don't use await in Paralle.ForEach, this will break + var dnsResolverTask = DNSClient.GetInstance().ResolvePtrAsync(ipAddress); - // Wait for task inside a Parallel.Foreach - dnsResolverTask.Wait(); + // Wait for task inside a Parallel.Foreach + dnsResolverTask.Wait(); - if (!dnsResolverTask.Result.HasError) - hostname = dnsResolverTask.Result.Value; - } + if (!dnsResolverTask.Result.HasError) + hostname = dnsResolverTask.Result.Value; + } - // Check each port - Parallel.ForEach(ports, portParallelOptions, port => + // Check each port + Parallel.ForEach(ports, portParallelOptions, port => + { + // Test if port is open + using (var tcpClient = new TcpClient(ipAddress.AddressFamily)) { - // Test if port is open - using (var tcpClient = new TcpClient(ipAddress.AddressFamily)) + PortState portState = PortState.None; + + try + { + var task = tcpClient.ConnectAsync(ipAddress, port); + + if (task.Wait(Timeout)) + portState = tcpClient.Connected ? PortState.Open : PortState.Closed; + else + portState = PortState.TimedOut; + } + catch + { + portState = PortState.Closed; + } + finally { - PortState portState = PortState.None; - - try - { - var task = tcpClient.ConnectAsync(ipAddress, port); - - if (task.Wait(Timeout)) - portState = tcpClient.Connected ? PortState.Open : PortState.Closed; - else - portState = PortState.TimedOut; - } - catch - { - portState = PortState.Closed; - } - finally - { - tcpClient?.Close(); - - if (ShowClosed || portState == PortState.Open) - OnPortScanned(new PortScannedArgs(ipAddress, hostname, port, PortLookup.Lookup(port).FirstOrDefault(x => x.Protocol == PortLookup.Protocol.Tcp), portState)); - } + tcpClient?.Close(); + + if (ShowClosed || portState == PortState.Open) + OnPortScanned(new PortScannedArgs(ipAddress, hostname, port, PortLookup.Lookup(port).FirstOrDefault(x => x.Protocol == PortLookup.Protocol.Tcp), portState)); } + } - IncreaseProgess(); - }); + IncreaseProgess(); }); - } - catch (OperationCanceledException) // If user has canceled - { - OnUserHasCanceled(); - } - finally - { - // Reset the ThreadPool to defaul - ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); - ThreadPool.SetMinThreads(workerThreads - HostThreads + PortThreads, completionPortThreads - HostThreads + PortThreads); + }); + } + catch (OperationCanceledException) // If user has canceled + { + OnUserHasCanceled(); + } + finally + { + // Reset the ThreadPool to defaul + ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); + ThreadPool.SetMinThreads(workerThreads - HostThreads + PortThreads, completionPortThreads - HostThreads + PortThreads); - OnScanComplete(); - } - }, cancellationToken); - } + OnScanComplete(); + } + }, cancellationToken); + } - private void IncreaseProgess() - { - // Increase the progress - Interlocked.Increment(ref _progressValue); - OnProgressChanged(); - } - #endregion + private void IncreaseProgess() + { + // Increase the progress + Interlocked.Increment(ref _progressValue); + OnProgressChanged(); } + #endregion } diff --git a/Source/NETworkManager.Models/Network/PortState.cs b/Source/NETworkManager.Models/Network/PortState.cs index 38c708b675..d014baac32 100644 --- a/Source/NETworkManager.Models/Network/PortState.cs +++ b/Source/NETworkManager.Models/Network/PortState.cs @@ -1,28 +1,27 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Represents the state of a port. +/// +public enum PortState { /// - /// Represents the state of a port. + /// Port is not defined. + /// + None, + + /// + /// Port is open. /// - public enum PortState - { - /// - /// Port is not defined. - /// - None, - - /// - /// Port is open. - /// - Open, + Open, - /// - /// Port is closed. - /// - Closed, + /// + /// Port is closed. + /// + Closed, - /// - /// Port has timed out. - /// - TimedOut - } + /// + /// Port has timed out. + /// + TimedOut } diff --git a/Source/NETworkManager.Models/Network/ProgressChangedArgs.cs b/Source/NETworkManager.Models/Network/ProgressChangedArgs.cs index 2f1eda2886..94efc930b4 100644 --- a/Source/NETworkManager.Models/Network/ProgressChangedArgs.cs +++ b/Source/NETworkManager.Models/Network/ProgressChangedArgs.cs @@ -1,17 +1,16 @@ -namespace NETworkManager.Models.Network -{ - public class ProgressChangedArgs : System.EventArgs - { - public int Value { get; set; } +namespace NETworkManager.Models.Network; - public ProgressChangedArgs() - { +public class ProgressChangedArgs : System.EventArgs +{ + public int Value { get; set; } - } + public ProgressChangedArgs() + { - public ProgressChangedArgs(int value) - { - Value = value; - } } + + public ProgressChangedArgs(int value) + { + Value = value; + } } diff --git a/Source/NETworkManager.Models/Network/SNMPReceivedArgs.cs b/Source/NETworkManager.Models/Network/SNMPReceivedArgs.cs index bbde5de1af..aa041a4040 100644 --- a/Source/NETworkManager.Models/Network/SNMPReceivedArgs.cs +++ b/Source/NETworkManager.Models/Network/SNMPReceivedArgs.cs @@ -1,21 +1,20 @@ using Lextm.SharpSnmpLib; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class SNMPReceivedArgs : System.EventArgs { - public class SNMPReceivedArgs : System.EventArgs - { - public string OID { get; set; } - public string Data { get; set; } + public string OID { get; set; } + public string Data { get; set; } - public SNMPReceivedArgs() - { + public SNMPReceivedArgs() + { - } + } - public SNMPReceivedArgs(ObjectIdentifier oid, ISnmpData data) - { - OID = oid.ToString(); - Data = data.ToString(); - } + public SNMPReceivedArgs(ObjectIdentifier oid, ISnmpData data) + { + OID = oid.ToString(); + Data = data.ToString(); } } diff --git a/Source/NETworkManager.Models/Network/SNMPReceivedInfo.cs b/Source/NETworkManager.Models/Network/SNMPReceivedInfo.cs index 808936db78..fc48f3ec06 100644 --- a/Source/NETworkManager.Models/Network/SNMPReceivedInfo.cs +++ b/Source/NETworkManager.Models/Network/SNMPReceivedInfo.cs @@ -1,24 +1,23 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class SNMPReceivedInfo { - public class SNMPReceivedInfo + public string OID { get; set; } + public string Data { get; set; } + + public SNMPReceivedInfo() { - public string OID { get; set; } - public string Data { get; set; } - - public SNMPReceivedInfo() - { - } + } - public SNMPReceivedInfo(string oid, string data) - { - OID = oid; - Data = data; - } + public SNMPReceivedInfo(string oid, string data) + { + OID = oid; + Data = data; + } - public static SNMPReceivedInfo Parse(SNMPReceivedArgs e) - { - return new SNMPReceivedInfo(e.OID, e.Data); - } + public static SNMPReceivedInfo Parse(SNMPReceivedArgs e) + { + return new SNMPReceivedInfo(e.OID, e.Data); } } diff --git a/Source/NETworkManager.Models/Network/SNTPDateTime.cs b/Source/NETworkManager.Models/Network/SNTPDateTime.cs index 013a4b0d22..c6a0dac5bd 100644 --- a/Source/NETworkManager.Models/Network/SNTPDateTime.cs +++ b/Source/NETworkManager.Models/Network/SNTPDateTime.cs @@ -1,43 +1,42 @@ using System; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class is used to store informations about SNTP date time. +/// +public class SNTPDateTime { /// - /// Class is used to store informations about SNTP date time. + /// Time when the requests started. /// - public class SNTPDateTime + public DateTime LocalStartTime { get; set; } + + /// + /// Time from the SNTP server. + /// + public DateTime NetworkTime { get; set; } + + /// + /// Time when the requests ended. + /// + public DateTime LocalEndTime { get; set; } + + /// + /// Round trip delay in milliseconds. + /// + public double RoundTripDelay { get; set; } + + /// + /// Offset to the local clock in seconds. + /// + public double Offset { get; set; } + + /// + /// Create an instance of . + /// + public SNTPDateTime() { - /// - /// Time when the requests started. - /// - public DateTime LocalStartTime { get; set; } - - /// - /// Time from the SNTP server. - /// - public DateTime NetworkTime { get; set; } - - /// - /// Time when the requests ended. - /// - public DateTime LocalEndTime { get; set; } - - /// - /// Round trip delay in milliseconds. - /// - public double RoundTripDelay { get; set; } - - /// - /// Offset to the local clock in seconds. - /// - public double Offset { get; set; } - - /// - /// Create an instance of . - /// - public SNTPDateTime() - { - - } + } } diff --git a/Source/NETworkManager.Models/Network/SNTPLookup.cs b/Source/NETworkManager.Models/Network/SNTPLookup.cs index 85096d1bd1..ed48c0198e 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookup.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookup.cs @@ -7,128 +7,127 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class SNTPLookup { - public class SNTPLookup + #region Variables + private SNTPLookupSettings _settings; + #endregion + + #region Constructor + public SNTPLookup(SNTPLookupSettings settings) { - #region Variables - private SNTPLookupSettings _settings; - #endregion + _settings = settings; + } + #endregion - #region Constructor - public SNTPLookup(SNTPLookupSettings settings) - { - _settings = settings; - } - #endregion + #region Events + public event EventHandler ResultReceived; - #region Events - public event EventHandler ResultReceived; + protected virtual void OnResultReceived(SNTPLookupResultArgs e) + { + ResultReceived?.Invoke(this, e); + } - protected virtual void OnResultReceived(SNTPLookupResultArgs e) - { - ResultReceived?.Invoke(this, e); - } + public event EventHandler LookupError; - public event EventHandler LookupError; + protected virtual void OnLookupError(SNTPLookupErrorArgs e) + { + LookupError?.Invoke(this, e); + } - protected virtual void OnLookupError(SNTPLookupErrorArgs e) - { - LookupError?.Invoke(this, e); - } + public event EventHandler LookupComplete; - public event EventHandler LookupComplete; + protected virtual void OnLookupComplete() + { + LookupComplete?.Invoke(this, EventArgs.Empty); + } + #endregion - protected virtual void OnLookupComplete() - { - LookupComplete?.Invoke(this, EventArgs.Empty); - } - #endregion + #region Methods + public static SNTPDateTime GetNetworkTimeRfc2030(IPEndPoint server, int timeout = 4000) + { + var ntpData = new byte[48]; // RFC 2030 + ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) - #region Methods - public static SNTPDateTime GetNetworkTimeRfc2030(IPEndPoint server, int timeout = 4000) - { - var ntpData = new byte[48]; // RFC 2030 - ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) + var udpClient = new UdpClient(server.AddressFamily); + udpClient.Client.SendTimeout = timeout; + udpClient.Client.ReceiveTimeout = timeout; + udpClient.Connect(server); - var udpClient = new UdpClient(server.AddressFamily); - udpClient.Client.SendTimeout = timeout; - udpClient.Client.ReceiveTimeout = timeout; - udpClient.Connect(server); + var localStartTime = DateTime.Now.ToUniversalTime(); - var localStartTime = DateTime.Now.ToUniversalTime(); + udpClient.Send(ntpData, ntpData.Length); + ntpData = udpClient.Receive(ref server); - udpClient.Send(ntpData, ntpData.Length); - ntpData = udpClient.Receive(ref server); + var localEndTime = DateTime.Now.ToUniversalTime(); - var localEndTime = DateTime.Now.ToUniversalTime(); + udpClient.Close(); - udpClient.Close(); + ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43]; + ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47]; - ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43]; - ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47]; + var milliseconds = (intPart * 1000) + (fractPart * 1000 / 0x100000000L); + var networkTime = new DateTime(1900, 1, 1).AddMilliseconds((long)milliseconds); - var milliseconds = (intPart * 1000) + (fractPart * 1000 / 0x100000000L); - var networkTime = new DateTime(1900, 1, 1).AddMilliseconds((long)milliseconds); + // Calculate local offset with local start/end time and network time in seconds + var roundTripDelayTicks = localEndTime.Ticks - localStartTime.Ticks; + var offsetInSeconds = (localStartTime.Ticks + (roundTripDelayTicks / 2) - networkTime.Ticks) / TimeSpan.TicksPerSecond; - // Calculate local offset with local start/end time and network time in seconds - var roundTripDelayTicks = localEndTime.Ticks - localStartTime.Ticks; - var offsetInSeconds = (localStartTime.Ticks + (roundTripDelayTicks / 2) - networkTime.Ticks) / TimeSpan.TicksPerSecond; + return new SNTPDateTime() + { + LocalStartTime = localStartTime, + LocalEndTime = localEndTime, + NetworkTime = networkTime, + RoundTripDelay = roundTripDelayTicks / TimeSpan.TicksPerMillisecond, + Offset = offsetInSeconds + }; + } - return new SNTPDateTime() - { - LocalStartTime = localStartTime, - LocalEndTime = localEndTime, - NetworkTime = networkTime, - RoundTripDelay = roundTripDelayTicks / TimeSpan.TicksPerMillisecond, - Offset = offsetInSeconds - }; - } - - public void QueryAsync(IEnumerable servers, bool dnsResolveHostnamePreferIPv4) + public void QueryAsync(IEnumerable servers, bool dnsResolveHostnamePreferIPv4) + { + Task.Run(() => { - Task.Run(() => + Parallel.ForEach(servers, server => { - Parallel.ForEach(servers, server => - { - // NTP requires an IP address to connect to - IPAddress serverIP = null; + // NTP requires an IP address to connect to + IPAddress serverIP = null; - if (Regex.IsMatch(server.Server, RegexHelper.IPv4AddressRegex) || Regex.IsMatch(server.Server, RegexHelper.IPv6AddressRegex)) - { - serverIP = IPAddress.Parse(server.Server); - } - else - { - using var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(server.Server, dnsResolveHostnamePreferIPv4); - - // Wait for task inside a Parallel.Foreach - dnsResolverTask.Wait(); + if (Regex.IsMatch(server.Server, RegexHelper.IPv4AddressRegex) || Regex.IsMatch(server.Server, RegexHelper.IPv6AddressRegex)) + { + serverIP = IPAddress.Parse(server.Server); + } + else + { + using var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(server.Server, dnsResolveHostnamePreferIPv4); - if (dnsResolverTask.Result.HasError) - { - OnLookupError(new SNTPLookupErrorArgs(DNSClientHelper.FormatDNSClientResultError(server.Server, dnsResolverTask.Result), true)); - return; - } + // Wait for task inside a Parallel.Foreach + dnsResolverTask.Wait(); - serverIP = dnsResolverTask.Result.Value; + if (dnsResolverTask.Result.HasError) + { + OnLookupError(new SNTPLookupErrorArgs(DNSClientHelper.FormatDNSClientResultError(server.Server, dnsResolverTask.Result), true)); + return; } - try - { - SNTPDateTime dateTime = GetNetworkTimeRfc2030(new(serverIP, server.Port), _settings.Timeout); + serverIP = dnsResolverTask.Result.Value; + } - OnResultReceived(new SNTPLookupResultArgs(server.Server, $"{serverIP}:{server.Port}", dateTime)); - } - catch (Exception ex) - { - OnLookupError(new SNTPLookupErrorArgs(server.Server, $"{serverIP}:{server.Port}", ex.Message)); - } - }); + try + { + SNTPDateTime dateTime = GetNetworkTimeRfc2030(new(serverIP, server.Port), _settings.Timeout); - OnLookupComplete(); + OnResultReceived(new SNTPLookupResultArgs(server.Server, $"{serverIP}:{server.Port}", dateTime)); + } + catch (Exception ex) + { + OnLookupError(new SNTPLookupErrorArgs(server.Server, $"{serverIP}:{server.Port}", ex.Message)); + } }); - } - #endregion + + OnLookupComplete(); + }); } + #endregion } diff --git a/Source/NETworkManager.Models/Network/SNTPLookupErrorArgs.cs b/Source/NETworkManager.Models/Network/SNTPLookupErrorArgs.cs index 463ad006ef..3f208a2bec 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookupErrorArgs.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookupErrorArgs.cs @@ -1,31 +1,30 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class SNTPLookupErrorArgs : System.EventArgs { - public class SNTPLookupErrorArgs : System.EventArgs - { - public string Server { get; set; } + public string Server { get; set; } - public string IPEndPoint { get; set; } - - public string ErrorMessage { get; set; } + public string IPEndPoint { get; set; } + + public string ErrorMessage { get; set; } - public bool IsDNSError { get; set; } + public bool IsDNSError { get; set; } - public SNTPLookupErrorArgs() - { + public SNTPLookupErrorArgs() + { - } + } - public SNTPLookupErrorArgs(string errorMessage, bool isDNSError) - { - ErrorMessage = errorMessage; - IsDNSError = isDNSError; - } + public SNTPLookupErrorArgs(string errorMessage, bool isDNSError) + { + ErrorMessage = errorMessage; + IsDNSError = isDNSError; + } - public SNTPLookupErrorArgs(string server, string ipEndPoint, string errorMessage) - { - Server = server; - IPEndPoint = ipEndPoint; - ErrorMessage = errorMessage; - } + public SNTPLookupErrorArgs(string server, string ipEndPoint, string errorMessage) + { + Server = server; + IPEndPoint = ipEndPoint; + ErrorMessage = errorMessage; } } diff --git a/Source/NETworkManager.Models/Network/SNTPLookupResultArgs.cs b/Source/NETworkManager.Models/Network/SNTPLookupResultArgs.cs index 542bcfd796..5ca30ec1a5 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookupResultArgs.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookupResultArgs.cs @@ -1,23 +1,22 @@ using System.Net; -namespace NETworkManager.Models.Network -{ - public class SNTPLookupResultArgs : System.EventArgs - { - public string Server { get; set; } - public string IPEndPoint { get; set; } - public SNTPDateTime DateTime { get; set; } +namespace NETworkManager.Models.Network; - public SNTPLookupResultArgs() - { +public class SNTPLookupResultArgs : System.EventArgs +{ + public string Server { get; set; } + public string IPEndPoint { get; set; } + public SNTPDateTime DateTime { get; set; } - } + public SNTPLookupResultArgs() + { - public SNTPLookupResultArgs(string server, string ipEndPoint, SNTPDateTime dateTime) - { - Server = server; - IPEndPoint = ipEndPoint; - DateTime = dateTime; - } + } + + public SNTPLookupResultArgs(string server, string ipEndPoint, SNTPDateTime dateTime) + { + Server = server; + IPEndPoint = ipEndPoint; + DateTime = dateTime; } } diff --git a/Source/NETworkManager.Models/Network/SNTPLookupResultInfo.cs b/Source/NETworkManager.Models/Network/SNTPLookupResultInfo.cs index 1ed51fed58..a31e5e6cea 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookupResultInfo.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookupResultInfo.cs @@ -1,26 +1,25 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class SNTPLookupResultInfo { - public class SNTPLookupResultInfo + public string Server { get; set; } + public string IPEndPoint { get; set; } + public SNTPDateTime DateTime { get; set; } + + public SNTPLookupResultInfo() { - public string Server { get; set; } - public string IPEndPoint { get; set; } - public SNTPDateTime DateTime { get; set; } - - public SNTPLookupResultInfo() - { - } + } - public SNTPLookupResultInfo(string server, string ipEndPoint, SNTPDateTime dateTime) - { - Server = server; - IPEndPoint = ipEndPoint; - DateTime = dateTime; - } + public SNTPLookupResultInfo(string server, string ipEndPoint, SNTPDateTime dateTime) + { + Server = server; + IPEndPoint = ipEndPoint; + DateTime = dateTime; + } - public static SNTPLookupResultInfo Parse(SNTPLookupResultArgs e) - { - return new SNTPLookupResultInfo(e.Server, e.IPEndPoint, e.DateTime); - } + public static SNTPLookupResultInfo Parse(SNTPLookupResultArgs e) + { + return new SNTPLookupResultInfo(e.Server, e.IPEndPoint, e.DateTime); } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/SNTPLookupSettings.cs b/Source/NETworkManager.Models/Network/SNTPLookupSettings.cs index 656fb50854..13eabcf5cc 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookupSettings.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookupSettings.cs @@ -1,13 +1,12 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class contains the settings for the SNTP lookup. +/// +public class SNTPLookupSettings { /// - /// Class contains the settings for the SNTP lookup. + /// Timeout in milliseconds after which the request is aborted. /// - public class SNTPLookupSettings - { - /// - /// Timeout in milliseconds after which the request is aborted. - /// - public int Timeout { get; set; } - } + public int Timeout { get; set; } } diff --git a/Source/NETworkManager.Models/Network/SNTPServer.cs b/Source/NETworkManager.Models/Network/SNTPServer.cs index 2d82858761..988c39b1ec 100644 --- a/Source/NETworkManager.Models/Network/SNTPServer.cs +++ b/Source/NETworkManager.Models/Network/SNTPServer.cs @@ -1,41 +1,40 @@ using System.Collections.Generic; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class provides static informations about SNTP servers. +/// +public static class SNTPServer { /// - /// Class provides static informations about SNTP servers. + /// Method will return a default list of common SNTP servers. /// - public static class SNTPServer + /// GetDefaultList() => new() { - /// - /// Method will return a default list of common SNTP servers. - /// - /// GetDefaultList() => new() + new ServerConnectionInfoProfile("Cloudflare", new() + { + new ServerConnectionInfo("time.cloudflare.com", 123) + }), + new ServerConnectionInfoProfile("Google Public NTP", new() + { + new ServerConnectionInfo("time.google.com", 123), + new ServerConnectionInfo("time1.google.com", 123), + new ServerConnectionInfo("time2.google.com", 123), + new ServerConnectionInfo ("time3.google.com", 123), + new ServerConnectionInfo("time4.google.com", 123) + }), + new ServerConnectionInfoProfile("Microsoft", new() + { + new ServerConnectionInfo("time.windows.com", 123) + }), + new ServerConnectionInfoProfile("pool.ntp.org", new() { - new ServerConnectionInfoProfile("Cloudflare", new() - { - new ServerConnectionInfo("time.cloudflare.com", 123) - }), - new ServerConnectionInfoProfile("Google Public NTP", new() - { - new ServerConnectionInfo("time.google.com", 123), - new ServerConnectionInfo("time1.google.com", 123), - new ServerConnectionInfo("time2.google.com", 123), - new ServerConnectionInfo ("time3.google.com", 123), - new ServerConnectionInfo("time4.google.com", 123) - }), - new ServerConnectionInfoProfile("Microsoft", new() - { - new ServerConnectionInfo("time.windows.com", 123) - }), - new ServerConnectionInfoProfile("pool.ntp.org", new() - { - new ServerConnectionInfo("0.pool.ntp.org", 123), - new ServerConnectionInfo("1.pool.ntp.org", 123), - new ServerConnectionInfo("2.pool.ntp.org", 123), - new ServerConnectionInfo("3.pool.ntp.org", 123) - }) - }; - } + new ServerConnectionInfo("0.pool.ntp.org", 123), + new ServerConnectionInfo("1.pool.ntp.org", 123), + new ServerConnectionInfo("2.pool.ntp.org", 123), + new ServerConnectionInfo("3.pool.ntp.org", 123) + }) + }; } diff --git a/Source/NETworkManager.Models/Network/ServerConnectionInfo.cs b/Source/NETworkManager.Models/Network/ServerConnectionInfo.cs index cde57b1ad4..c58117a070 100644 --- a/Source/NETworkManager.Models/Network/ServerConnectionInfo.cs +++ b/Source/NETworkManager.Models/Network/ServerConnectionInfo.cs @@ -1,67 +1,66 @@ using System.Net; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class contains information about a server. +/// +public class ServerConnectionInfo { /// - /// Class contains information about a server. + /// Server name or IP address. /// - public class ServerConnectionInfo - { - /// - /// Server name or IP address. - /// - public string Server { get; set; } + public string Server { get; set; } - /// - /// Port used for the connection. - /// - public int Port { get; set; } + /// + /// Port used for the connection. + /// + public int Port { get; set; } - /// - /// Transport protocol used for the connection. - /// - public TransportProtocol TransportProtocol { get; set; } + /// + /// Transport protocol used for the connection. + /// + public TransportProtocol TransportProtocol { get; set; } - /// - /// Create an instance of . - /// - public ServerConnectionInfo() - { - - } + /// + /// Create an instance of . + /// + public ServerConnectionInfo() + { + + } - /// - /// Create an instance of with parameters. Default transport protocol is TCP. - /// - /// Server name or IP address. - /// Port used for the connection. - public ServerConnectionInfo(string server, int port) - { - Server = server; - Port = port; - TransportProtocol = TransportProtocol.TCP; - } + /// + /// Create an instance of with parameters. Default transport protocol is TCP. + /// + /// Server name or IP address. + /// Port used for the connection. + public ServerConnectionInfo(string server, int port) + { + Server = server; + Port = port; + TransportProtocol = TransportProtocol.TCP; + } - /// - /// Create an instance of with parameters. - /// - /// Server name or IP address. - /// Port used for the connection. - /// Transport protocol used for the connection. - public ServerConnectionInfo(string server, int port, TransportProtocol transportProtocol) - { - Server = server; - Port = port; - TransportProtocol = transportProtocol; - } + /// + /// Create an instance of with parameters. + /// + /// Server name or IP address. + /// Port used for the connection. + /// Transport protocol used for the connection. + public ServerConnectionInfo(string server, int port, TransportProtocol transportProtocol) + { + Server = server; + Port = port; + TransportProtocol = transportProtocol; + } - /// - /// Returns a string that represents the current object. - /// - /// Server:Port - public override string ToString() - { - return $"{Server}:{Port}"; - } + /// + /// Returns a string that represents the current object. + /// + /// Server:Port + public override string ToString() + { + return $"{Server}:{Port}"; } } diff --git a/Source/NETworkManager.Models/Network/ServerConnectionInfoProfile.cs b/Source/NETworkManager.Models/Network/ServerConnectionInfoProfile.cs index 8e5103771d..9c3dabbc41 100644 --- a/Source/NETworkManager.Models/Network/ServerConnectionInfoProfile.cs +++ b/Source/NETworkManager.Models/Network/ServerConnectionInfoProfile.cs @@ -1,39 +1,38 @@ using System.Collections.Generic; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +/// +/// Class is used to store informations about a server profile. +/// +public class ServerConnectionInfoProfile { /// - /// Class is used to store informations about a server profile. + /// Name of the server profile. /// - public class ServerConnectionInfoProfile - { - /// - /// Name of the server profile. - /// - public string Name { get; set; } - - /// - /// List of servers as . - /// - public List Servers { get; set; } = new(); + public string Name { get; set; } - /// - /// Create an instance of . - /// - public ServerConnectionInfoProfile() - { + /// + /// List of servers as . + /// + public List Servers { get; set; } = new(); - } + /// + /// Create an instance of . + /// + public ServerConnectionInfoProfile() + { - /// - /// Create an instance of with parameters. - /// - /// Name of the profile. - /// List of servers as . - public ServerConnectionInfoProfile(string name, List servers) - { - Name = name; - Servers = servers; - } } + + /// + /// Create an instance of with parameters. + /// + /// Name of the profile. + /// List of servers as . + public ServerConnectionInfoProfile(string name, List servers) + { + Name = name; + Servers = servers; + } } diff --git a/Source/NETworkManager.Models/Network/Subnetmask.cs b/Source/NETworkManager.Models/Network/Subnetmask.cs index 216cbde001..930cd939f8 100644 --- a/Source/NETworkManager.Models/Network/Subnetmask.cs +++ b/Source/NETworkManager.Models/Network/Subnetmask.cs @@ -1,44 +1,43 @@ using System.Collections.Generic; using System.Net; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public static class Subnetmask { - public static class Subnetmask - { - public static List List => GenerateList(); + public static List List => GenerateList(); - private static List GenerateList() - { - var list = new List(); + private static List GenerateList() + { + var list = new List(); - for (var i = 2; i < 31; i++) - list.Add(GetFromCidr(i)); + for (var i = 2; i < 31; i++) + list.Add(GetFromCidr(i)); - return list; - } + return list; + } - public static SubnetmaskInfo GetFromCidr(int cidr) - { - return new SubnetmaskInfo - { - CIDR = cidr, - Subnetmask = ConvertCidrToSubnetmask(cidr) - }; - } - - public static string ConvertCidrToSubnetmask(int cidr) + public static SubnetmaskInfo GetFromCidr(int cidr) + { + return new SubnetmaskInfo { - var bits = string.Empty; + CIDR = cidr, + Subnetmask = ConvertCidrToSubnetmask(cidr) + }; + } - for (var i = 0; i < cidr; i++) - bits += "1"; + public static string ConvertCidrToSubnetmask(int cidr) + { + var bits = string.Empty; - return IPv4Address.ToHumanString(bits.PadRight(32, '0')); - } + for (var i = 0; i < cidr; i++) + bits += "1"; - public static int ConvertSubnetmaskToCidr(IPAddress subnetmask) - { - return string.Join("", IPv4Address.ToBinaryString(subnetmask.ToString()).Replace(".", "").TrimEnd('0')).Length; - } + return IPv4Address.ToHumanString(bits.PadRight(32, '0')); + } + + public static int ConvertSubnetmaskToCidr(IPAddress subnetmask) + { + return string.Join("", IPv4Address.ToBinaryString(subnetmask.ToString()).Replace(".", "").TrimEnd('0')).Length; } } diff --git a/Source/NETworkManager.Models/Network/SubnetmaskInfo.cs b/Source/NETworkManager.Models/Network/SubnetmaskInfo.cs index c219c42ee0..a47c99a3bf 100644 --- a/Source/NETworkManager.Models/Network/SubnetmaskInfo.cs +++ b/Source/NETworkManager.Models/Network/SubnetmaskInfo.cs @@ -1,24 +1,23 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class SubnetmaskInfo { - public class SubnetmaskInfo - { - public int CIDR { get; set; } - public string Subnetmask { get; set; } + public int CIDR { get; set; } + public string Subnetmask { get; set; } - public SubnetmaskInfo() - { + public SubnetmaskInfo() + { - } + } - public SubnetmaskInfo(int cidr, string subnetmask) - { - CIDR = cidr; - Subnetmask = subnetmask; - } + public SubnetmaskInfo(int cidr, string subnetmask) + { + CIDR = cidr; + Subnetmask = subnetmask; + } - public override string ToString() - { - return Subnetmask; - } + public override string ToString() + { + return Subnetmask; } } diff --git a/Source/NETworkManager.Models/Network/Traceroute.cs b/Source/NETworkManager.Models/Network/Traceroute.cs index 724b03cc17..6bea733a47 100644 --- a/Source/NETworkManager.Models/Network/Traceroute.cs +++ b/Source/NETworkManager.Models/Network/Traceroute.cs @@ -8,151 +8,150 @@ using System.Threading; using System.Threading.Tasks; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class Traceroute { - public class Traceroute - { - #region Variables - private readonly TracerouteOptions _options; - #endregion + #region Variables + private readonly TracerouteOptions _options; + #endregion - #region Events - public event EventHandler HopReceived; - protected virtual void OnHopReceived(TracerouteHopReceivedArgs e) - { - HopReceived?.Invoke(this, e); - } + #region Events + public event EventHandler HopReceived; + protected virtual void OnHopReceived(TracerouteHopReceivedArgs e) + { + HopReceived?.Invoke(this, e); + } - public event EventHandler TraceComplete; - protected virtual void OnTraceComplete() - { - TraceComplete?.Invoke(this, EventArgs.Empty); - } + public event EventHandler TraceComplete; + protected virtual void OnTraceComplete() + { + TraceComplete?.Invoke(this, EventArgs.Empty); + } - public event EventHandler MaximumHopsReached; - protected virtual void OnMaximumHopsReached(MaximumHopsReachedArgs e) - { - MaximumHopsReached?.Invoke(this, e); - } + public event EventHandler MaximumHopsReached; + protected virtual void OnMaximumHopsReached(MaximumHopsReachedArgs e) + { + MaximumHopsReached?.Invoke(this, e); + } - public event EventHandler TraceError; - protected virtual void OnTraceError(TracerouteErrorArgs e) - { - TraceError?.Invoke(this, e); - } + public event EventHandler TraceError; + protected virtual void OnTraceError(TracerouteErrorArgs e) + { + TraceError?.Invoke(this, e); + } - public event EventHandler UserHasCanceled; - protected virtual void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - #endregion + public event EventHandler UserHasCanceled; + protected virtual void OnUserHasCanceled() + { + UserHasCanceled?.Invoke(this, EventArgs.Empty); + } + #endregion - #region Constructor - public Traceroute(TracerouteOptions options) - { - _options = options; - } - #endregion + #region Constructor + public Traceroute(TracerouteOptions options) + { + _options = options; + } + #endregion - #region Methods - public void TraceAsync(IPAddress ipAddress, CancellationToken cancellationToken) + #region Methods + public void TraceAsync(IPAddress ipAddress, CancellationToken cancellationToken) + { + Task.Run(async () => { - Task.Run(async () => + try { - try + for (var i = 1; i < _options.MaximumHops + 1; i++) { - for (var i = 1; i < _options.MaximumHops + 1; i++) + var tasks = new List>>(); + + // Send 3 pings + for (var y = 0; y < 3; y++) { - var tasks = new List>>(); + var i1 = i; - // Send 3 pings - for (var y = 0; y < 3; y++) + tasks.Add(Task.Run(() => { - var i1 = i; + var stopwatch = new Stopwatch(); - tasks.Add(Task.Run(() => - { - var stopwatch = new Stopwatch(); + PingReply pingReply; - PingReply pingReply; + using (var ping = new System.Net.NetworkInformation.Ping()) + { + stopwatch.Start(); - using (var ping = new System.Net.NetworkInformation.Ping()) - { - stopwatch.Start(); + pingReply = ping.Send(ipAddress, _options.Timeout, _options.Buffer, new PingOptions { Ttl = i1, DontFragment = _options.DontFragment }); - pingReply = ping.Send(ipAddress, _options.Timeout, _options.Buffer, new PingOptions { Ttl = i1, DontFragment = _options.DontFragment }); + stopwatch.Stop(); + } - stopwatch.Stop(); - } + return Tuple.Create(pingReply, stopwatch.ElapsedMilliseconds); + }, cancellationToken)); + } - return Tuple.Create(pingReply, stopwatch.ElapsedMilliseconds); - }, cancellationToken)); - } + try + { + Task.WaitAll(tasks.ToArray()); + } + catch (AggregateException ex) + { + // Remove duplicate messages + OnTraceError(new TracerouteErrorArgs(string.Join(", ", ex.Flatten().InnerExceptions.Select(s => s.Message).Distinct()))); + return; + } - try - { - Task.WaitAll(tasks.ToArray()); - } - catch (AggregateException ex) - { - // Remove duplicate messages - OnTraceError(new TracerouteErrorArgs(string.Join(", ", ex.Flatten().InnerExceptions.Select(s => s.Message).Distinct()))); - return; - } + // Check results -> Get IP on success or TTL expired + IPAddress ipAddressHop = null; - // Check results -> Get IP on success or TTL expired - IPAddress ipAddressHop = null; + foreach (var task in tasks) + { + if (task.Result.Item1.Status == IPStatus.TimedOut) + continue; - foreach (var task in tasks) + if (task.Result.Item1.Status == IPStatus.TtlExpired || task.Result.Item1.Status == IPStatus.Success) { - if (task.Result.Item1.Status == IPStatus.TimedOut) - continue; - - if (task.Result.Item1.Status == IPStatus.TtlExpired || task.Result.Item1.Status == IPStatus.Success) - { - ipAddressHop = task.Result.Item1.Address; - break; - } + ipAddressHop = task.Result.Item1.Address; + break; } + } - // Resolve Hostname - var hostname = string.Empty; - - if (ipAddressHop != null && _options.ResolveHostname) - { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(ipAddressHop); - - if (!dnsResult.HasError) - hostname = dnsResult.Value; - } + // Resolve Hostname + var hostname = string.Empty; - OnHopReceived(new TracerouteHopReceivedArgs(i, tasks[0].Result.Item2, tasks[1].Result.Item2, tasks[2].Result.Item2, ipAddressHop, hostname, tasks[0].Result.Item1.Status, tasks[1].Result.Item1.Status, tasks[2].Result.Item1.Status)); + if (ipAddressHop != null && _options.ResolveHostname) + { + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(ipAddressHop); - // Check if finished - if (ipAddressHop != null && ipAddress.ToString() == ipAddressHop.ToString()) - { - OnTraceComplete(); - return; - } + if (!dnsResult.HasError) + hostname = dnsResult.Value; + } - // Check for cancel - if (!cancellationToken.IsCancellationRequested) - continue; + OnHopReceived(new TracerouteHopReceivedArgs(i, tasks[0].Result.Item2, tasks[1].Result.Item2, tasks[2].Result.Item2, ipAddressHop, hostname, tasks[0].Result.Item1.Status, tasks[1].Result.Item1.Status, tasks[2].Result.Item1.Status)); - OnUserHasCanceled(); + // Check if finished + if (ipAddressHop != null && ipAddress.ToString() == ipAddressHop.ToString()) + { + OnTraceComplete(); return; } - // Max hops reached... - OnMaximumHopsReached(new MaximumHopsReachedArgs(_options.MaximumHops)); - } - catch (Exception ex) - { - OnTraceError(new TracerouteErrorArgs(ex.Message)); + // Check for cancel + if (!cancellationToken.IsCancellationRequested) + continue; + + OnUserHasCanceled(); + return; } - }, cancellationToken); - } - #endregion + + // Max hops reached... + OnMaximumHopsReached(new MaximumHopsReachedArgs(_options.MaximumHops)); + } + catch (Exception ex) + { + OnTraceError(new TracerouteErrorArgs(ex.Message)); + } + }, cancellationToken); } + #endregion } diff --git a/Source/NETworkManager.Models/Network/TracerouteErrorArgs.cs b/Source/NETworkManager.Models/Network/TracerouteErrorArgs.cs index eb7d99df92..ccc1d38e8e 100644 --- a/Source/NETworkManager.Models/Network/TracerouteErrorArgs.cs +++ b/Source/NETworkManager.Models/Network/TracerouteErrorArgs.cs @@ -1,17 +1,16 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class TracerouteErrorArgs : System.EventArgs { - public class TracerouteErrorArgs : System.EventArgs - { - public string ErrorMessage { get; set; } + public string ErrorMessage { get; set; } - public TracerouteErrorArgs() - { + public TracerouteErrorArgs() + { - } + } - public TracerouteErrorArgs(string errorMessage) - { - ErrorMessage = errorMessage; - } + public TracerouteErrorArgs(string errorMessage) + { + ErrorMessage = errorMessage; } } diff --git a/Source/NETworkManager.Models/Network/TracerouteHopInfo.cs b/Source/NETworkManager.Models/Network/TracerouteHopInfo.cs index 3656a7147b..39219b0cf5 100644 --- a/Source/NETworkManager.Models/Network/TracerouteHopInfo.cs +++ b/Source/NETworkManager.Models/Network/TracerouteHopInfo.cs @@ -2,41 +2,40 @@ using System.Net; using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class TracerouteHopInfo { - public class TracerouteHopInfo - { - public int Hop { get; set; } - public long Time1 { get; set; } - public long Time2 { get; set; } - public long Time3 { get; set; } - public IPAddress IPAddress { get; set; } - public string Hostname { get; set; } - public IPStatus Status1 { get; set; } - public IPStatus Status2 { get; set; } - public IPStatus Status3 { get; set; } + public int Hop { get; set; } + public long Time1 { get; set; } + public long Time2 { get; set; } + public long Time3 { get; set; } + public IPAddress IPAddress { get; set; } + public string Hostname { get; set; } + public IPStatus Status1 { get; set; } + public IPStatus Status2 { get; set; } + public IPStatus Status3 { get; set; } - public TracerouteHopInfo() - { + public TracerouteHopInfo() + { - } + } - public TracerouteHopInfo(int hop, long time1, long time2, long time3, IPAddress ipAddress, string hostname, IPStatus status1, IPStatus status2, IPStatus status3) - { - Hop = hop; - Time1 = time1; - Time2 = time2; - Time3 = time3; - IPAddress = ipAddress; - Hostname = hostname; - Status1 = status1; - Status2 = status2; - Status3 = status3; - } + public TracerouteHopInfo(int hop, long time1, long time2, long time3, IPAddress ipAddress, string hostname, IPStatus status1, IPStatus status2, IPStatus status3) + { + Hop = hop; + Time1 = time1; + Time2 = time2; + Time3 = time3; + IPAddress = ipAddress; + Hostname = hostname; + Status1 = status1; + Status2 = status2; + Status3 = status3; + } - public static TracerouteHopInfo Parse(TracerouteHopReceivedArgs e) - { - return new TracerouteHopInfo(e.Hop, e.Time1, e.Time2, e.Time3, e.IPAddress, e.Hostname, e.Status1, e.Status2, e.Status3); - } + public static TracerouteHopInfo Parse(TracerouteHopReceivedArgs e) + { + return new TracerouteHopInfo(e.Hop, e.Time1, e.Time2, e.Time3, e.IPAddress, e.Hostname, e.Status1, e.Status2, e.Status3); } } diff --git a/Source/NETworkManager.Models/Network/TracerouteHopReceivedArgs.cs b/Source/NETworkManager.Models/Network/TracerouteHopReceivedArgs.cs index 0885d4feb0..aabb591e2f 100644 --- a/Source/NETworkManager.Models/Network/TracerouteHopReceivedArgs.cs +++ b/Source/NETworkManager.Models/Network/TracerouteHopReceivedArgs.cs @@ -1,36 +1,35 @@ using System.Net; using System.Net.NetworkInformation; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class TracerouteHopReceivedArgs : System.EventArgs { - public class TracerouteHopReceivedArgs : System.EventArgs - { - public int Hop { get; set; } - public long Time1 { get; set; } - public long Time2 { get; set; } - public long Time3 { get; set; } - public IPAddress IPAddress { get; set; } - public string Hostname { get; set; } - public IPStatus Status1 { get; set; } - public IPStatus Status2 { get; set; } - public IPStatus Status3 { get; set; } + public int Hop { get; set; } + public long Time1 { get; set; } + public long Time2 { get; set; } + public long Time3 { get; set; } + public IPAddress IPAddress { get; set; } + public string Hostname { get; set; } + public IPStatus Status1 { get; set; } + public IPStatus Status2 { get; set; } + public IPStatus Status3 { get; set; } - public TracerouteHopReceivedArgs() - { + public TracerouteHopReceivedArgs() + { - } + } - public TracerouteHopReceivedArgs(int hop, long time1, long time2, long time3, IPAddress ipAddress, string hostname, IPStatus status1, IPStatus status2, IPStatus status3) - { - Hop = hop; - Time1 = time1; - Time2 = time2; - Time3 = time3; - IPAddress = ipAddress; - Hostname = hostname; - Status1 = status1; - Status2 = status2; - Status3 = status3; - } + public TracerouteHopReceivedArgs(int hop, long time1, long time2, long time3, IPAddress ipAddress, string hostname, IPStatus status1, IPStatus status2, IPStatus status3) + { + Hop = hop; + Time1 = time1; + Time2 = time2; + Time3 = time3; + IPAddress = ipAddress; + Hostname = hostname; + Status1 = status1; + Status2 = status2; + Status3 = status3; } } diff --git a/Source/NETworkManager.Models/Network/WakeOnLAN.cs b/Source/NETworkManager.Models/Network/WakeOnLAN.cs index 776c2f5f8b..fc0e8ab5a9 100644 --- a/Source/NETworkManager.Models/Network/WakeOnLAN.cs +++ b/Source/NETworkManager.Models/Network/WakeOnLAN.cs @@ -1,41 +1,40 @@ using NETworkManager.Utilities; using System.Net.Sockets; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public static class WakeOnLAN { - public static class WakeOnLAN + public static void Send(WakeOnLANInfo info) { - public static void Send(WakeOnLANInfo info) + using (var udpClient = new UdpClient()) { - using (var udpClient = new UdpClient()) - { - udpClient.Connect(info.Broadcast, info.Port); + udpClient.Connect(info.Broadcast, info.Port); - udpClient.Send(info.MagicPacket, info.MagicPacket.Length); - } + udpClient.Send(info.MagicPacket, info.MagicPacket.Length); } + } - public static byte[] CreateMagicPacket(byte[] mac) - { - var packet = new byte[17 * 6]; - - for (var i = 0; i < 6; i++) - packet[i] = 0xFF; + public static byte[] CreateMagicPacket(byte[] mac) + { + var packet = new byte[17 * 6]; - for (var i = 1; i <= 16; i++) - { - for (var j = 0; j < 6; j++) - packet[i * 6 + j] = mac[j]; - } + for (var i = 0; i < 6; i++) + packet[i] = 0xFF; - return packet; + for (var i = 1; i <= 16; i++) + { + for (var j = 0; j < 6; j++) + packet[i * 6 + j] = mac[j]; } - public static byte[] CreateMagicPacket(string mac) - { - var macBytes = MACAddressHelper.ConvertStringToByteArray(mac); + return packet; + } - return CreateMagicPacket(macBytes); - } + public static byte[] CreateMagicPacket(string mac) + { + var macBytes = MACAddressHelper.ConvertStringToByteArray(mac); + + return CreateMagicPacket(macBytes); } } diff --git a/Source/NETworkManager.Models/Network/WakeOnLanInfo.cs b/Source/NETworkManager.Models/Network/WakeOnLanInfo.cs index 2210bb0571..8db31b1c1a 100644 --- a/Source/NETworkManager.Models/Network/WakeOnLanInfo.cs +++ b/Source/NETworkManager.Models/Network/WakeOnLanInfo.cs @@ -1,23 +1,22 @@ using System.Net; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class WakeOnLANInfo { - public class WakeOnLANInfo - { - public byte[] MagicPacket; - public IPAddress Broadcast; - public int Port; + public byte[] MagicPacket; + public IPAddress Broadcast; + public int Port; - public WakeOnLANInfo() - { + public WakeOnLANInfo() + { - } + } - public WakeOnLANInfo(byte[] magicPacket, IPAddress broadcast, int port) - { - MagicPacket = magicPacket; - Broadcast = broadcast; - Port = port; - } + public WakeOnLANInfo(byte[] magicPacket, IPAddress broadcast, int port) + { + MagicPacket = magicPacket; + Broadcast = broadcast; + Port = port; } } diff --git a/Source/NETworkManager.Models/Network/Whois.cs b/Source/NETworkManager.Models/Network/Whois.cs index a9930428ad..76984e3fc1 100644 --- a/Source/NETworkManager.Models/Network/Whois.cs +++ b/Source/NETworkManager.Models/Network/Whois.cs @@ -7,74 +7,73 @@ using System.Threading.Tasks; using System.Xml; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public static class Whois { - public static class Whois - { - #region Variables - private static readonly string WhoisServerFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Resources", "WhoisServers.xml"); + #region Variables + private static readonly string WhoisServerFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Resources", "WhoisServers.xml"); - private static readonly List WhoisServerList; - private static readonly Lookup WhoisServers; - #endregion + private static readonly List WhoisServerList; + private static readonly Lookup WhoisServers; + #endregion - #region Constructor + #region Constructor - static Whois() - { - var document = new XmlDocument(); - document.Load(WhoisServerFilePath); - - WhoisServerList = new List(); + static Whois() + { + var document = new XmlDocument(); + document.Load(WhoisServerFilePath); - foreach (XmlNode node in document.SelectNodes("/WhoisServers/WhoisServer")) - { - if (node == null) - continue; + WhoisServerList = new List(); - WhoisServerList.Add(new WhoisServerInfo(node.SelectSingleNode("Server")?.InnerText, node.SelectSingleNode("TLD")?.InnerText)); - } + foreach (XmlNode node in document.SelectNodes("/WhoisServers/WhoisServer")) + { + if (node == null) + continue; - WhoisServers = (Lookup)WhoisServerList.ToLookup(x => x.Tld); + WhoisServerList.Add(new WhoisServerInfo(node.SelectSingleNode("Server")?.InnerText, node.SelectSingleNode("TLD")?.InnerText)); } - #endregion - #region Methods - public static Task QueryAsync(string domain, string whoisServer) - { - return Task.Run(() => Query(domain, whoisServer)); - } + WhoisServers = (Lookup)WhoisServerList.ToLookup(x => x.Tld); + } + #endregion - public static string Query(string domain, string whoisServer) - { - var tcpClient = new TcpClient(whoisServer, 43); + #region Methods + public static Task QueryAsync(string domain, string whoisServer) + { + return Task.Run(() => Query(domain, whoisServer)); + } - var networkStream = tcpClient.GetStream(); + public static string Query(string domain, string whoisServer) + { + var tcpClient = new TcpClient(whoisServer, 43); - var bufferedStream = new BufferedStream(networkStream); + var networkStream = tcpClient.GetStream(); - var streamWriter = new StreamWriter(bufferedStream); + var bufferedStream = new BufferedStream(networkStream); - streamWriter.WriteLine(domain); - streamWriter.Flush(); + var streamWriter = new StreamWriter(bufferedStream); - var streamReader = new StreamReader(bufferedStream); + streamWriter.WriteLine(domain); + streamWriter.Flush(); - var stringBuilder = new StringBuilder(); + var streamReader = new StreamReader(bufferedStream); - while (!streamReader.EndOfStream) - stringBuilder.AppendLine(streamReader.ReadLine()); + var stringBuilder = new StringBuilder(); - return stringBuilder.ToString(); - } + while (!streamReader.EndOfStream) + stringBuilder.AppendLine(streamReader.ReadLine()); - public static string GetWhoisServer(string domain) - { - var domainParts = domain.Split('.'); + return stringBuilder.ToString(); + } - // TLD to upper because the lookup is case sensitive - return WhoisServers[domainParts[domainParts.Length - 1].ToUpper()].FirstOrDefault()?.Server; - } - #endregion + public static string GetWhoisServer(string domain) + { + var domainParts = domain.Split('.'); + + // TLD to upper because the lookup is case sensitive + return WhoisServers[domainParts[domainParts.Length - 1].ToUpper()].FirstOrDefault()?.Server; } + #endregion } diff --git a/Source/NETworkManager.Models/Network/WhoisServerInfo.cs b/Source/NETworkManager.Models/Network/WhoisServerInfo.cs index da9d430f9c..c573b4168a 100644 --- a/Source/NETworkManager.Models/Network/WhoisServerInfo.cs +++ b/Source/NETworkManager.Models/Network/WhoisServerInfo.cs @@ -1,14 +1,13 @@ -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class WhoisServerInfo { - public class WhoisServerInfo - { - public string Server { get; set; } - public string Tld { get; set; } + public string Server { get; set; } + public string Tld { get; set; } - public WhoisServerInfo(string server, string tld) - { - Server = server; - Tld = tld; - } + public WhoisServerInfo(string server, string tld) + { + Server = server; + Tld = tld; } } diff --git a/Source/NETworkManager.Models/Network/WiFi.cs b/Source/NETworkManager.Models/Network/WiFi.cs index 0bc04354d5..1a9392aebd 100644 --- a/Source/NETworkManager.Models/Network/WiFi.cs +++ b/Source/NETworkManager.Models/Network/WiFi.cs @@ -7,166 +7,165 @@ //https://docs.microsoft.com/en-us/uwp/api/windows.devices.wifi.wifiadapter.requestaccessasync //var access = await WiFiAdapter.RequestAccessAsync(); -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class WiFi { - public class WiFi + public static async Task> GetAdapterAsync() { - public static async Task> GetAdapterAsync() - { - List wifiAdapters = new List(); - List networkInterfaces = await NetworkInterface.GetNetworkInterfacesAsync(); + List wifiAdapters = new List(); + List networkInterfaces = await NetworkInterface.GetNetworkInterfacesAsync(); - foreach (WiFiAdapter wifiAdapter in await WiFiAdapter.FindAllAdaptersAsync()) + foreach (WiFiAdapter wifiAdapter in await WiFiAdapter.FindAllAdaptersAsync()) + { + foreach (NetworkInterfaceInfo networkInterface in networkInterfaces) { - foreach (NetworkInterfaceInfo networkInterface in networkInterfaces) + if (!wifiAdapter.NetworkAdapter.NetworkAdapterId.ToString().Equals(networkInterface.Id.TrimStart('{').TrimEnd('}'), StringComparison.OrdinalIgnoreCase)) + continue; + + wifiAdapters.Add(new WiFiAdapterInfo { - if (!wifiAdapter.NetworkAdapter.NetworkAdapterId.ToString().Equals(networkInterface.Id.TrimStart('{').TrimEnd('}'), StringComparison.OrdinalIgnoreCase)) - continue; - - wifiAdapters.Add(new WiFiAdapterInfo - { - NetworkInterfaceInfo = networkInterface, - WiFiAdapter = wifiAdapter - }); - } + NetworkInterfaceInfo = networkInterface, + WiFiAdapter = wifiAdapter + }); } - - return wifiAdapters; } - public static async Task> GetNetworksAsync(WiFiAdapter adapter) - { - List wifiNetworks = new List(); - - await adapter.ScanAsync(); + return wifiAdapters; + } - foreach (var network in adapter.NetworkReport.AvailableNetworks) - { - wifiNetworks.Add(new WiFiNetworkInfo() - { - BSSID = network.Bssid, - SSID = network.Ssid, - ChannelCenterFrequencyInKilohertz = network.ChannelCenterFrequencyInKilohertz, - SignalBars = network.SignalBars, - IsWiFiDirect = network.IsWiFiDirect, - NetworkRssiInDecibelMilliwatts = network.NetworkRssiInDecibelMilliwatts, - PhyKind = network.PhyKind, - NetworkKind = network.NetworkKind, - AuthenticationType = network.SecuritySettings.NetworkAuthenticationType, - EncryptionType = network.SecuritySettings.NetworkEncryptionType, - BeaconInterval = network.BeaconInterval, - Uptime = network.Uptime - }); - } + public static async Task> GetNetworksAsync(WiFiAdapter adapter) + { + List wifiNetworks = new List(); - return wifiNetworks; - } + await adapter.ScanAsync(); - public static int GetChannelFromChannelFrequency(int kilohertz) + foreach (var network in adapter.NetworkReport.AvailableNetworks) { - return (double)ConvertChannelFrequencyToGigahertz(kilohertz) switch + wifiNetworks.Add(new WiFiNetworkInfo() { - // 2.4 GHz - 2.412 => 1, - 2.417 => 2, - 2.422 => 3, - 2.427 => 4, - 2.432 => 5, - 2.437 => 6, - 2.442 => 7, - 2.447 => 8, - 2.452 => 9, - 2.457 => 10, - 2.462 => 11, - 2.467 => 12, - 2.472 => 13, - // 5 GHz - 5.180 => 36, - 5.200 => 40, - 5.220 => 44, - 5.240 => 48, - 5.260 => 52, - 5.280 => 56, - 5.300 => 60, - 5.320 => 64, - 5.500 => 100, - 5.520 => 104, - 5.540 => 108, - 5.560 => 112, - 5.580 => 116, - 5.600 => 120, - 5.620 => 124, - 5.640 => 128, - 5.660 => 132, - 5.680 => 136, - 5.700 => 140, - 5.720 => 144, - 5.745 => 149, - 5.765 => 153, - 5.785 => 157, - 5.805 => 161, - 5.825 => 165, - _ => -1, - }; + BSSID = network.Bssid, + SSID = network.Ssid, + ChannelCenterFrequencyInKilohertz = network.ChannelCenterFrequencyInKilohertz, + SignalBars = network.SignalBars, + IsWiFiDirect = network.IsWiFiDirect, + NetworkRssiInDecibelMilliwatts = network.NetworkRssiInDecibelMilliwatts, + PhyKind = network.PhyKind, + NetworkKind = network.NetworkKind, + AuthenticationType = network.SecuritySettings.NetworkAuthenticationType, + EncryptionType = network.SecuritySettings.NetworkEncryptionType, + BeaconInterval = network.BeaconInterval, + Uptime = network.Uptime + }); } - public static double ConvertChannelFrequencyToGigahertz(int kilohertz) - { - return Convert.ToDouble(kilohertz) / 1000 / 1000; - } + return wifiNetworks; + } - public static bool Is2dot4GHzNetwork(int kilohertz) + public static int GetChannelFromChannelFrequency(int kilohertz) + { + return (double)ConvertChannelFrequencyToGigahertz(kilohertz) switch { - var x = ConvertChannelFrequencyToGigahertz(kilohertz); + // 2.4 GHz + 2.412 => 1, + 2.417 => 2, + 2.422 => 3, + 2.427 => 4, + 2.432 => 5, + 2.437 => 6, + 2.442 => 7, + 2.447 => 8, + 2.452 => 9, + 2.457 => 10, + 2.462 => 11, + 2.467 => 12, + 2.472 => 13, + // 5 GHz + 5.180 => 36, + 5.200 => 40, + 5.220 => 44, + 5.240 => 48, + 5.260 => 52, + 5.280 => 56, + 5.300 => 60, + 5.320 => 64, + 5.500 => 100, + 5.520 => 104, + 5.540 => 108, + 5.560 => 112, + 5.580 => 116, + 5.600 => 120, + 5.620 => 124, + 5.640 => 128, + 5.660 => 132, + 5.680 => 136, + 5.700 => 140, + 5.720 => 144, + 5.745 => 149, + 5.765 => 153, + 5.785 => 157, + 5.805 => 161, + 5.825 => 165, + _ => -1, + }; + } - return x >= 2.412 && x <= 2.472; - } + public static double ConvertChannelFrequencyToGigahertz(int kilohertz) + { + return Convert.ToDouble(kilohertz) / 1000 / 1000; + } - public static bool Is5GHzNetwork(int kilohertz) - { - var x = ConvertChannelFrequencyToGigahertz(kilohertz); + public static bool Is2dot4GHzNetwork(int kilohertz) + { + var x = ConvertChannelFrequencyToGigahertz(kilohertz); - return x >= 5.180 && x <= 5.825; - } + return x >= 2.412 && x <= 2.472; + } - public static string GetHumanReadableNetworkAuthenticationType(NetworkAuthenticationType networkAuthenticationType) - { - return networkAuthenticationType switch - { - NetworkAuthenticationType.Open80211 => "Open", - NetworkAuthenticationType.Rsna => "WPA2 Enterprise", - NetworkAuthenticationType.RsnaPsk => "WPA2 PSK", - NetworkAuthenticationType.Wpa => "WPA Enterprise", - NetworkAuthenticationType.WpaNone => "WPA None", - NetworkAuthenticationType.WpaPsk => "WPA PSK", - NetworkAuthenticationType.SharedKey80211 => "WEP", - NetworkAuthenticationType.Ihv => "IHV", - NetworkAuthenticationType.Unknown => "Unkown", - NetworkAuthenticationType.None => "-/-", - _ => "-/-", - }; - } + public static bool Is5GHzNetwork(int kilohertz) + { + var x = ConvertChannelFrequencyToGigahertz(kilohertz); - public static string GetHumandReadablePhyKind(WiFiPhyKind phyKind) + return x >= 5.180 && x <= 5.825; + } + + public static string GetHumanReadableNetworkAuthenticationType(NetworkAuthenticationType networkAuthenticationType) + { + return networkAuthenticationType switch { - return phyKind switch - { - WiFiPhyKind.Dsss or WiFiPhyKind.Fhss => "802.11", - WiFiPhyKind.Ofdm => "802.11a", - WiFiPhyKind.Hrdsss => "802.11b", - WiFiPhyKind.Erp => "802.11g", - WiFiPhyKind.HT => "802.11n", - WiFiPhyKind.Dmg => "802.11ad", - WiFiPhyKind.Vht => "802.11ac", - WiFiPhyKind.HE => "802.11ax", - _ => "-/-", - }; - } + NetworkAuthenticationType.Open80211 => "Open", + NetworkAuthenticationType.Rsna => "WPA2 Enterprise", + NetworkAuthenticationType.RsnaPsk => "WPA2 PSK", + NetworkAuthenticationType.Wpa => "WPA Enterprise", + NetworkAuthenticationType.WpaNone => "WPA None", + NetworkAuthenticationType.WpaPsk => "WPA PSK", + NetworkAuthenticationType.SharedKey80211 => "WEP", + NetworkAuthenticationType.Ihv => "IHV", + NetworkAuthenticationType.Unknown => "Unkown", + NetworkAuthenticationType.None => "-/-", + _ => "-/-", + }; + } - public enum Radio + public static string GetHumandReadablePhyKind(WiFiPhyKind phyKind) + { + return phyKind switch { - One, - Two - } + WiFiPhyKind.Dsss or WiFiPhyKind.Fhss => "802.11", + WiFiPhyKind.Ofdm => "802.11a", + WiFiPhyKind.Hrdsss => "802.11b", + WiFiPhyKind.Erp => "802.11g", + WiFiPhyKind.HT => "802.11n", + WiFiPhyKind.Dmg => "802.11ad", + WiFiPhyKind.Vht => "802.11ac", + WiFiPhyKind.HE => "802.11ax", + _ => "-/-", + }; + } + + public enum Radio + { + One, + Two } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs b/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs index 0f1777fbb1..7553d83de4 100644 --- a/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs +++ b/Source/NETworkManager.Models/Network/WiFiAdapterInfo.cs @@ -1,15 +1,14 @@ using Windows.Devices.WiFi; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class WiFiAdapterInfo { - public class WiFiAdapterInfo - { - public NetworkInterfaceInfo NetworkInterfaceInfo { get; set; } - public WiFiAdapter WiFiAdapter { get; set; } + public NetworkInterfaceInfo NetworkInterfaceInfo { get; set; } + public WiFiAdapter WiFiAdapter { get; set; } - public WiFiAdapterInfo() - { - - } + public WiFiAdapterInfo() + { + } } diff --git a/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs b/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs index 6a42fa50b9..d3f8569015 100644 --- a/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs +++ b/Source/NETworkManager.Models/Network/WiFiNetworkInfo.cs @@ -4,37 +4,36 @@ using Windows.Devices.WiFi; using Windows.Networking.Connectivity; -namespace NETworkManager.Models.Network +namespace NETworkManager.Models.Network; + +public class WiFiNetworkInfo : INotifyPropertyChanged { - public class WiFiNetworkInfo : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - public string BSSID { get; set; } - public string SSID { get; set; } - public int ChannelCenterFrequencyInKilohertz { get; set; } - public byte SignalBars { get; set; } - public bool IsWiFiDirect { get; set; } - public double NetworkRssiInDecibelMilliwatts { get; set; } - public WiFiPhyKind PhyKind { get; set; } - public WiFiNetworkKind NetworkKind { get; set; } - public NetworkAuthenticationType AuthenticationType { get; set; } - public NetworkEncryptionType EncryptionType { get; set; } - public TimeSpan BeaconInterval { get; set; } - public TimeSpan Uptime { get; set; } - #endregion + #region Variables + public string BSSID { get; set; } + public string SSID { get; set; } + public int ChannelCenterFrequencyInKilohertz { get; set; } + public byte SignalBars { get; set; } + public bool IsWiFiDirect { get; set; } + public double NetworkRssiInDecibelMilliwatts { get; set; } + public WiFiPhyKind PhyKind { get; set; } + public WiFiNetworkKind NetworkKind { get; set; } + public NetworkAuthenticationType AuthenticationType { get; set; } + public NetworkEncryptionType EncryptionType { get; set; } + public TimeSpan BeaconInterval { get; set; } + public TimeSpan Uptime { get; set; } + #endregion - public WiFiNetworkInfo() - { + public WiFiNetworkInfo() + { - } } } diff --git a/Source/NETworkManager.Models/PowerShell/ExecutionPolicy.cs b/Source/NETworkManager.Models/PowerShell/ExecutionPolicy.cs index 00d46fd406..0423abec85 100644 --- a/Source/NETworkManager.Models/PowerShell/ExecutionPolicy.cs +++ b/Source/NETworkManager.Models/PowerShell/ExecutionPolicy.cs @@ -1,14 +1,13 @@ -namespace NETworkManager.Models.PowerShell +namespace NETworkManager.Models.PowerShell; + +public partial class PowerShell { - public partial class PowerShell + public enum ExecutionPolicy { - public enum ExecutionPolicy - { - Restricted, - AllSigned, - RemoteSigned, - Unrestricted, - Bypass - } + Restricted, + AllSigned, + RemoteSigned, + Unrestricted, + Bypass } } diff --git a/Source/NETworkManager.Models/PowerShell/PowerShell.cs b/Source/NETworkManager.Models/PowerShell/PowerShell.cs index 9440824ca2..587347665c 100644 --- a/Source/NETworkManager.Models/PowerShell/PowerShell.cs +++ b/Source/NETworkManager.Models/PowerShell/PowerShell.cs @@ -4,109 +4,108 @@ using System.IO; using System.Linq; -namespace NETworkManager.Models.PowerShell +namespace NETworkManager.Models.PowerShell; + +public static partial class PowerShell { - public static partial class PowerShell - { - public static readonly List GetDefaultIntallationPaths = new() - { - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "PowerShell", "7", "pwsh.exe"), - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "PowerShell", "7", "pwsh.exe"), - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"System32\WindowsPowerShell\v1.0\powershell.exe") - }; - - /// - /// Default SZ registry keys for the global PowerShell profile. - /// - private static readonly List> DefaultProfileRegkeysSZBase = new() - { - new Tuple("FaceName", "Consolas"), + public static readonly List GetDefaultIntallationPaths = new() + { + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "PowerShell", "7", "pwsh.exe"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "PowerShell", "7", "pwsh.exe"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"System32\WindowsPowerShell\v1.0\powershell.exe") + }; + + /// + /// Default SZ registry keys for the global PowerShell profile. + /// + private static readonly List> DefaultProfileRegkeysSZBase = new() + { + new Tuple("FaceName", "Consolas"), - }; + }; - private static readonly List> DefaultProfileRegkeysDwordBase = new() - { - new Tuple("CursorType", 1), - new Tuple("FontFamiliy", 54), // 36 - new Tuple("FontSize", 1179648), // 120000 - new Tuple("FontWeight", 400) // 190 - }; + private static readonly List> DefaultProfileRegkeysDwordBase = new() + { + new Tuple("CursorType", 1), + new Tuple("FontFamiliy", 54), // 36 + new Tuple("FontSize", 1179648), // 120000 + new Tuple("FontWeight", 400) // 190 + }; - private static List> GetProfileRegkeysDwordDark() - { - return DefaultProfileRegkeysDwordBase.Concat( - new[] { - new Tuple("DefaultBackground", 2434341 ), // HEX: 252525 - new Tuple("ColorTable00", 2434341), // HEX: 252525 - new Tuple("ColorTable07", 13421772), // HEX: cccccc - }).ToList(); - } - private static List> GetProfileRegkeysDwordWhite() - { - return DefaultProfileRegkeysDwordBase.Concat( - new[] { - new Tuple("DefaultBackground", 16777215 ), // HEX: FFFFFF - new Tuple("ColorTable00", 16777215), // HEX: FFFFFF - new Tuple("ColorTable07", 2434341), // HEX: 252525 - }).ToList(); - } + private static List> GetProfileRegkeysDwordDark() + { + return DefaultProfileRegkeysDwordBase.Concat( + new[] { + new Tuple("DefaultBackground", 2434341 ), // HEX: 252525 + new Tuple("ColorTable00", 2434341), // HEX: 252525 + new Tuple("ColorTable07", 13421772), // HEX: cccccc + }).ToList(); + } + private static List> GetProfileRegkeysDwordWhite() + { + return DefaultProfileRegkeysDwordBase.Concat( + new[] { + new Tuple("DefaultBackground", 16777215 ), // HEX: FFFFFF + new Tuple("ColorTable00", 16777215), // HEX: FFFFFF + new Tuple("ColorTable07", 2434341), // HEX: 252525 + }).ToList(); + } - private static List DefaultProfileRegkeysDwordDelete = new() - { - "ScreenColors" - }; + private static List DefaultProfileRegkeysDwordDelete = new() + { + "ScreenColors" + }; - public static void WriteDefaultProfileToRegistry(string theme, string powerShellPath) - { - var registryPath = @"Console\"; + public static void WriteDefaultProfileToRegistry(string theme, string powerShellPath) + { + var registryPath = @"Console\"; - var systemRoot = Environment.ExpandEnvironmentVariables("%SystemRoot%"); + var systemRoot = Environment.ExpandEnvironmentVariables("%SystemRoot%"); - // Windows PowerShell --> HKCU:\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe - if (powerShellPath.StartsWith(systemRoot)) - registryPath += "%SystemRoot%" + powerShellPath.Substring(systemRoot.Length, powerShellPath.Length - systemRoot.Length).Replace(@"\", "_"); - // PWSH --> HKCU:\Console\C:_Program Files_PowerShell_7_pwsh.exe - else - registryPath += powerShellPath.Replace(@"\", "_"); + // Windows PowerShell --> HKCU:\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe + if (powerShellPath.StartsWith(systemRoot)) + registryPath += "%SystemRoot%" + powerShellPath.Substring(systemRoot.Length, powerShellPath.Length - systemRoot.Length).Replace(@"\", "_"); + // PWSH --> HKCU:\Console\C:_Program Files_PowerShell_7_pwsh.exe + else + registryPath += powerShellPath.Replace(@"\", "_"); - RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(registryPath, true); + RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(registryPath, true); - registryKey ??= Registry.CurrentUser.CreateSubKey(registryPath); + registryKey ??= Registry.CurrentUser.CreateSubKey(registryPath); - if (registryKey != null) - { - foreach (var item in theme == "Dark" ? GetProfileRegkeysDwordDark() : GetProfileRegkeysDwordWhite()) - registryKey.SetValue(item.Item1, item.Item2); + if (registryKey != null) + { + foreach (var item in theme == "Dark" ? GetProfileRegkeysDwordDark() : GetProfileRegkeysDwordWhite()) + registryKey.SetValue(item.Item1, item.Item2); - foreach (var item in DefaultProfileRegkeysSZBase) - registryKey.SetValue(item.Item1, item.Item2); + foreach (var item in DefaultProfileRegkeysSZBase) + registryKey.SetValue(item.Item1, item.Item2); - foreach (var item in DefaultProfileRegkeysDwordDelete) - { - registryKey.DeleteValue(item, false); - } + foreach (var item in DefaultProfileRegkeysDwordDelete) + { + registryKey.DeleteValue(item, false); } - - registryKey.Close(); } - /// - /// Build command line arguments based on a . - /// - /// Instance of . - /// Command line arguments like "-NoExit -ExecutionPolicy RemoteSigned ...". - public static string BuildCommandLine(PowerShellSessionInfo sessionInfo) - { - var command = $"-NoExit -ExecutionPolicy {sessionInfo.ExecutionPolicy} {sessionInfo.AdditionalCommandLine}"; + registryKey.Close(); + } - // Connect to remote host or execute local command if configured - if (sessionInfo.EnableRemoteConsole) - command += $" -Command \"& {{Enter-PSSession -ComputerName {sessionInfo.Host}}}\""; - else if (!string.IsNullOrEmpty(sessionInfo.Command)) - command += $" -Command \"& {{{sessionInfo.Command}}}\""; + /// + /// Build command line arguments based on a . + /// + /// Instance of . + /// Command line arguments like "-NoExit -ExecutionPolicy RemoteSigned ...". + public static string BuildCommandLine(PowerShellSessionInfo sessionInfo) + { + var command = $"-NoExit -ExecutionPolicy {sessionInfo.ExecutionPolicy} {sessionInfo.AdditionalCommandLine}"; - return command; - } + // Connect to remote host or execute local command if configured + if (sessionInfo.EnableRemoteConsole) + command += $" -Command \"& {{Enter-PSSession -ComputerName {sessionInfo.Host}}}\""; + else if (!string.IsNullOrEmpty(sessionInfo.Command)) + command += $" -Command \"& {{{sessionInfo.Command}}}\""; + + return command; } } diff --git a/Source/NETworkManager.Models/PowerShell/PowerShellSessionInfo.cs b/Source/NETworkManager.Models/PowerShell/PowerShellSessionInfo.cs index 6cca0cca21..1755b93f10 100644 --- a/Source/NETworkManager.Models/PowerShell/PowerShellSessionInfo.cs +++ b/Source/NETworkManager.Models/PowerShell/PowerShellSessionInfo.cs @@ -1,19 +1,18 @@ using static NETworkManager.Models.PowerShell.PowerShell; -namespace NETworkManager.Models.PowerShell +namespace NETworkManager.Models.PowerShell; + +public class PowerShellSessionInfo { - public class PowerShellSessionInfo - { - public string ApplicationFilePath { get; set; } - public bool EnableRemoteConsole { get; set; } - public string Host { get; set; } - public string Command { get; set; } - public string AdditionalCommandLine { get; set; } - public ExecutionPolicy ExecutionPolicy { get; set; } + public string ApplicationFilePath { get; set; } + public bool EnableRemoteConsole { get; set; } + public string Host { get; set; } + public string Command { get; set; } + public string AdditionalCommandLine { get; set; } + public ExecutionPolicy ExecutionPolicy { get; set; } - public PowerShellSessionInfo() - { + public PowerShellSessionInfo() + { - } } } diff --git a/Source/NETworkManager.Models/PuTTY/ConnectionMode.cs b/Source/NETworkManager.Models/PuTTY/ConnectionMode.cs index 78ee292545..ce1dd54b5b 100644 --- a/Source/NETworkManager.Models/PuTTY/ConnectionMode.cs +++ b/Source/NETworkManager.Models/PuTTY/ConnectionMode.cs @@ -1,33 +1,32 @@ -namespace NETworkManager.Models.PuTTY +namespace NETworkManager.Models.PuTTY; + +/// +/// Connection modes for PuTTY. +/// +public enum ConnectionMode { /// - /// Connection modes for PuTTY. + /// SSH connection. /// - public enum ConnectionMode - { - /// - /// SSH connection. - /// - SSH, + SSH, - /// - /// Telnet connection. - /// - Telnet, + /// + /// Telnet connection. + /// + Telnet, - /// - /// Serial connection. - /// - Serial, + /// + /// Serial connection. + /// + Serial, - /// - /// Rlogin connection. - /// - Rlogin, + /// + /// Rlogin connection. + /// + Rlogin, - /// - /// RAW connection. - /// - RAW - } + /// + /// RAW connection. + /// + RAW } diff --git a/Source/NETworkManager.Models/PuTTY/LogMode.cs b/Source/NETworkManager.Models/PuTTY/LogMode.cs index 2114e92048..e3eb588007 100644 --- a/Source/NETworkManager.Models/PuTTY/LogMode.cs +++ b/Source/NETworkManager.Models/PuTTY/LogMode.cs @@ -1,23 +1,22 @@ -namespace NETworkManager.Models.PuTTY +namespace NETworkManager.Models.PuTTY; + +/// +/// Logging modes for PuTTY. +/// +public enum LogMode { /// - /// Logging modes for PuTTY. + /// All session output will be logged. /// - public enum LogMode - { - /// - /// All session output will be logged. - /// - SessionLog, + SessionLog, - /// - /// SSH packages will be logged. - /// - SSHLog, + /// + /// SSH packages will be logged. + /// + SSHLog, - /// - /// SSH packages and raw data will be logged. - /// - SSHRawLog - } + /// + /// SSH packages and raw data will be logged. + /// + SSHRawLog } diff --git a/Source/NETworkManager.Models/PuTTY/PuTTY.cs b/Source/NETworkManager.Models/PuTTY/PuTTY.cs index cbb60cce14..d78ea4b39f 100644 --- a/Source/NETworkManager.Models/PuTTY/PuTTY.cs +++ b/Source/NETworkManager.Models/PuTTY/PuTTY.cs @@ -5,207 +5,206 @@ using System.IO; using System.Linq; -namespace NETworkManager.Models.PuTTY +namespace NETworkManager.Models.PuTTY; + +/// +/// Class control PuTTY. +/// +public partial class PuTTY { /// - /// Class control PuTTY. + /// Name of the PuTTY folder. + /// + private static string _puttyFolder => "PuTTY"; + + /// + /// Name of the PuTTY executable. /// - public partial class PuTTY + private static string _puttyFile => "putty.exe"; + + /// + /// Default PuTTY installation paths. + /// + public static readonly List GetDefaultInstallationPaths = new() { - /// - /// Name of the PuTTY folder. - /// - private static string _puttyFolder => "PuTTY"; - - /// - /// Name of the PuTTY executable. - /// - private static string _puttyFile => "putty.exe"; - - /// - /// Default PuTTY installation paths. - /// - public static readonly List GetDefaultInstallationPaths = new() - { - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), _puttyFolder, _puttyFile), - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), _puttyFolder, _puttyFile) - }; - - /// - /// Default SZ registry keys for PuTTY profile NETworkManager. - /// - private static readonly List> DefaultProfileRegkeysSZBase = new() - { - new Tuple("Colour1", "255,255,255"), - new Tuple("Colour3", "85,85,85"), - new Tuple("Colour4", "0,0,0"), - new Tuple("Colour5", "0,255,0"), - new Tuple("Colour6", "0,0,0"), - new Tuple("Colour7", "85,85,85"), - new Tuple("Colour8", "187,0,0"), - new Tuple("Colour9", "255,85,85"), - new Tuple("Colour10", "0,187,0"), - new Tuple("Colour11", "85,255,85"), - new Tuple("Colour12", "187,187,0"), - new Tuple("Colour13", "255,255,85"), - new Tuple("Colour14", "0,0,187"), - new Tuple("Colour15", "85,85,255"), - new Tuple("Colour16", "187,0,187"), - new Tuple("Colour17", "255,85,255"), - new Tuple("Colour18", "0,187,187"), - new Tuple("Colour19", "85,255,255"), - new Tuple("Colour20", "187,187,187"), - new Tuple("Colour21", "255,255,255"), - new Tuple("LineCodePage", "UTF-8"), - new Tuple("Font", "Consolas") - }; - - /// - /// SZ registry keys for PuTTY profile NETworkManager if app theme is dark. - /// - /// List with SZ registry keys. - private static List> GetProfileRegkeysSZDark() - { - return DefaultProfileRegkeysSZBase.Concat( - new[] { - // new Tuple("Colour0", "255,255,255"), - new Tuple("Colour0", "187,187,187"), // Foreground - new Tuple("Colour2", "37,37,37") // Background - }).ToList(); - } + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), _puttyFolder, _puttyFile), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), _puttyFolder, _puttyFile) + }; + + /// + /// Default SZ registry keys for PuTTY profile NETworkManager. + /// + private static readonly List> DefaultProfileRegkeysSZBase = new() + { + new Tuple("Colour1", "255,255,255"), + new Tuple("Colour3", "85,85,85"), + new Tuple("Colour4", "0,0,0"), + new Tuple("Colour5", "0,255,0"), + new Tuple("Colour6", "0,0,0"), + new Tuple("Colour7", "85,85,85"), + new Tuple("Colour8", "187,0,0"), + new Tuple("Colour9", "255,85,85"), + new Tuple("Colour10", "0,187,0"), + new Tuple("Colour11", "85,255,85"), + new Tuple("Colour12", "187,187,0"), + new Tuple("Colour13", "255,255,85"), + new Tuple("Colour14", "0,0,187"), + new Tuple("Colour15", "85,85,255"), + new Tuple("Colour16", "187,0,187"), + new Tuple("Colour17", "255,85,255"), + new Tuple("Colour18", "0,187,187"), + new Tuple("Colour19", "85,255,255"), + new Tuple("Colour20", "187,187,187"), + new Tuple("Colour21", "255,255,255"), + new Tuple("LineCodePage", "UTF-8"), + new Tuple("Font", "Consolas") + }; - /// - /// SZ registry keys for PuTTY profile NETworkManager if app theme is white. - /// - /// List with DWORD registry keys. - private static List> GetProfileRegkeysSZWhite() + /// + /// SZ registry keys for PuTTY profile NETworkManager if app theme is dark. + /// + /// List with SZ registry keys. + private static List> GetProfileRegkeysSZDark() + { + return DefaultProfileRegkeysSZBase.Concat( + new[] { + // new Tuple("Colour0", "255,255,255"), + new Tuple("Colour0", "187,187,187"), // Foreground + new Tuple("Colour2", "37,37,37") // Background + }).ToList(); + } + + /// + /// SZ registry keys for PuTTY profile NETworkManager if app theme is white. + /// + /// List with DWORD registry keys. + private static List> GetProfileRegkeysSZWhite() + { + return DefaultProfileRegkeysSZBase.Concat( + new[] { + // new Tuple("Colour0", "68,68,68"), + new Tuple("Colour0", "0,0,0"), // Foreground + new Tuple("Colour2", "255,255,255") // Background + }).ToList(); + } + + /// + /// Default DWORD registry keys for PuTTY profile NETworkManager. + /// + private static readonly List> DefaultProfileRegkeysDwordBase = new() + { + new Tuple("CurType", 2), + new Tuple("FontHeight", 12), + new Tuple("BlinkCur", 1), + new Tuple("ScrollBar", 0) + }; + + /// + /// Write the default PuTTY profile NETworkManager to the registry. + /// HKCU\Software\SimonTatham\PuTTY\Sessions\NETworkManager + /// + /// Current application theme to adjust the PuTTY colors + public static void WriteDefaultProfileToRegistry(string theme) + { + string profilePath = @"Software\SimonTatham\PuTTY\Sessions\NETworkManager"; + + RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(profilePath, true); + + registryKey ??= Registry.CurrentUser.CreateSubKey(profilePath); + + if (registryKey != null) { - return DefaultProfileRegkeysSZBase.Concat( - new[] { - // new Tuple("Colour0", "68,68,68"), - new Tuple("Colour0", "0,0,0"), // Foreground - new Tuple("Colour2", "255,255,255") // Background - }).ToList(); + foreach (var item in theme == "Dark" ? GetProfileRegkeysSZDark() : GetProfileRegkeysSZWhite()) + registryKey.SetValue(item.Item1, item.Item2); + + foreach (var item in DefaultProfileRegkeysDwordBase) + registryKey.SetValue(item.Item1, item.Item2); } - /// - /// Default DWORD registry keys for PuTTY profile NETworkManager. - /// - private static readonly List> DefaultProfileRegkeysDwordBase = new() - { - new Tuple("CurType", 2), - new Tuple("FontHeight", 12), - new Tuple("BlinkCur", 1), - new Tuple("ScrollBar", 0) - }; - - /// - /// Write the default PuTTY profile NETworkManager to the registry. - /// HKCU\Software\SimonTatham\PuTTY\Sessions\NETworkManager - /// - /// Current application theme to adjust the PuTTY colors - public static void WriteDefaultProfileToRegistry(string theme) + registryKey.Close(); + } + + /// + /// Build command line arguments based on a . + /// + /// Instance of . + /// Command line arguments like "-ssh -l root -i C:\data\key.ppk". + public static string BuildCommandLine(PuTTYSessionInfo sessionInfo) + { + var command = string.Empty; + + // Protocol + switch (sessionInfo.Mode) { - string profilePath = @"Software\SimonTatham\PuTTY\Sessions\NETworkManager"; + case ConnectionMode.SSH: + command += "-ssh"; + break; + case ConnectionMode.Telnet: + command += "-telnet"; + break; + case ConnectionMode.Serial: + command += "-serial"; + break; + case ConnectionMode.Rlogin: + command += "-rlogin"; + break; + case ConnectionMode.RAW: + command += "-raw"; + break; + } - RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(profilePath, true); + // Username + if (!string.IsNullOrEmpty(sessionInfo.Username)) + command += $" -l {sessionInfo.Username}"; - registryKey ??= Registry.CurrentUser.CreateSubKey(profilePath); + // Private key + if (!string.IsNullOrEmpty(sessionInfo.PrivateKey)) + command += $" -i \"{sessionInfo.PrivateKey}\""; - if (registryKey != null) - { - foreach (var item in theme == "Dark" ? GetProfileRegkeysSZDark() : GetProfileRegkeysSZWhite()) - registryKey.SetValue(item.Item1, item.Item2); + // Profile + if (!string.IsNullOrEmpty(sessionInfo.Profile)) + command += $" -load \"{sessionInfo.Profile}\""; - foreach (var item in DefaultProfileRegkeysDwordBase) - registryKey.SetValue(item.Item1, item.Item2); - } + // Hostkey(s) + if (!string.IsNullOrEmpty(sessionInfo.Hostkey)) + { + var hostkeys = StringHelper.RemoveWhitespace(sessionInfo.Hostkey).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - registryKey.Close(); + foreach (var hostkey in hostkeys) + command += $" -hostkey \"{hostkey}\""; } - /// - /// Build command line arguments based on a . - /// - /// Instance of . - /// Command line arguments like "-ssh -l root -i C:\data\key.ppk". - public static string BuildCommandLine(PuTTYSessionInfo sessionInfo) + // Log + if (sessionInfo.EnableLog) { - var command = string.Empty; - - // Protocol - switch (sessionInfo.Mode) + switch (sessionInfo.LogMode) { - case ConnectionMode.SSH: - command += "-ssh"; - break; - case ConnectionMode.Telnet: - command += "-telnet"; - break; - case ConnectionMode.Serial: - command += "-serial"; + case LogMode.SessionLog: + command += $" -sessionlog"; break; - case ConnectionMode.Rlogin: - command += "-rlogin"; + case LogMode.SSHLog: + command += $" -sshlog"; break; - case ConnectionMode.RAW: - command += "-raw"; + case LogMode.SSHRawLog: + command += $" -sshrawlog"; break; } - // Username - if (!string.IsNullOrEmpty(sessionInfo.Username)) - command += $" -l {sessionInfo.Username}"; - - // Private key - if (!string.IsNullOrEmpty(sessionInfo.PrivateKey)) - command += $" -i \"{sessionInfo.PrivateKey}\""; - - // Profile - if (!string.IsNullOrEmpty(sessionInfo.Profile)) - command += $" -load \"{sessionInfo.Profile}\""; - - // Hostkey(s) - if (!string.IsNullOrEmpty(sessionInfo.Hostkey)) - { - var hostkeys = StringHelper.RemoveWhitespace(sessionInfo.Hostkey).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - - foreach (var hostkey in hostkeys) - command += $" -hostkey \"{hostkey}\""; - } - - // Log - if (sessionInfo.EnableLog) - { - switch (sessionInfo.LogMode) - { - case LogMode.SessionLog: - command += $" -sessionlog"; - break; - case LogMode.SSHLog: - command += $" -sshlog"; - break; - case LogMode.SSHRawLog: - command += $" -sshrawlog"; - break; - } - - command += $" {'"'}{Environment.ExpandEnvironmentVariables(Path.Combine(sessionInfo.LogPath, sessionInfo.LogFileName))}{'"'}"; - } + command += $" {'"'}{Environment.ExpandEnvironmentVariables(Path.Combine(sessionInfo.LogPath, sessionInfo.LogFileName))}{'"'}"; + } - // Additional commands - if (!string.IsNullOrEmpty(sessionInfo.AdditionalCommandLine)) - command += $" {sessionInfo.AdditionalCommandLine}"; + // Additional commands + if (!string.IsNullOrEmpty(sessionInfo.AdditionalCommandLine)) + command += $" {sessionInfo.AdditionalCommandLine}"; - // SerialLine, Baud - if (sessionInfo.Mode == ConnectionMode.Serial) - command += $" {sessionInfo.HostOrSerialLine} -sercfg {sessionInfo.PortOrBaud}"; + // SerialLine, Baud + if (sessionInfo.Mode == ConnectionMode.Serial) + command += $" {sessionInfo.HostOrSerialLine} -sercfg {sessionInfo.PortOrBaud}"; - // Port, Host - if (sessionInfo.Mode != ConnectionMode.Serial) - command += $" -P {sessionInfo.PortOrBaud} {sessionInfo.HostOrSerialLine}"; + // Port, Host + if (sessionInfo.Mode != ConnectionMode.Serial) + command += $" -P {sessionInfo.PortOrBaud} {sessionInfo.HostOrSerialLine}"; - return command; - } + return command; } } diff --git a/Source/NETworkManager.Models/PuTTY/PuTTYSessionInfo.cs b/Source/NETworkManager.Models/PuTTY/PuTTYSessionInfo.cs index 3be7c3772f..ee77249140 100644 --- a/Source/NETworkManager.Models/PuTTY/PuTTYSessionInfo.cs +++ b/Source/NETworkManager.Models/PuTTY/PuTTYSessionInfo.cs @@ -1,81 +1,80 @@ -namespace NETworkManager.Models.PuTTY +namespace NETworkManager.Models.PuTTY; + +/// +/// Stores informations about a PuTTY session. +/// +public class PuTTYSessionInfo { /// - /// Stores informations about a PuTTY session. + /// Full path to the PuTTY.exe on the filesystem. /// - public class PuTTYSessionInfo - { - /// - /// Full path to the PuTTY.exe on the filesystem. - /// - public string ApplicationFilePath { get; set; } + public string ApplicationFilePath { get; set; } - /// - /// Mode (SSH, Telnet, etc.), which is used to establish the connection. - /// - public ConnectionMode Mode { get; set; } + /// + /// Mode (SSH, Telnet, etc.), which is used to establish the connection. + /// + public ConnectionMode Mode { get; set; } - /// - /// Hostname or SerialLine. Depends on the . - /// - public string HostOrSerialLine { get; set; } + /// + /// Hostname or SerialLine. Depends on the . + /// + public string HostOrSerialLine { get; set; } - /// - /// Port or Baud. Depends on the . - /// - public int PortOrBaud { get; set; } + /// + /// Port or Baud. Depends on the . + /// + public int PortOrBaud { get; set; } - /// - /// Username for login. - /// - public string Username { get; set; } + /// + /// Username for login. + /// + public string Username { get; set; } - /// - /// Path to the private key. - /// - public string PrivateKey { get; set; } + /// + /// Path to the private key. + /// + public string PrivateKey { get; set; } - /// - /// PuTTY profile to use. - /// - public string Profile { get; set; } + /// + /// PuTTY profile to use. + /// + public string Profile { get; set; } - /// - /// PuTTY host key. Multiple keys are separated by a comma. - /// - public string Hostkey { get; set; } + /// + /// PuTTY host key. Multiple keys are separated by a comma. + /// + public string Hostkey { get; set; } - /// - /// Enables session log. - /// - public bool EnableLog { get; set; } + /// + /// Enables session log. + /// + public bool EnableLog { get; set; } - /// - /// PuTTY log mode. - /// - public LogMode LogMode { get; set; } + /// + /// PuTTY log mode. + /// + public LogMode LogMode { get; set; } - /// - /// Path to the PuTTY log files like "C:\temp". - /// - public string LogPath { get; set; } + /// + /// Path to the PuTTY log files like "C:\temp". + /// + public string LogPath { get; set; } - /// - /// Filename of the PuTTY log like "PuTTY.log". - /// - public string LogFileName { get; set; } + /// + /// Filename of the PuTTY log like "PuTTY.log". + /// + public string LogFileName { get; set; } - /// - /// Additional command line argument. Everything putty can handle. - /// - public string AdditionalCommandLine { get; set; } + /// + /// Additional command line argument. Everything putty can handle. + /// + public string AdditionalCommandLine { get; set; } - /// - /// Create an instance of . - /// - public PuTTYSessionInfo() - { + /// + /// Create an instance of . + /// + public PuTTYSessionInfo() + { - } - } + } } diff --git a/Source/NETworkManager.Models/RemoteDesktop/AudioCaptureRedirectionMode.cs b/Source/NETworkManager.Models/RemoteDesktop/AudioCaptureRedirectionMode.cs index ccd7863caf..fa78bcec5c 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/AudioCaptureRedirectionMode.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/AudioCaptureRedirectionMode.cs @@ -1,19 +1,18 @@ -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +/// +/// Represents whether the default audio input is redirected from the client to the remote session. +/// See also: https://docs.microsoft.com/en-us/windows/win32/termserv/imsrdpclientadvancedsettings7-audiocaptureredirectionmode +/// +public enum AudioCaptureRedirectionMode { /// - /// Represents whether the default audio input is redirected from the client to the remote session. - /// See also: https://docs.microsoft.com/en-us/windows/win32/termserv/imsrdpclientadvancedsettings7-audiocaptureredirectionmode + /// Redirect the default audio input device to the remote session. /// - public enum AudioCaptureRedirectionMode - { - /// - /// Redirect the default audio input device to the remote session. - /// - RecordFromThisComputer, + RecordFromThisComputer, - /// - /// Don't redirect the default audio input device to the remote session. - /// - DoNotRecord - } + /// + /// Don't redirect the default audio input device to the remote session. + /// + DoNotRecord } diff --git a/Source/NETworkManager.Models/RemoteDesktop/AudioRedirectionMode.cs b/Source/NETworkManager.Models/RemoteDesktop/AudioRedirectionMode.cs index 4727f0610e..c9a07ef5fa 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/AudioRedirectionMode.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/AudioRedirectionMode.cs @@ -1,24 +1,23 @@ -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +/// +/// Represents the audio redirection mode and different audio redirection options. +/// See also: https://docs.microsoft.com/en-us/windows/win32/termserv/imsrdpclientadvancedsettings5-audioredirectionmode +/// +public enum AudioRedirectionMode { /// - /// Represents the audio redirection mode and different audio redirection options. - /// See also: https://docs.microsoft.com/en-us/windows/win32/termserv/imsrdpclientadvancedsettings5-audioredirectionmode + /// Audio redirection is enabled and the option for redirection is "Bring to this computer". This is the default mode. /// - public enum AudioRedirectionMode - { - /// - /// Audio redirection is enabled and the option for redirection is "Bring to this computer". This is the default mode. - /// - PlayOnThisComputer, + PlayOnThisComputer, - /// - /// Audio redirection is enabled and the option is "Leave at remote computer" - /// - PlayOnRemoteComputer, + /// + /// Audio redirection is enabled and the option is "Leave at remote computer" + /// + PlayOnRemoteComputer, - /// - /// Audio redirection is enabled and the mode is "Do not play". - /// - DoNotPlay - } + /// + /// Audio redirection is enabled and the mode is "Do not play". + /// + DoNotPlay } diff --git a/Source/NETworkManager.Models/RemoteDesktop/KeyboardHookMode.cs b/Source/NETworkManager.Models/RemoteDesktop/KeyboardHookMode.cs index 89ababf483..8ff8041750 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/KeyboardHookMode.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/KeyboardHookMode.cs @@ -1,22 +1,21 @@ -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +/// +/// Represents the keyboard redirection settings, which specify how and when to apply Windows keyboard shortcut (for example, ALT+TAB). +/// See also: https://docs.microsoft.com/en-us/windows/win32/termserv/imsrdpclientsecuredsettings-keyboardhookmode +/// +public enum KeyboardHookMode { /// - /// Represents the keyboard redirection settings, which specify how and when to apply Windows keyboard shortcut (for example, ALT+TAB). - /// See also: https://docs.microsoft.com/en-us/windows/win32/termserv/imsrdpclientsecuredsettings-keyboardhookmode + /// Apply key combinations only locally at the client computer. /// - public enum KeyboardHookMode - { - /// - /// Apply key combinations only locally at the client computer. - /// - OnThisComputer, + OnThisComputer, - /// - /// Apply key combinations at the remote server. - /// - OnTheRemoteComputer, + /// + /// Apply key combinations at the remote server. + /// + OnTheRemoteComputer, - // Apply key combinations to the remote server only when the client is running in full-screen mode. - //OnlyWhenUsingTheFullScreen - } + // Apply key combinations to the remote server only when the client is running in full-screen mode. + //OnlyWhenUsingTheFullScreen } diff --git a/Source/NETworkManager.Models/RemoteDesktop/Keystroke.cs b/Source/NETworkManager.Models/RemoteDesktop/Keystroke.cs index 5b880fc040..7b79487091 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/Keystroke.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/Keystroke.cs @@ -1,13 +1,12 @@ -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +/// +/// Represents keystrokes which can be send into the remote session. +/// +public enum Keystroke { /// - /// Represents keystrokes which can be send into the remote session. + /// Ctrl + Alt + Del keystroke. /// - public enum Keystroke - { - /// - /// Ctrl + Alt + Del keystroke. - /// - CtrlAltDel - } + CtrlAltDel } diff --git a/Source/NETworkManager.Models/RemoteDesktop/NetworkConnectionType.cs b/Source/NETworkManager.Models/RemoteDesktop/NetworkConnectionType.cs index 6e8e93cf6b..c9a68ad9c0 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/NetworkConnectionType.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/NetworkConnectionType.cs @@ -1,45 +1,44 @@ -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +/// +/// Represents the network connection used between the client and server. +/// The network connection type information passed on to the server helps the server tune several parameters based on the network connection type. +/// See also: https://docs.microsoft.com/en-us/windows/desktop/termserv/imsrdpclientadvancedsettings7-networkconnectiontype +/// +public enum NetworkConnectionType { /// - /// Represents the network connection used between the client and server. - /// The network connection type information passed on to the server helps the server tune several parameters based on the network connection type. - /// See also: https://docs.microsoft.com/en-us/windows/desktop/termserv/imsrdpclientadvancedsettings7-networkconnectiontype + /// Detect the network connection type automatically. /// - public enum NetworkConnectionType - { - /// - /// Detect the network connection type automatically. - /// - DetectAutomatically, + DetectAutomatically, - /// - /// Modem (56 Kbps). - /// - Modem, + /// + /// Modem (56 Kbps). + /// + Modem, - /// - /// Low-speed broadband (256 Kbps to 2 Mbps). - /// - BroadbandLow, + /// + /// Low-speed broadband (256 Kbps to 2 Mbps). + /// + BroadbandLow, - /// - /// Satellite (2 Mbps to 16 Mbps, with high latency). - /// - Satellite, + /// + /// Satellite (2 Mbps to 16 Mbps, with high latency). + /// + Satellite, - /// - /// High-speed broadband (2 Mbps to 10 Mbps). - /// - BroadbandHigh, + /// + /// High-speed broadband (2 Mbps to 10 Mbps). + /// + BroadbandHigh, - /// - /// Wide area network (WAN) (10 Mbps or higher, with high latency). - /// - WAN, + /// + /// Wide area network (WAN) (10 Mbps or higher, with high latency). + /// + WAN, - /// - /// Local area network (LAN) (10 Mbps or higher). - /// - LAN - } + /// + /// Local area network (LAN) (10 Mbps or higher). + /// + LAN } diff --git a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktop.cs b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktop.cs index b2158f0127..55e14aa0a8 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktop.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktop.cs @@ -1,46 +1,45 @@ using System.Collections.Generic; -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +public static class RemoteDesktop { - public static class RemoteDesktop + public static List ScreenResolutions => new List { - public static List ScreenResolutions => new List - { - "640x480", - "800x600", - "1024x768", - "1280x720", - "1280x768", - "1280x800", - "1280x1024", - "1366x768", - "1440x900", - "1400x1050", - "1680x1050", - "1920x1080" - }; + "640x480", + "800x600", + "1024x768", + "1280x720", + "1280x768", + "1280x800", + "1280x1024", + "1366x768", + "1440x900", + "1400x1050", + "1680x1050", + "1920x1080" + }; - public static List ColorDepths => new List - { - 15, - 16, - 24, - 32 - }; - - public static RemoteDesktopKeystrokeInfo GetKeystroke(Keystroke keystroke) - { - RemoteDesktopKeystrokeInfo info = new RemoteDesktopKeystrokeInfo(); + public static List ColorDepths => new List + { + 15, + 16, + 24, + 32 + }; - switch (keystroke) - { - case Keystroke.CtrlAltDel: - info.ArrayKeyUp = new bool[] { false, false, false, true, true, true, }; - info.KeyData = new int[] { 0x1d, 0x38, 0x53, 0x53, 0x38, 0x1d }; - break; - } + public static RemoteDesktopKeystrokeInfo GetKeystroke(Keystroke keystroke) + { + RemoteDesktopKeystrokeInfo info = new RemoteDesktopKeystrokeInfo(); - return info; + switch (keystroke) + { + case Keystroke.CtrlAltDel: + info.ArrayKeyUp = new bool[] { false, false, false, true, true, true, }; + info.KeyData = new int[] { 0x1d, 0x38, 0x53, 0x53, 0x38, 0x1d }; + break; } + + return info; } } diff --git a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopKeystrokeInfo.cs b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopKeystrokeInfo.cs index 04b9f95bf7..97c2d7eb38 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopKeystrokeInfo.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopKeystrokeInfo.cs @@ -1,19 +1,18 @@ -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +public class RemoteDesktopKeystrokeInfo { - public class RemoteDesktopKeystrokeInfo - { - public bool[] ArrayKeyUp; - public int[] KeyData; + public bool[] ArrayKeyUp; + public int[] KeyData; - public RemoteDesktopKeystrokeInfo() - { + public RemoteDesktopKeystrokeInfo() + { - } + } - public RemoteDesktopKeystrokeInfo(bool[] arrayKeyUp, int[] keyData) - { - ArrayKeyUp = arrayKeyUp; - KeyData = keyData; - } + public RemoteDesktopKeystrokeInfo(bool[] arrayKeyUp, int[] keyData) + { + ArrayKeyUp = arrayKeyUp; + KeyData = keyData; } } diff --git a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopPerformanceConstants.cs b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopPerformanceConstants.cs index 18b2e300c2..113486c870 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopPerformanceConstants.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopPerformanceConstants.cs @@ -1,36 +1,35 @@ -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +public static class RemoteDesktopPerformanceConstants { - public static class RemoteDesktopPerformanceConstants - { - // No features are disabled. - public const int TS_PERF_DISABLE_NOTHING = 0x00000000; + // No features are disabled. + public const int TS_PERF_DISABLE_NOTHING = 0x00000000; - // Wallpaper on the desktop is not displayed. - public const int TS_PERF_DISABLE_WALLPAPER = 0x00000001; + // Wallpaper on the desktop is not displayed. + public const int TS_PERF_DISABLE_WALLPAPER = 0x00000001; - // Full-window drag is disabled; only the window outline is displayed when the window is moved. - public const int TS_PERF_DISABLE_FULLWINDOWDRAG = 0x00000002; + // Full-window drag is disabled; only the window outline is displayed when the window is moved. + public const int TS_PERF_DISABLE_FULLWINDOWDRAG = 0x00000002; - // Menu animations are disabled. - public const int TS_PERF_DISABLE_MENUANIMATIONS = 0x00000004; + // Menu animations are disabled. + public const int TS_PERF_DISABLE_MENUANIMATIONS = 0x00000004; - // Themes are disabled. - public const int TS_PERF_DISABLE_THEMING = 0x00000008; + // Themes are disabled. + public const int TS_PERF_DISABLE_THEMING = 0x00000008; - // Enable enhanced graphics. - public const int TS_PERF_ENABLE_ENHANCED_GRAPHICS = 0x00000010; + // Enable enhanced graphics. + public const int TS_PERF_ENABLE_ENHANCED_GRAPHICS = 0x00000010; - // No shadow is displayed for the cursor. - public const int TS_PERF_DISABLE_CURSOR_SHADOW = 0x00000020; + // No shadow is displayed for the cursor. + public const int TS_PERF_DISABLE_CURSOR_SHADOW = 0x00000020; - // Cursor blinking is disabled. - public const int TS_PERF_DISABLE_CURSORSETTINGS = 0x00000040; + // Cursor blinking is disabled. + public const int TS_PERF_DISABLE_CURSORSETTINGS = 0x00000040; - // Font smoothing - public const int TS_PERF_ENABLE_FONT_SMOOTHING = 0x00000080; + // Font smoothing + public const int TS_PERF_ENABLE_FONT_SMOOTHING = 0x00000080; - // Desktop composition - public const int TS_PERF_ENABLE_DESKTOP_COMPOSITION = 0x00000100; + // Desktop composition + public const int TS_PERF_ENABLE_DESKTOP_COMPOSITION = 0x00000100; - } } diff --git a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopSessionInfo.cs b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopSessionInfo.cs index f8eb194f9f..c4b2d8c158 100644 --- a/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopSessionInfo.cs +++ b/Source/NETworkManager.Models/RemoteDesktop/RemoteDesktopSessionInfo.cs @@ -1,43 +1,42 @@ using System.Security; -namespace NETworkManager.Models.RemoteDesktop +namespace NETworkManager.Models.RemoteDesktop; + +public class RemoteDesktopSessionInfo { - public class RemoteDesktopSessionInfo - { - public string Hostname { get; set; } - public int Port { get; set; } - public bool CustomCredentials { get; set; } - public string Username { get; set; } - public SecureString Password { get; set; } - public bool AdjustScreenAutomatically { get; set; } - public bool UseCurrentViewSize { get; set; } - public int DesktopWidth { get; set; } - public int DesktopHeight { get; set; } - public int ColorDepth { get; set; } - public bool EnableCredSspSupport { get; set; } - public uint AuthenticationLevel { get; set; } - public AudioRedirectionMode AudioRedirectionMode { get; set; } - public AudioCaptureRedirectionMode AudioCaptureRedirectionMode { get; set; } - public KeyboardHookMode KeyboardHookMode { get; set; } - public bool RedirectClipboard { get; set; } - public bool RedirectDevices { get; set; } - public bool RedirectDrives { get; set; } - public bool RedirectPorts { get; set; } - public bool RedirectSmartCards { get; set; } - public bool RedirectPrinters { get; set; } - public bool PersistentBitmapCaching { get; set; } - public bool ReconnectIfTheConnectionIsDropped { get; set; } - public NetworkConnectionType NetworkConnectionType { get; set; } - public bool DesktopBackground { get; set; } - public bool FontSmoothing { get; set; } - public bool DesktopComposition { get; set; } - public bool ShowWindowContentsWhileDragging { get; set; } - public bool MenuAndWindowAnimation { get; set; } - public bool VisualStyles { get; set; } + public string Hostname { get; set; } + public int Port { get; set; } + public bool CustomCredentials { get; set; } + public string Username { get; set; } + public SecureString Password { get; set; } + public bool AdjustScreenAutomatically { get; set; } + public bool UseCurrentViewSize { get; set; } + public int DesktopWidth { get; set; } + public int DesktopHeight { get; set; } + public int ColorDepth { get; set; } + public bool EnableCredSspSupport { get; set; } + public uint AuthenticationLevel { get; set; } + public AudioRedirectionMode AudioRedirectionMode { get; set; } + public AudioCaptureRedirectionMode AudioCaptureRedirectionMode { get; set; } + public KeyboardHookMode KeyboardHookMode { get; set; } + public bool RedirectClipboard { get; set; } + public bool RedirectDevices { get; set; } + public bool RedirectDrives { get; set; } + public bool RedirectPorts { get; set; } + public bool RedirectSmartCards { get; set; } + public bool RedirectPrinters { get; set; } + public bool PersistentBitmapCaching { get; set; } + public bool ReconnectIfTheConnectionIsDropped { get; set; } + public NetworkConnectionType NetworkConnectionType { get; set; } + public bool DesktopBackground { get; set; } + public bool FontSmoothing { get; set; } + public bool DesktopComposition { get; set; } + public bool ShowWindowContentsWhileDragging { get; set; } + public bool MenuAndWindowAnimation { get; set; } + public bool VisualStyles { get; set; } - public RemoteDesktopSessionInfo() - { + public RemoteDesktopSessionInfo() + { - } } } diff --git a/Source/NETworkManager.Models/TigerVNC/TigerVNC.cs b/Source/NETworkManager.Models/TigerVNC/TigerVNC.cs index 80bdca69f9..fadf93f116 100644 --- a/Source/NETworkManager.Models/TigerVNC/TigerVNC.cs +++ b/Source/NETworkManager.Models/TigerVNC/TigerVNC.cs @@ -1,10 +1,9 @@ -namespace NETworkManager.Models.TigerVNC +namespace NETworkManager.Models.TigerVNC; + +public static class TigerVNC { - public static class TigerVNC + public static string BuildCommandLine(TigerVNCSessionInfo sessionInfo) { - public static string BuildCommandLine(TigerVNCSessionInfo sessionInfo) - { - return $"{sessionInfo.Host}::{sessionInfo.Port}"; - } + return $"{sessionInfo.Host}::{sessionInfo.Port}"; } } diff --git a/Source/NETworkManager.Models/TigerVNC/TigerVNCSessionInfo.cs b/Source/NETworkManager.Models/TigerVNC/TigerVNCSessionInfo.cs index 88a02c5f41..cf31f89cea 100644 --- a/Source/NETworkManager.Models/TigerVNC/TigerVNCSessionInfo.cs +++ b/Source/NETworkManager.Models/TigerVNC/TigerVNCSessionInfo.cs @@ -1,14 +1,13 @@ -namespace NETworkManager.Models.TigerVNC +namespace NETworkManager.Models.TigerVNC; + +public class TigerVNCSessionInfo { - public class TigerVNCSessionInfo + public string ApplicationFilePath { get; set; } + public string Host { get; set; } + public int Port { get; set; } + + public TigerVNCSessionInfo() { - public string ApplicationFilePath { get; set; } - public string Host { get; set; } - public int Port { get; set; } - - public TigerVNCSessionInfo() - { - } } } diff --git a/Source/NETworkManager.Models/WebConsole/WebConsoleSessionInfo.cs b/Source/NETworkManager.Models/WebConsole/WebConsoleSessionInfo.cs index 6ca356863d..b606c812a3 100644 --- a/Source/NETworkManager.Models/WebConsole/WebConsoleSessionInfo.cs +++ b/Source/NETworkManager.Models/WebConsole/WebConsoleSessionInfo.cs @@ -1,12 +1,11 @@ -namespace NETworkManager.Models.WebConsole +namespace NETworkManager.Models.WebConsole; + +public class WebConsoleSessionInfo { - public class WebConsoleSessionInfo + public string Url { get; set; } + + public WebConsoleSessionInfo() { - public string Url { get; set; } - - public WebConsoleSessionInfo() - { - } } } diff --git a/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs b/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs index df175bdd4f..b6a8785175 100644 --- a/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs +++ b/Source/NETworkManager.Validators/EmptyOrAWSRegionExistsValidator.cs @@ -1,8 +1,7 @@ -using AWS; +using NETworkManager.Models.AWS; using System.Globalization; using System.Windows.Controls; -namespace NETworkManager.Validators; namespace NETworkManager.Validators; public class EmptyOrAWSRegionExistsValidator : ValidationRule From 494864d49e1b5c1d105c01fded9ce7c1f38492ef Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 20:54:18 +0100 Subject: [PATCH 10/11] Chore: Use .NET 7 syntax --- Source/NETworkManager/App.xaml.cs | 469 ++- .../NETworkManager/CommandLineWindow.xaml.cs | 29 +- .../Controls/AWSSessionManagerControl.xaml.cs | 343 +- .../Controls/DragablzInterTabClient.cs | 33 +- .../Controls/DragablzTabHostWindow.xaml.cs | 511 ++- .../Controls/DragablzTabItem.cs | 49 +- .../LvlChartsBandwidthTooltip.xaml.cs | 49 +- .../Controls/LvlChartsPingTimeTooltip.xaml.cs | 49 +- .../LvlChartsWiFiChannelTooltip.xaml.cs | 49 +- .../Controls/PowerShellControl.xaml.cs | 351 +- .../Controls/PuTTYControl.xaml.cs | 373 +- .../Controls/RemoteDesktopControl.xaml.cs | 735 ++-- .../Controls/TightVNCControl.xaml.cs | 345 +- .../Controls/WebConsoleControl.xaml.cs | 303 +- Source/NETworkManager/MainWindow.xaml.cs | 2635 ++++++------ Source/NETworkManager/StatusWindow.xaml.cs | 151 +- .../ViewModels/ARPTableAddEntryViewModel.cs | 65 +- .../ViewModels/ARPTableViewModel.cs | 653 ++- .../ViewModels/AWSProfileViewModel.cs | 163 +- .../AWSSessionManagerConnectViewModel.cs | 103 +- .../AWSSessionManagerHostViewModel.cs | 1383 ++++--- .../AWSSessionManagerSettingsViewModel.cs | 481 ++- .../ViewModels/AboutViewModel.cs | 357 +- .../BitCalculatorSettingsViewModel.cs | 63 +- .../ViewModels/BitCalculatorViewModel.cs | 275 +- .../ViewModels/CommandLineViewModel.cs | 185 +- .../ViewModels/ConfirmDeleteViewModel.cs | 43 +- .../ViewModels/ConnectionsViewModel.cs | 547 ++- .../CredentialsChangePasswordViewModel.cs | 231 +- ...CredentialsPasswordProfileFileViewModel.cs | 199 +- .../CredentialsPasswordViewModel.cs | 117 +- .../CredentialsSetPasswordViewModel.cs | 197 +- .../ViewModels/CustomCommandViewModel.cs | 185 +- .../ViewModels/DNSLookupHostViewModel.cs | 509 ++- .../ViewModels/DNSLookupSettingsViewModel.cs | 553 ++- .../ViewModels/DNSLookupViewModel.cs | 659 ++- .../ViewModels/DashboardSettingsViewModel.cs | 243 +- .../ViewModels/DashboardViewModel.cs | 57 +- .../ViewModels/DiscoveryProtocolViewModel.cs | 593 ++- .../ViewModels/DropdownViewModel.cs | 87 +- .../ViewModels/ExportViewModel.cs | 433 +- .../ViewModels/FirstRunViewModel.cs | 81 +- .../ViewModels/GroupViewModel.cs | 2101 +++++----- .../IPAddressAndSubnetmaskViewModel.cs | 65 +- .../ViewModels/IPAddressViewModel.cs | 41 +- .../ViewModels/IPScannerHostViewModel.cs | 525 ++- .../ViewModels/IPScannerSettingsViewModel.cs | 477 ++- .../ViewModels/IPScannerViewModel.cs | 963 +++-- .../ViewModels/ListenersViewModel.cs | 515 ++- .../ViewModels/LookupHostViewModel.cs | 29 +- .../ViewModels/LookupOUILookupViewModel.cs | 335 +- .../ViewModels/LookupPortViewModel.cs | 389 +- .../ViewModels/NetworkConnectionViewModel.cs | 1219 +++--- .../ViewModels/NetworkInterfaceViewModel.cs | 1833 ++++---- .../ViewModels/PingMonitorHostViewModel.cs | 761 ++-- .../PingMonitorSettingsViewModel.cs | 183 +- .../ViewModels/PingMonitorViewModel.cs | 587 ++- .../ViewModels/PortProfileViewModel.cs | 143 +- .../ViewModels/PortProfilesViewModel.cs | 103 +- .../ViewModels/PortScannerHostViewModel.cs | 507 ++- .../PortScannerSettingsViewModel.cs | 349 +- .../ViewModels/PortScannerViewModel.cs | 849 ++-- .../ViewModels/PowerShellConnectViewModel.cs | 183 +- .../ViewModels/PowerShellHostViewModel.cs | 853 ++-- .../ViewModels/PowerShellSettingsViewModel.cs | 281 +- .../ViewModels/ProfileFileViewModel.cs | 75 +- .../ViewModels/ProfileViewModel.cs | 3673 ++++++++--------- .../ViewModels/ProfilesViewModel.cs | 437 +- .../ViewModels/PuTTYConnectViewModel.cs | 431 +- .../ViewModels/PuTTYHostViewModel.cs | 993 +++-- .../ViewModels/PuTTYSettingsViewModel.cs | 811 ++-- .../RemoteDesktopConnectViewModel.cs | 163 +- .../ViewModels/RemoteDesktopHostViewModel.cs | 835 ++-- .../RemoteDesktopSettingsViewModel.cs | 895 ++-- .../ViewModels/SNMPHostViewModel.cs | 113 +- .../ViewModels/SNMPSettingsViewModel.cs | 117 +- .../ViewModels/SNMPViewModel.cs | 909 ++-- .../ViewModels/SNTPLookupHostViewModel.cs | 165 +- .../ViewModels/SNTPLookupSettingsViewModel.cs | 299 +- .../ViewModels/SNTPLookupViewModel.cs | 443 +- .../ServerConnectionInfoProfileViewModel.cs | 185 +- .../ViewModels/SettingsAppearanceViewModel.cs | 199 +- .../ViewModels/SettingsAutostartViewModel.cs | 163 +- .../ViewModels/SettingsGeneralViewModel.cs | 355 +- .../ViewModels/SettingsHotKeysViewModel.cs | 99 +- .../ViewModels/SettingsLanguageViewModel.cs | 123 +- .../ViewModels/SettingsNetworkViewModel.cs | 153 +- .../ViewModels/SettingsProfilesViewModel.cs | 425 +- .../ViewModels/SettingsSettingsViewModel.cs | 101 +- .../ViewModels/SettingsStatusViewModel.cs | 126 +- .../ViewModels/SettingsUpdateViewModel.cs | 93 +- .../ViewModels/SettingsViewModel.cs | 577 ++- .../ViewModels/SettingsWindowViewModel.cs | 213 +- .../SubnetCalculatorCalculatorViewModel.cs | 165 +- .../SubnetCalculatorHostViewModel.cs | 29 +- .../SubnetCalculatorSubnettingViewModel.cs | 463 ++- .../SubnetCalculatorWideSubnetViewModel.cs | 233 +- .../ViewModels/TigerVNCConnectViewModel.cs | 87 +- .../ViewModels/TigerVNCHostViewModel.cs | 705 ++-- .../ViewModels/TigerVNCSettingsViewModel.cs | 193 +- .../ViewModels/TracerouteHostViewModel.cs | 521 ++- .../ViewModels/TracerouteSettingsViewModel.cs | 153 +- .../ViewModels/TracerouteViewModel.cs | 661 ++- .../ViewModels/ViewModelBase.cs | 15 +- .../ViewModels/WakeOnLANSettingsViewModel.cs | 63 +- .../ViewModels/WakeOnLANViewModel.cs | 651 ++- .../ViewModels/WebConsoleConnectViewModel.cs | 55 +- .../ViewModels/WebConsoleHostViewModel.cs | 677 ++- .../ViewModels/WhoisHostViewModel.cs | 509 ++- .../ViewModels/WhoisSettingsViewModel.cs | 37 +- .../ViewModels/WhoisViewModel.cs | 349 +- .../ViewModels/WiFiViewModel.cs | 907 ++-- 112 files changed, 23878 insertions(+), 23993 deletions(-) diff --git a/Source/NETworkManager/App.xaml.cs b/Source/NETworkManager/App.xaml.cs index 62645454a5..269e0389a9 100644 --- a/Source/NETworkManager/App.xaml.cs +++ b/Source/NETworkManager/App.xaml.cs @@ -11,40 +11,40 @@ using System.IO; using log4net; -namespace NETworkManager +namespace NETworkManager; + +/* + * Class: App + * 1) Get command line args + * 2) Detect current configuration + * 3) Get assembly info + * 4) Load settings + * 5) Load localization / language + * + * Class: MainWindow + * 6) Load appearance + * 7) Load profiles + */ + +public partial class App { - /* - * Class: App - * 1) Get command line args - * 2) Detect current configuration - * 3) Get assembly info - * 4) Load settings - * 5) Load localization / language - * - * Class: MainWindow - * 6) Load appearance - * 7) Load profiles - */ - - public partial class App - { - private static readonly ILog _log = LogManager.GetLogger(typeof(App)); + private static readonly ILog _log = LogManager.GetLogger(typeof(App)); - // Single instance identifier - private const string GUID = "6A3F34B2-161F-4F70-A8BC-A19C40F79CFB"; - private Mutex _mutex; - private DispatcherTimer _dispatcherTimer; + // Single instance identifier + private const string GUID = "6A3F34B2-161F-4F70-A8BC-A19C40F79CFB"; + private Mutex _mutex; + private DispatcherTimer _dispatcherTimer; - private bool _singleInstanceClose; + private bool _singleInstanceClose; - public App() - { - ShutdownMode = ShutdownMode.OnMainWindowClose; - } + public App() + { + ShutdownMode = ShutdownMode.OnMainWindowClose; + } - private void Application_Startup(object sender, StartupEventArgs e) - { - var startLog = $@" + private void Application_Startup(object sender, StartupEventArgs e) + { + var startLog = $@" _ _ _____ _____ _ __ __ | \ | | ____|_ _|_ _____ _ __| | _| \/ | __ _ _ __ __ _ __ _ ___ _ __ | \| | _| | | \ \ /\ / / _ \| '__| |/ / |\/| |/ _` | '_ \ / _` |/ _` |/ _ \ '__| @@ -57,290 +57,289 @@ by BornToBeRoot Version: {AssemblyManager.Current.Version} "; - _log.Info(startLog); + _log.Info(startLog); - // Catch unhandled exception globally - AppDomain.CurrentDomain.UnhandledException += (sender, e) => - { - _log.Fatal("Unhandled exception occured!"); + // Catch unhandled exception globally + AppDomain.CurrentDomain.UnhandledException += (sender, e) => + { + _log.Fatal("Unhandled exception occured!"); - if (e.ExceptionObject != null) - _log.Fatal($"Exception raised by: {e.ExceptionObject}"); - }; + if (e.ExceptionObject != null) + _log.Fatal($"Exception raised by: {e.ExceptionObject}"); + }; - // If we have restart our application... wait until it has finished - if (CommandLineManager.Current.RestartPid != -1) - { - _log.Info($"Waiting for another NETworkManager process with Pid {CommandLineManager.Current.RestartPid} to exit..."); + // If we have restart our application... wait until it has finished + if (CommandLineManager.Current.RestartPid != -1) + { + _log.Info($"Waiting for another NETworkManager process with Pid {CommandLineManager.Current.RestartPid} to exit..."); - var processList = Process.GetProcesses(); - var process = processList.FirstOrDefault(x => x.Id == CommandLineManager.Current.RestartPid); - process?.WaitForExit(); + var processList = Process.GetProcesses(); + var process = processList.FirstOrDefault(x => x.Id == CommandLineManager.Current.RestartPid); + process?.WaitForExit(); - _log.Info($"NETworkManager process with Pid {CommandLineManager.Current.RestartPid} has been exited."); - } + _log.Info($"NETworkManager process with Pid {CommandLineManager.Current.RestartPid} has been exited."); + } - MigrateAppDataToDocuments(); + MigrateAppDataToDocuments(); - // Load settings - try - { - _log.Info("Application settings are being loaded..."); + // Load settings + try + { + _log.Info("Application settings are being loaded..."); - if (CommandLineManager.Current.ResetSettings) - SettingsManager.InitDefault(); - else - SettingsManager.Load(); - } - catch (InvalidOperationException ex) - { - _log.Error("Could not load application settings!"); - _log.Error(ex.Message + "-" + ex.StackTrace); + if (CommandLineManager.Current.ResetSettings) + SettingsManager.InitDefault(); + else + SettingsManager.Load(); + } + catch (InvalidOperationException ex) + { + _log.Error("Could not load application settings!"); + _log.Error(ex.Message + "-" + ex.StackTrace); - // Create backup of corrupted file - var destinationFile = $"{TimestampHelper.GetTimestamp()}_corrupted_" + SettingsManager.GetSettingsFileName(); - File.Copy(SettingsManager.GetSettingsFilePath(), Path.Combine(SettingsManager.GetSettingsFolderLocation(), destinationFile)); - _log.Info($"A backup of the corrupted settings file has been saved under {destinationFile}"); + // Create backup of corrupted file + var destinationFile = $"{TimestampHelper.GetTimestamp()}_corrupted_" + SettingsManager.GetSettingsFileName(); + File.Copy(SettingsManager.GetSettingsFilePath(), Path.Combine(SettingsManager.GetSettingsFolderLocation(), destinationFile)); + _log.Info($"A backup of the corrupted settings file has been saved under {destinationFile}"); - // Initialize default application settings - _log.Info("Initialize default application settings..."); + // Initialize default application settings + _log.Info("Initialize default application settings..."); - SettingsManager.InitDefault(); - ConfigurationManager.Current.ShowSettingsResetNoteOnStartup = true; - } + SettingsManager.InitDefault(); + ConfigurationManager.Current.ShowSettingsResetNoteOnStartup = true; + } - // Perform settings update if settings version is lower than application version - if (SettingsManager.Current.FirstRun || string.IsNullOrEmpty(SettingsManager.Current.Version)) + // Perform settings update if settings version is lower than application version + if (SettingsManager.Current.FirstRun || string.IsNullOrEmpty(SettingsManager.Current.Version)) + { + _log.Info($"Application settings version is empty and will be set to {AssemblyManager.Current.Version}."); + + SettingsManager.Current.Version = AssemblyManager.Current.Version.ToString(); + } + else + { + Version settingsVersion = Version.Parse(SettingsManager.Current.Version); + + if (settingsVersion < AssemblyManager.Current.Version) { - _log.Info($"Application settings version is empty and will be set to {AssemblyManager.Current.Version}."); + _log.Info($"Application settings are on version {settingsVersion} and will be upgraded to {AssemblyManager.Current.Version}"); + + SettingsManager.Upgrade(settingsVersion, AssemblyManager.Current.Version); - SettingsManager.Current.Version = AssemblyManager.Current.Version.ToString(); + _log.Info($"Application settings upgraded to version {AssemblyManager.Current.Version}"); } else { - Version settingsVersion = Version.Parse(SettingsManager.Current.Version); - - if (settingsVersion < AssemblyManager.Current.Version) - { - _log.Info($"Application settings are on version {settingsVersion} and will be upgraded to {AssemblyManager.Current.Version}"); - - SettingsManager.Upgrade(settingsVersion, AssemblyManager.Current.Version); - - _log.Info($"Application settings upgraded to version {AssemblyManager.Current.Version}"); - } - else - { - _log.Info($"Application settings are already on version {AssemblyManager.Current.Version}."); - } + _log.Info($"Application settings are already on version {AssemblyManager.Current.Version}."); } + } - // Init the location with the culture code... - var localizationManager = LocalizationManager.GetInstance(SettingsManager.Current.Localization_CultureCode); - Localization.Resources.Strings.Culture = localizationManager.Culture; + // Init the location with the culture code... + var localizationManager = LocalizationManager.GetInstance(SettingsManager.Current.Localization_CultureCode); + Localization.Resources.Strings.Culture = localizationManager.Culture; - _log.Info($"Application localization culture has been set to {localizationManager.Current.Code} (Settings value is \"{SettingsManager.Current.Localization_CultureCode}\")."); + _log.Info($"Application localization culture has been set to {localizationManager.Current.Code} (Settings value is \"{SettingsManager.Current.Localization_CultureCode}\")."); - // Show help window - if (CommandLineManager.Current.Help) - { - _log.Info("Set StartupUri to CommandLineWindow.xaml..."); - StartupUri = new Uri("CommandLineWindow.xaml", UriKind.Relative); + // Show help window + if (CommandLineManager.Current.Help) + { + _log.Info("Set StartupUri to CommandLineWindow.xaml..."); + StartupUri = new Uri("CommandLineWindow.xaml", UriKind.Relative); - return; - } + return; + } - // Create mutex - _log.Info($"Try to acquire mutex with GUID {GUID} for single instance detection..."); + // Create mutex + _log.Info($"Try to acquire mutex with GUID {GUID} for single instance detection..."); - _mutex = new Mutex(true, "{" + GUID + "}"); - var mutexIsAcquired = _mutex.WaitOne(TimeSpan.Zero, true); + _mutex = new Mutex(true, "{" + GUID + "}"); + var mutexIsAcquired = _mutex.WaitOne(TimeSpan.Zero, true); - _log.Info($"Mutex value for {GUID} is {mutexIsAcquired}"); + _log.Info($"Mutex value for {GUID} is {mutexIsAcquired}"); - // Release mutex - if (mutexIsAcquired) - _mutex.ReleaseMutex(); + // Release mutex + if (mutexIsAcquired) + _mutex.ReleaseMutex(); - if (mutexIsAcquired || SettingsManager.Current.Window_MultipleInstances) + if (mutexIsAcquired || SettingsManager.Current.Window_MultipleInstances) + { + if (SettingsManager.Current.General_BackgroundJobInterval != 0) { - if (SettingsManager.Current.General_BackgroundJobInterval != 0) - { - _log.Info($"Setup background job with interval {SettingsManager.Current.General_BackgroundJobInterval} minute(s)..."); - - _dispatcherTimer = new DispatcherTimer - { - Interval = TimeSpan.FromMinutes(SettingsManager.Current.General_BackgroundJobInterval) - }; - _dispatcherTimer.Tick += DispatcherTimer_Tick; - _dispatcherTimer.Start(); - } - else - { - _log.Info("Background job is disabled."); - } + _log.Info($"Setup background job with interval {SettingsManager.Current.General_BackgroundJobInterval} minute(s)..."); - // Show splash screen - if (SettingsManager.Current.SplashScreen_Enabled) + _dispatcherTimer = new DispatcherTimer { - _log.Info("Show SplashScreen while application is loading..."); - new SplashScreen(@"SplashScreen.png").Show(true, true); - } - - // Show main window - _log.Info("Set StartupUri to MainWindow.xaml..."); - StartupUri = new Uri("MainWindow.xaml", UriKind.Relative); + Interval = TimeSpan.FromMinutes(SettingsManager.Current.General_BackgroundJobInterval) + }; + _dispatcherTimer.Tick += DispatcherTimer_Tick; + _dispatcherTimer.Start(); } else { - // Bring the already running application into the foreground - _log.Info("Another NETworkManager process is already running. Try to bring the window to the foreground..."); - SingleInstance.PostMessage((IntPtr)SingleInstance.HWND_BROADCAST, SingleInstance.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); + _log.Info("Background job is disabled."); + } - // Close the application - _singleInstanceClose = true; - Shutdown(); + // Show splash screen + if (SettingsManager.Current.SplashScreen_Enabled) + { + _log.Info("Show SplashScreen while application is loading..."); + new SplashScreen(@"SplashScreen.png").Show(true, true); } - } - [Obsolete("Temp method to migrate settings and profiles... should be removed after in 2-3 updates.")] - private void MigrateAppDataToDocuments() + // Show main window + _log.Info("Set StartupUri to MainWindow.xaml..."); + StartupUri = new Uri("MainWindow.xaml", UriKind.Relative); + } + else { - // Migrate settings and profiles from old paths to new paths - if (!ConfigurationManager.Current.IsPortable) - { - string oldSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "NETworkManager", "Settings"); + // Bring the already running application into the foreground + _log.Info("Another NETworkManager process is already running. Try to bring the window to the foreground..."); + SingleInstance.PostMessage((IntPtr)SingleInstance.HWND_BROADCAST, SingleInstance.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); - if (Directory.Exists(oldSettingsPath)) - { - string oldSettingsFile = Path.Combine(oldSettingsPath, "Settings.xml"); + // Close the application + _singleInstanceClose = true; + Shutdown(); + } + } - var oldSettingsError = false; + [Obsolete("Temp method to migrate settings and profiles... should be removed after in 2-3 updates.")] + private void MigrateAppDataToDocuments() + { + // Migrate settings and profiles from old paths to new paths + if (!ConfigurationManager.Current.IsPortable) + { + string oldSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "NETworkManager", "Settings"); - if (File.Exists(oldSettingsFile)) - { - _log.Info($"Migrate settings file from \"{oldSettingsFile}\" to \"{SettingsManager.GetSettingsFilePath()}\"..."); - Directory.CreateDirectory(SettingsManager.GetSettingsFolderLocation()); + if (Directory.Exists(oldSettingsPath)) + { + string oldSettingsFile = Path.Combine(oldSettingsPath, "Settings.xml"); - try - { - File.Move(oldSettingsFile, SettingsManager.GetSettingsFilePath()); - } - catch (Exception ex) - { - oldSettingsError = true; - _log.Error("Could not migrate settings file!", ex); - } - } + var oldSettingsError = false; + + if (File.Exists(oldSettingsFile)) + { + _log.Info($"Migrate settings file from \"{oldSettingsFile}\" to \"{SettingsManager.GetSettingsFilePath()}\"..."); + Directory.CreateDirectory(SettingsManager.GetSettingsFolderLocation()); try { - if (!oldSettingsError) - { - _log.Info($"Delete folder \"{oldSettingsPath}\"..."); - Directory.Delete(oldSettingsPath, true); - } + File.Move(oldSettingsFile, SettingsManager.GetSettingsFilePath()); } catch (Exception ex) { - _log.Error($"Could not delete folder!", ex); + oldSettingsError = true; + _log.Error("Could not migrate settings file!", ex); } } - string oldProfilesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "NETworkManager", "Profiles"); - - if (Directory.Exists(oldProfilesPath)) + try { - var profileExtensions = new[] { ".xml", ".encrypted" }; + if (!oldSettingsError) + { + _log.Info($"Delete folder \"{oldSettingsPath}\"..."); + Directory.Delete(oldSettingsPath, true); + } + } + catch (Exception ex) + { + _log.Error($"Could not delete folder!", ex); + } + } - var oldProfileFilePaths = Directory.EnumerateFiles(oldProfilesPath, "*.*", SearchOption.TopDirectoryOnly) - .Where(f => profileExtensions.Contains(Path.GetExtension(f).ToLowerInvariant())); + string oldProfilesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "NETworkManager", "Profiles"); + + if (Directory.Exists(oldProfilesPath)) + { + var profileExtensions = new[] { ".xml", ".encrypted" }; - var oldProfilesError = false; + var oldProfileFilePaths = Directory.EnumerateFiles(oldProfilesPath, "*.*", SearchOption.TopDirectoryOnly) + .Where(f => profileExtensions.Contains(Path.GetExtension(f).ToLowerInvariant())); - if (oldProfileFilePaths != null && oldProfileFilePaths.Count() > 0) + var oldProfilesError = false; + + if (oldProfileFilePaths != null && oldProfileFilePaths.Count() > 0) + { + _log.Info($"Migrate \"{oldProfileFilePaths.Count()}\" profile(s)..."); + var newProfilesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "NETworkManager", "Profiles"); + Directory.CreateDirectory(newProfilesPath); + + foreach (var oldProfileFilePath in oldProfileFilePaths) { - _log.Info($"Migrate \"{oldProfileFilePaths.Count()}\" profile(s)..."); - var newProfilesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "NETworkManager", "Profiles"); - Directory.CreateDirectory(newProfilesPath); + var newProfileFilePath = Path.Combine(newProfilesPath, Path.GetFileName(oldProfileFilePath)); + + _log.Info($"Migrate profile file from \"{oldProfileFilePath}\" to \"{newProfileFilePath}\""); - foreach (var oldProfileFilePath in oldProfileFilePaths) + try { - var newProfileFilePath = Path.Combine(newProfilesPath, Path.GetFileName(oldProfileFilePath)); - - _log.Info($"Migrate profile file from \"{oldProfileFilePath}\" to \"{newProfileFilePath}\""); - - try - { - File.Move(oldProfileFilePath, newProfileFilePath); - } - catch (Exception ex) - { - oldProfilesError = true; - _log.Error("Could not migrate profile file!", ex); - } + File.Move(oldProfileFilePath, newProfileFilePath); } - } - - try - { - if (!oldProfilesError) + catch (Exception ex) { - _log.Info($"Delete folder \"{oldProfilesPath}\"..."); - Directory.Delete(oldProfilesPath, true); + oldProfilesError = true; + _log.Error("Could not migrate profile file!", ex); } } - catch (Exception ex) + } + + try + { + if (!oldProfilesError) { - _log.Error($"Could not delete folder!", ex); + _log.Info($"Delete folder \"{oldProfilesPath}\"..."); + Directory.Delete(oldProfilesPath, true); } } + catch (Exception ex) + { + _log.Error($"Could not delete folder!", ex); + } } } + } - private void DispatcherTimer_Tick(object sender, EventArgs e) - { - _log.Info("Run background job..."); + private void DispatcherTimer_Tick(object sender, EventArgs e) + { + _log.Info("Run background job..."); - Save(); - } + Save(); + } - protected override void OnSessionEnding(SessionEndingCancelEventArgs e) - { - base.OnSessionEnding(e); + protected override void OnSessionEnding(SessionEndingCancelEventArgs e) + { + base.OnSessionEnding(e); - e.Cancel = true; + e.Cancel = true; - Shutdown(); - } + Shutdown(); + } - private void Application_Exit(object sender, ExitEventArgs e) - { - _log.Info("Exiting NETworkManager..."); + private void Application_Exit(object sender, ExitEventArgs e) + { + _log.Info("Exiting NETworkManager..."); - // Save settings, when the application is normally closed - if (_singleInstanceClose || CommandLineManager.Current.Help) - return; + // Save settings, when the application is normally closed + if (_singleInstanceClose || CommandLineManager.Current.Help) + return; - _log.Info("Stop background job (if it exists)..."); - _dispatcherTimer?.Stop(); + _log.Info("Stop background job (if it exists)..."); + _dispatcherTimer?.Stop(); - Save(); - _log.Info("Bye!"); - } + Save(); + _log.Info("Bye!"); + } - private void Save() + private void Save() + { + if (SettingsManager.Current.SettingsChanged && !ConfigurationManager.Current.DisableSaveSettings) { - if (SettingsManager.Current.SettingsChanged && !ConfigurationManager.Current.DisableSaveSettings) - { - _log.Info("Save application settings..."); - SettingsManager.Save(); - } + _log.Info("Save application settings..."); + SettingsManager.Save(); + } - if (ProfileManager.ProfilesChanged) - { - _log.Info("Save current profiles..."); - ProfileManager.Save(); - } + if (ProfileManager.ProfilesChanged) + { + _log.Info("Save current profiles..."); + ProfileManager.Save(); } } } diff --git a/Source/NETworkManager/CommandLineWindow.xaml.cs b/Source/NETworkManager/CommandLineWindow.xaml.cs index 5077d339d6..37f7656c1b 100644 --- a/Source/NETworkManager/CommandLineWindow.xaml.cs +++ b/Source/NETworkManager/CommandLineWindow.xaml.cs @@ -1,21 +1,20 @@ using NETworkManager.ViewModels; -namespace NETworkManager -{ - // ReSharper disable once UnusedMember.Global, called from App.xaml.cs - public partial class CommandLineWindow - { - private readonly CommandLineViewModel _viewModel = new CommandLineViewModel(); +namespace NETworkManager; - public CommandLineWindow() - { - InitializeComponent(); - DataContext = _viewModel; - } +// ReSharper disable once UnusedMember.Global, called from App.xaml.cs +public partial class CommandLineWindow +{ + private readonly CommandLineViewModel _viewModel = new CommandLineViewModel(); - private void Click(object sender, System.Windows.RoutedEventArgs e) - { - Close(); - } + public CommandLineWindow() + { + InitializeComponent(); + DataContext = _viewModel; + } + + private void Click(object sender, System.Windows.RoutedEventArgs e) + { + Close(); } } \ No newline at end of file diff --git a/Source/NETworkManager/Controls/AWSSessionManagerControl.xaml.cs b/Source/NETworkManager/Controls/AWSSessionManagerControl.xaml.cs index 118cb16202..c473dcaf72 100644 --- a/Source/NETworkManager/Controls/AWSSessionManagerControl.xaml.cs +++ b/Source/NETworkManager/Controls/AWSSessionManagerControl.xaml.cs @@ -13,239 +13,238 @@ using NETworkManager.Settings; using NETworkManager.Models.AWS; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class AWSSessionManagerControl : INotifyPropertyChanged { - public partial class AWSSessionManagerControl : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private bool _initialized; - private bool _closing; // When the tab is closed --> OnClose() + #region Variables + private bool _initialized; + private bool _closing; // When the tab is closed --> OnClose() - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - private readonly AWSSessionManagerSessionInfo _sessionInfo; + private readonly AWSSessionManagerSessionInfo _sessionInfo; - private Process _process; - private IntPtr _appWin; + private Process _process; + private IntPtr _appWin; - private bool _isConnected; - public bool IsConnected + private bool _isConnected; + public bool IsConnected + { + get => _isConnected; + set { - get => _isConnected; - set - { - if (value == _isConnected) - return; + if (value == _isConnected) + return; - _isConnected = value; - OnPropertyChanged(); - } + _isConnected = value; + OnPropertyChanged(); } + } - private bool _isConnecting; - public bool IsConnecting + private bool _isConnecting; + public bool IsConnecting + { + get => _isConnecting; + set { - get => _isConnecting; - set - { - if (value == _isConnecting) - return; + if (value == _isConnecting) + return; - _isConnecting = value; - OnPropertyChanged(); - } + _isConnecting = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load - public AWSSessionManagerControl(AWSSessionManagerSessionInfo info) - { - InitializeComponent(); - DataContext = this; + #region Constructor, load + public AWSSessionManagerControl(AWSSessionManagerSessionInfo info) + { + InitializeComponent(); + DataContext = this; - _dialogCoordinator = DialogCoordinator.Instance; + _dialogCoordinator = DialogCoordinator.Instance; - _sessionInfo = info; + _sessionInfo = info; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - // Connect after the control is drawn and only on the first init - if (_initialized) - return; + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Connect after the control is drawn and only on the first init + if (_initialized) + return; - // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly - WindowHost.Height = (int)ActualHeight; - WindowHost.Width = (int)ActualWidth; + // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly + WindowHost.Height = (int)ActualHeight; + WindowHost.Width = (int)ActualWidth; - Connect(); - _initialized = true; - } + Connect(); + _initialized = true; + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) - { - CloseTab(); - } - #endregion + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + CloseTab(); + } + #endregion - #region ICommands & Actions - public ICommand ReconnectCommand - { - get { return new RelayCommand(p => ReconnectAction()); } - } + #region ICommands & Actions + public ICommand ReconnectCommand + { + get { return new RelayCommand(p => ReconnectAction()); } + } - private void ReconnectAction() + private void ReconnectAction() + { + Reconnect(); + } + #endregion + + #region Methods + private async Task Connect() + { + IsConnecting = true; + + var info = new ProcessStartInfo { - Reconnect(); - } - #endregion + FileName = _sessionInfo.ApplicationFilePath, + Arguments = AWSSessionManager.BuildCommandLine(_sessionInfo) + }; - #region Methods - private async Task Connect() + try { - IsConnecting = true; + _process = Process.Start(info); - var info = new ProcessStartInfo + if (_process != null) { - FileName = _sessionInfo.ApplicationFilePath, - Arguments = AWSSessionManager.BuildCommandLine(_sessionInfo) - }; + _process.EnableRaisingEvents = true; + _process.Exited += Process_Exited; - try - { - _process = Process.Start(info); + // Embed window into panel, remove border etc. + // _process.WaitForInputIdle(); + _appWin = _process.MainWindowHandle; - if (_process != null) + if (_appWin == IntPtr.Zero) { - _process.EnableRaisingEvents = true; - _process.Exited += Process_Exited; - - // Embed window into panel, remove border etc. - // _process.WaitForInputIdle(); - _appWin = _process.MainWindowHandle; + var startTime = DateTime.Now; - if (_appWin == IntPtr.Zero) + while ((DateTime.Now - startTime).TotalSeconds < 10) { - var startTime = DateTime.Now; + _process.Refresh(); - while ((DateTime.Now - startTime).TotalSeconds < 10) - { - _process.Refresh(); + if (_process.HasExited) + break; - if (_process.HasExited) - break; + _appWin = _process.MainWindowHandle; - _appWin = _process.MainWindowHandle; + if (IntPtr.Zero != _appWin) + break; - if (IntPtr.Zero != _appWin) - break; - - await Task.Delay(100); - } + await Task.Delay(100); } + } - if (_appWin != IntPtr.Zero) - { - NativeMethods.SetParent(_appWin, WindowHost.Handle); + if (_appWin != IntPtr.Zero) + { + NativeMethods.SetParent(_appWin, WindowHost.Handle); - // Show window before set style and resize - NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); + // Show window before set style and resize + NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); - // Remove border etc. - long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); - style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); - NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); + // Remove border etc. + long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); + style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); + NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); - IsConnected = true; + IsConnected = true; - // Resize embedded application & refresh - // Requires a short delay because it's not applied immediately - await Task.Delay(250); - ResizeEmbeddedWindow(); - } - } - else - { - throw new Exception("Process could not be started!"); + // Resize embedded application & refresh + // Requires a short delay because it's not applied immediately + await Task.Delay(250); + ResizeEmbeddedWindow(); } } - catch (Exception ex) + else { - if (!_closing) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + throw new Exception("Process could not be started!"); + } + } + catch (Exception ex) + { + if (!_closing) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - ConfigurationManager.Current.IsDialogOpen = true; + ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, - ex.Message, MessageDialogStyle.Affirmative, settings); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, + ex.Message, MessageDialogStyle.Affirmative, settings); - ConfigurationManager.Current.IsDialogOpen = false; - } + ConfigurationManager.Current.IsDialogOpen = false; } - - IsConnecting = false; } - private void Process_Exited(object sender, EventArgs e) - { - // This happens when the user exit the process - IsConnected = false; - } + IsConnecting = false; + } - public void FocusEmbeddedWindow() - { - if (IsConnected) - NativeMethods.SetForegroundWindow(_process.MainWindowHandle); - } + private void Process_Exited(object sender, EventArgs e) + { + // This happens when the user exit the process + IsConnected = false; + } - public void ResizeEmbeddedWindow() - { - if (IsConnected) - NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); - } + public void FocusEmbeddedWindow() + { + if (IsConnected) + NativeMethods.SetForegroundWindow(_process.MainWindowHandle); + } - public void Disconnect() - { - if (IsConnected) - _process.Kill(); - } + public void ResizeEmbeddedWindow() + { + if (IsConnected) + NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); + } - private void Reconnect() - { - if (IsConnected) - Disconnect(); + public void Disconnect() + { + if (IsConnected) + _process.Kill(); + } - Connect(); - } + private void Reconnect() + { + if (IsConnected) + Disconnect(); - public void CloseTab() - { - _closing = true; + Connect(); + } - Disconnect(); - } - #endregion + public void CloseTab() + { + _closing = true; - #region Events - private void WindowGrid_SizeChanged(object sender, SizeChangedEventArgs e) - { - if (IsConnected) - ResizeEmbeddedWindow(); - } - #endregion + Disconnect(); + } + #endregion + + #region Events + private void WindowGrid_SizeChanged(object sender, SizeChangedEventArgs e) + { + if (IsConnected) + ResizeEmbeddedWindow(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/Controls/DragablzInterTabClient.cs b/Source/NETworkManager/Controls/DragablzInterTabClient.cs index 28f80bd449..469dbbf617 100644 --- a/Source/NETworkManager/Controls/DragablzInterTabClient.cs +++ b/Source/NETworkManager/Controls/DragablzInterTabClient.cs @@ -2,26 +2,25 @@ using NETworkManager.Models; using System.Windows; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public class DragablzInterTabClient : IInterTabClient { - public class DragablzInterTabClient : IInterTabClient - { - private readonly ApplicationName _applicationName; + private readonly ApplicationName _applicationName; - public DragablzInterTabClient(ApplicationName applicationName) - { - _applicationName = applicationName; - } + public DragablzInterTabClient(ApplicationName applicationName) + { + _applicationName = applicationName; + } - public INewTabHost GetNewHost(IInterTabClient interTabClient, object partition, TabablzControl source) - { - var dragablzTabHostWindow = new DragablzTabHostWindow(_applicationName); - return new NewTabHost(dragablzTabHostWindow, dragablzTabHostWindow.TabsContainer); - } + public INewTabHost GetNewHost(IInterTabClient interTabClient, object partition, TabablzControl source) + { + var dragablzTabHostWindow = new DragablzTabHostWindow(_applicationName); + return new NewTabHost(dragablzTabHostWindow, dragablzTabHostWindow.TabsContainer); + } - public TabEmptiedResponse TabEmptiedHandler(TabablzControl tabControl, Window window) - { - return window is MainWindow ? TabEmptiedResponse.DoNothing : TabEmptiedResponse.CloseWindowOrLayoutBranch; - } + public TabEmptiedResponse TabEmptiedHandler(TabablzControl tabControl, Window window) + { + return window is MainWindow ? TabEmptiedResponse.DoNothing : TabEmptiedResponse.CloseWindowOrLayoutBranch; } } diff --git a/Source/NETworkManager/Controls/DragablzTabHostWindow.xaml.cs b/Source/NETworkManager/Controls/DragablzTabHostWindow.xaml.cs index b849a87004..2612d6c27c 100644 --- a/Source/NETworkManager/Controls/DragablzTabHostWindow.xaml.cs +++ b/Source/NETworkManager/Controls/DragablzTabHostWindow.xaml.cs @@ -12,341 +12,340 @@ using NETworkManager.Models; using System.Threading.Tasks; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class DragablzTabHostWindow : INotifyPropertyChanged { - public partial class DragablzTabHostWindow : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - public IInterTabClient InterTabClient { get; } - private ApplicationName _applicationName; + #region Variables + public IInterTabClient InterTabClient { get; } + private ApplicationName _applicationName; - public ApplicationName ApplicationName + public ApplicationName ApplicationName + { + get => _applicationName; + set { - get => _applicationName; - set - { - if (value == _applicationName) - return; + if (value == _applicationName) + return; - _applicationName = value; - OnPropertyChanged(); - } + _applicationName = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor - public DragablzTabHostWindow(ApplicationName applicationName) - { - InitializeComponent(); - DataContext = this; + #region Constructor + public DragablzTabHostWindow(ApplicationName applicationName) + { + InitializeComponent(); + DataContext = this; - ApplicationName = applicationName; + ApplicationName = applicationName; - InterTabClient = new DragablzInterTabClient(applicationName); + InterTabClient = new DragablzInterTabClient(applicationName); - InterTabController.Partition = applicationName.ToString(); + InterTabController.Partition = applicationName.ToString(); - Title = $"NETworkManager {AssemblyManager.Current.Version} - {ApplicationNameTranslator.GetInstance().Translate(applicationName)}"; + Title = $"NETworkManager {AssemblyManager.Current.Version} - {ApplicationNameTranslator.GetInstance().Translate(applicationName)}"; - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - } - #endregion + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + } + #endregion - #region ICommand & Actions - public ItemActionCallback CloseItemCommand => CloseItemAction; + #region ICommand & Actions + public ItemActionCallback CloseItemCommand => CloseItemAction; - private void CloseItemAction(ItemActionCallbackArgs args) + private void CloseItemAction(ItemActionCallbackArgs args) + { + // Switch between application identifiert... + switch (_applicationName) { - // Switch between application identifiert... - switch (_applicationName) - { - case ApplicationName.None: - break; - case ApplicationName.IPScanner: - ((IPScannerView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.PortScanner: - ((PortScannerView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.Traceroute: - ((TracerouteView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.DNSLookup: - ((DNSLookupView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.RemoteDesktop: - ((RemoteDesktopControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.PowerShell: - ((PowerShellControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.PuTTY: - ((PuTTYControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.AWSSessionManager: - ((AWSSessionManagerControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.TigerVNC: - ((TigerVNCControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.WebConsole: - ((WebConsoleControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.SNMP: - ((SNMPView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.SNTPLookup: - ((SNTPLookupView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - case ApplicationName.Whois: - ((WhoisView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); - break; - default: - throw new ArgumentOutOfRangeException(); - } + case ApplicationName.None: + break; + case ApplicationName.IPScanner: + ((IPScannerView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.PortScanner: + ((PortScannerView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.Traceroute: + ((TracerouteView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.DNSLookup: + ((DNSLookupView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.RemoteDesktop: + ((RemoteDesktopControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.PowerShell: + ((PowerShellControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.PuTTY: + ((PuTTYControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.AWSSessionManager: + ((AWSSessionManagerControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.TigerVNC: + ((TigerVNCControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.WebConsole: + ((WebConsoleControl)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.SNMP: + ((SNMPView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.SNTPLookup: + ((SNTPLookupView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + case ApplicationName.Whois: + ((WhoisView)((DragablzTabItem)args.DragablzItem.Content).View).CloseTab(); + break; + default: + throw new ArgumentOutOfRangeException(); } + } - #region RemoteDesktop Commands - private bool RemoteDesktop_Disconnected_CanExecute(object view) - { - if (view is RemoteDesktopControl control) - return !control.IsConnected; + #region RemoteDesktop Commands + private bool RemoteDesktop_Disconnected_CanExecute(object view) + { + if (view is RemoteDesktopControl control) + return !control.IsConnected; - return false; - } + return false; + } - private bool RemoteDesktop_Connected_CanExecute(object view) - { - if (view is RemoteDesktopControl control) - return control.IsConnected; + private bool RemoteDesktop_Connected_CanExecute(object view) + { + if (view is RemoteDesktopControl control) + return control.IsConnected; - return false; - } + return false; + } - public ICommand RemoteDesktop_ReconnectCommand => new RelayCommand(RemoteDesktop_ReconnectAction, RemoteDesktop_Disconnected_CanExecute); + public ICommand RemoteDesktop_ReconnectCommand => new RelayCommand(RemoteDesktop_ReconnectAction, RemoteDesktop_Disconnected_CanExecute); - private void RemoteDesktop_ReconnectAction(object view) + private void RemoteDesktop_ReconnectAction(object view) + { + if (view is RemoteDesktopControl control) { - if (view is RemoteDesktopControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } + } - public ICommand RemoteDesktop_DisconnectCommand => new RelayCommand(RemoteDesktop_DisconnectAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_DisconnectCommand => new RelayCommand(RemoteDesktop_DisconnectAction, RemoteDesktop_Connected_CanExecute); - private void RemoteDesktop_DisconnectAction(object view) + private void RemoteDesktop_DisconnectAction(object view) + { + if (view is RemoteDesktopControl control) { - if (view is RemoteDesktopControl control) - { - if (control.DisconnectCommand.CanExecute(null)) - control.DisconnectCommand.Execute(null); - } + if (control.DisconnectCommand.CanExecute(null)) + control.DisconnectCommand.Execute(null); } + } - public ICommand RemoteDesktop_FullscreenCommand => new RelayCommand(RemoteDesktop_FullscreenAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_FullscreenCommand => new RelayCommand(RemoteDesktop_FullscreenAction, RemoteDesktop_Connected_CanExecute); - private void RemoteDesktop_FullscreenAction(object view) - { - if (view is RemoteDesktopControl control) - control.FullScreen(); - } + private void RemoteDesktop_FullscreenAction(object view) + { + if (view is RemoteDesktopControl control) + control.FullScreen(); + } - public ICommand RemoteDesktop_AdjustScreenCommand => new RelayCommand(RemoteDesktop_AdjustScreenAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_AdjustScreenCommand => new RelayCommand(RemoteDesktop_AdjustScreenAction, RemoteDesktop_Connected_CanExecute); - private void RemoteDesktop_AdjustScreenAction(object view) - { - if (view is RemoteDesktopControl control) - control.AdjustScreen(); - } + private void RemoteDesktop_AdjustScreenAction(object view) + { + if (view is RemoteDesktopControl control) + control.AdjustScreen(); + } - public ICommand RemoteDesktop_SendCtrlAltDelCommand => new RelayCommand(RemoteDesktop_SendCtrlAltDelAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_SendCtrlAltDelCommand => new RelayCommand(RemoteDesktop_SendCtrlAltDelAction, RemoteDesktop_Connected_CanExecute); - private async void RemoteDesktop_SendCtrlAltDelAction(object view) + private async void RemoteDesktop_SendCtrlAltDelAction(object view) + { + if (view is RemoteDesktopControl control) { - if (view is RemoteDesktopControl control) + try { - try - { - control.SendKey(Keystroke.CtrlAltDel); - } - catch (Exception ex) - { - ConfigurationManager.Current.IsDialogOpen = true; - - await this.ShowMessageAsync(Localization.Resources.Strings.Error, string.Format("{0}\n\nMessage:\n{1}", NETworkManager.Localization.Resources.Strings.CouldNotSendKeystroke, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog)); - - ConfigurationManager.Current.IsDialogOpen = false; - } + control.SendKey(Keystroke.CtrlAltDel); } - } - #endregion + catch (Exception ex) + { + ConfigurationManager.Current.IsDialogOpen = true; - #region PowerShell Commands - private bool PowerShell_Disconnected_CanExecute(object view) - { - if (view is PowerShellControl control) - return !control.IsConnected; + await this.ShowMessageAsync(Localization.Resources.Strings.Error, string.Format("{0}\n\nMessage:\n{1}", NETworkManager.Localization.Resources.Strings.CouldNotSendKeystroke, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog)); - return false; + ConfigurationManager.Current.IsDialogOpen = false; + } } + } + #endregion - public ICommand PowerShell_ReconnectCommand => new RelayCommand(PowerShell_ReconnectAction); + #region PowerShell Commands + private bool PowerShell_Disconnected_CanExecute(object view) + { + if (view is PowerShellControl control) + return !control.IsConnected; - private void PowerShell_ReconnectAction(object view) - { - if (view is PowerShellControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } - } + return false; + } - public ICommand PowerShell_ResizeWindowCommand => new RelayCommand(PowerShell_ResizeWindowAction, PowerShell_Disconnected_CanExecute); + public ICommand PowerShell_ReconnectCommand => new RelayCommand(PowerShell_ReconnectAction); - private void PowerShell_ResizeWindowAction(object view) + private void PowerShell_ReconnectAction(object view) + { + if (view is PowerShellControl control) { - if (view is PowerShellControl control) - control.ResizeEmbeddedWindow(); + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } - #endregion + } - #region PuTTY Commands - private bool PuTTY_Connected_CanExecute(object view) - { - if (view is PuTTYControl control) - return control.IsConnected; + public ICommand PowerShell_ResizeWindowCommand => new RelayCommand(PowerShell_ResizeWindowAction, PowerShell_Disconnected_CanExecute); - return false; - } + private void PowerShell_ResizeWindowAction(object view) + { + if (view is PowerShellControl control) + control.ResizeEmbeddedWindow(); + } + #endregion - public ICommand PuTTY_ReconnectCommand => new RelayCommand(PuTTY_ReconnectAction); + #region PuTTY Commands + private bool PuTTY_Connected_CanExecute(object view) + { + if (view is PuTTYControl control) + return control.IsConnected; - private void PuTTY_ReconnectAction(object view) - { - if (view is PuTTYControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } - } + return false; + } - public ICommand PuTTY_ResizeWindowCommand => new RelayCommand(PuTTY_ResizeWindowAction, PuTTY_Connected_CanExecute); + public ICommand PuTTY_ReconnectCommand => new RelayCommand(PuTTY_ReconnectAction); - private void PuTTY_ResizeWindowAction(object view) + private void PuTTY_ReconnectAction(object view) + { + if (view is PuTTYControl control) { - if (view is PuTTYControl control) - control.ResizeEmbeddedWindow(); + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } + } - public ICommand PuTTY_RestartSessionCommand => new RelayCommand(PuTTY_RestartSessionAction, PuTTY_Connected_CanExecute); + public ICommand PuTTY_ResizeWindowCommand => new RelayCommand(PuTTY_ResizeWindowAction, PuTTY_Connected_CanExecute); - private void PuTTY_RestartSessionAction(object view) - { - if (view is PuTTYControl control) - control.RestartSession(); - } - #endregion + private void PuTTY_ResizeWindowAction(object view) + { + if (view is PuTTYControl control) + control.ResizeEmbeddedWindow(); + } - #region AWSSessionManager Commands - private bool AWSSessionManager_Disconnected_CanExecute(object view) - { - if (view is AWSSessionManagerControl control) - return !control.IsConnected; + public ICommand PuTTY_RestartSessionCommand => new RelayCommand(PuTTY_RestartSessionAction, PuTTY_Connected_CanExecute); - return false; - } + private void PuTTY_RestartSessionAction(object view) + { + if (view is PuTTYControl control) + control.RestartSession(); + } + #endregion - public ICommand AWSSessionManager_ReconnectCommand => new RelayCommand(AWSSessionManager_ReconnectAction); + #region AWSSessionManager Commands + private bool AWSSessionManager_Disconnected_CanExecute(object view) + { + if (view is AWSSessionManagerControl control) + return !control.IsConnected; - private void AWSSessionManager_ReconnectAction(object view) - { - if (view is AWSSessionManagerControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } - } + return false; + } - public ICommand AWSSessionManager_ResizeWindowCommand => new RelayCommand(AWSSessionManager_ResizeWindowAction, AWSSessionManager_Disconnected_CanExecute); + public ICommand AWSSessionManager_ReconnectCommand => new RelayCommand(AWSSessionManager_ReconnectAction); - private void AWSSessionManager_ResizeWindowAction(object view) + private void AWSSessionManager_ReconnectAction(object view) + { + if (view is AWSSessionManagerControl control) { - if (view is PowerShellControl control) - control.ResizeEmbeddedWindow(); + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } - #endregion + } - #region TigerVNC Commands - public ICommand TigerVNC_ReconnectCommand => new RelayCommand(TigerVNC_ReconnectAction); + public ICommand AWSSessionManager_ResizeWindowCommand => new RelayCommand(AWSSessionManager_ResizeWindowAction, AWSSessionManager_Disconnected_CanExecute); - private void TigerVNC_ReconnectAction(object view) + private void AWSSessionManager_ResizeWindowAction(object view) + { + if (view is PowerShellControl control) + control.ResizeEmbeddedWindow(); + } + #endregion + + #region TigerVNC Commands + public ICommand TigerVNC_ReconnectCommand => new RelayCommand(TigerVNC_ReconnectAction); + + private void TigerVNC_ReconnectAction(object view) + { + if (view is TigerVNCControl control) { - if (view is TigerVNCControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } - #endregion + } + #endregion - #region WebConsole Commands - public ICommand WebConsole_ReloadCommand => new RelayCommand(WebConsole_RefreshAction); + #region WebConsole Commands + public ICommand WebConsole_ReloadCommand => new RelayCommand(WebConsole_RefreshAction); - private void WebConsole_RefreshAction(object view) + private void WebConsole_RefreshAction(object view) + { + if (view is WebConsoleControl control) { - if (view is WebConsoleControl control) - { - if (control.ReloadCommand.CanExecute(null)) - control.ReloadCommand.Execute(null); - } + if (control.ReloadCommand.CanExecute(null)) + control.ReloadCommand.Execute(null); } - #endregion - #endregion + } + #endregion + #endregion - private async void FocusEmbeddedWindow() + private async void FocusEmbeddedWindow() + { + // Delay the focus to prevent blocking the ui + do { - // Delay the focus to prevent blocking the ui - do - { - await Task.Delay(250); - } while (Mouse.LeftButton == MouseButtonState.Pressed); + await Task.Delay(250); + } while (Mouse.LeftButton == MouseButtonState.Pressed); - // Switch by name - switch (ApplicationName) - { - case ApplicationName.PowerShell: - ((PowerShellControl)((DragablzTabItem)TabsContainer?.SelectedItem)?.View)?.FocusEmbeddedWindow(); - break; - case ApplicationName.PuTTY: - ((PuTTYControl)((DragablzTabItem)TabsContainer?.SelectedItem)?.View)?.FocusEmbeddedWindow(); - break; - case ApplicationName.AWSSessionManager: - ((AWSSessionManagerControl)((DragablzTabItem)TabsContainer?.SelectedItem)?.View)?.FocusEmbeddedWindow(); - break; - } + // Switch by name + switch (ApplicationName) + { + case ApplicationName.PowerShell: + ((PowerShellControl)((DragablzTabItem)TabsContainer?.SelectedItem)?.View)?.FocusEmbeddedWindow(); + break; + case ApplicationName.PuTTY: + ((PuTTYControl)((DragablzTabItem)TabsContainer?.SelectedItem)?.View)?.FocusEmbeddedWindow(); + break; + case ApplicationName.AWSSessionManager: + ((AWSSessionManagerControl)((DragablzTabItem)TabsContainer?.SelectedItem)?.View)?.FocusEmbeddedWindow(); + break; } + } - #region Events - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) - { + #region Events + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { - } + } - private void MetroWindow_Activated(object sender, EventArgs e) - { - FocusEmbeddedWindow(); - } - #endregion + private void MetroWindow_Activated(object sender, EventArgs e) + { + FocusEmbeddedWindow(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/Controls/DragablzTabItem.cs b/Source/NETworkManager/Controls/DragablzTabItem.cs index 1d6c53cd76..8b89bb4fb1 100644 --- a/Source/NETworkManager/Controls/DragablzTabItem.cs +++ b/Source/NETworkManager/Controls/DragablzTabItem.cs @@ -1,38 +1,37 @@ using NETworkManager.ViewModels; using System.Windows.Controls; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public class DragablzTabItem : ViewModelBase { - public class DragablzTabItem : ViewModelBase + private string _header; + public string Header { - private string _header; - public string Header + get => _header; + set { - get => _header; - set - { - if (value == _header) - return; + if (value == _header) + return; - _header = value; - OnPropertyChanged(); - } + _header = value; + OnPropertyChanged(); } + } - public UserControl View { get; set; } - public int Id { get; set; } + public UserControl View { get; set; } + public int Id { get; set; } - public DragablzTabItem(string header, UserControl view) - { - Header = header; - View = view; - } + public DragablzTabItem(string header, UserControl view) + { + Header = header; + View = view; + } - public DragablzTabItem(string header, UserControl view, int id) - { - Header = header; - View = view; - Id = id; - } + public DragablzTabItem(string header, UserControl view, int id) + { + Header = header; + View = view; + Id = id; } } diff --git a/Source/NETworkManager/Controls/LvlChartsBandwidthTooltip.xaml.cs b/Source/NETworkManager/Controls/LvlChartsBandwidthTooltip.xaml.cs index 22e161a181..a01815b5ce 100644 --- a/Source/NETworkManager/Controls/LvlChartsBandwidthTooltip.xaml.cs +++ b/Source/NETworkManager/Controls/LvlChartsBandwidthTooltip.xaml.cs @@ -4,36 +4,35 @@ using System.Runtime.CompilerServices; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class LvlChartsBandwidthTooltip : IChartTooltip { - public partial class LvlChartsBandwidthTooltip : IChartTooltip - { - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - private TooltipData _data; + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private TooltipData _data; - public TooltipData Data + public TooltipData Data + { + get { return _data; } + set { - get { return _data; } - set - { - _data = value; - OnPropertyChanged(); - } + _data = value; + OnPropertyChanged(); } + } - public TooltipSelectionMode? SelectionMode { get; set; } - - public LvlChartsBandwidthTooltip() - { - InitializeComponent(); + public TooltipSelectionMode? SelectionMode { get; set; } - DataContext = this; - } - } + public LvlChartsBandwidthTooltip() + { + InitializeComponent(); + + DataContext = this; + } } diff --git a/Source/NETworkManager/Controls/LvlChartsPingTimeTooltip.xaml.cs b/Source/NETworkManager/Controls/LvlChartsPingTimeTooltip.xaml.cs index 50d1d9bff3..4fa8c4e4b8 100644 --- a/Source/NETworkManager/Controls/LvlChartsPingTimeTooltip.xaml.cs +++ b/Source/NETworkManager/Controls/LvlChartsPingTimeTooltip.xaml.cs @@ -4,36 +4,35 @@ using System.Runtime.CompilerServices; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class LvlChartsPingTimeTooltip : IChartTooltip { - public partial class LvlChartsPingTimeTooltip : IChartTooltip - { - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - private TooltipData _data; + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private TooltipData _data; - public TooltipData Data + public TooltipData Data + { + get { return _data; } + set { - get { return _data; } - set - { - _data = value; - OnPropertyChanged(); - } + _data = value; + OnPropertyChanged(); } + } - public TooltipSelectionMode? SelectionMode { get; set; } - - public LvlChartsPingTimeTooltip() - { - InitializeComponent(); + public TooltipSelectionMode? SelectionMode { get; set; } - DataContext = this; - } - } + public LvlChartsPingTimeTooltip() + { + InitializeComponent(); + + DataContext = this; + } } diff --git a/Source/NETworkManager/Controls/LvlChartsWiFiChannelTooltip.xaml.cs b/Source/NETworkManager/Controls/LvlChartsWiFiChannelTooltip.xaml.cs index 1e7f511d1c..55413801ff 100644 --- a/Source/NETworkManager/Controls/LvlChartsWiFiChannelTooltip.xaml.cs +++ b/Source/NETworkManager/Controls/LvlChartsWiFiChannelTooltip.xaml.cs @@ -4,36 +4,35 @@ using System.Runtime.CompilerServices; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class LvlChartsWiFiChannelTooltip : IChartTooltip { - public partial class LvlChartsWiFiChannelTooltip : IChartTooltip - { - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - - private TooltipData _data; + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + + private TooltipData _data; - public TooltipData Data + public TooltipData Data + { + get { return _data; } + set { - get { return _data; } - set - { - _data = value; - OnPropertyChanged(); - } + _data = value; + OnPropertyChanged(); } + } - public TooltipSelectionMode? SelectionMode { get; set; } - - public LvlChartsWiFiChannelTooltip() - { - InitializeComponent(); + public TooltipSelectionMode? SelectionMode { get; set; } + + public LvlChartsWiFiChannelTooltip() + { + InitializeComponent(); - DataContext = this; - } - } + DataContext = this; + } } diff --git a/Source/NETworkManager/Controls/PowerShellControl.xaml.cs b/Source/NETworkManager/Controls/PowerShellControl.xaml.cs index fefe0ec5c4..311ff5db68 100644 --- a/Source/NETworkManager/Controls/PowerShellControl.xaml.cs +++ b/Source/NETworkManager/Controls/PowerShellControl.xaml.cs @@ -13,239 +13,238 @@ using NETworkManager.Settings; using NETworkManager.Models.PowerShell; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class PowerShellControl : INotifyPropertyChanged { - public partial class PowerShellControl : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private bool _initialized; - private bool _closing; // When the tab is closed --> OnClose() + #region Variables + private bool _initialized; + private bool _closing; // When the tab is closed --> OnClose() - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - private readonly PowerShellSessionInfo _sessionInfo; + private readonly PowerShellSessionInfo _sessionInfo; - private Process _process; - private IntPtr _appWin; + private Process _process; + private IntPtr _appWin; - private bool _isConnected; - public bool IsConnected + private bool _isConnected; + public bool IsConnected + { + get => _isConnected; + set { - get => _isConnected; - set - { - if (value == _isConnected) - return; + if (value == _isConnected) + return; - _isConnected = value; - OnPropertyChanged(); - } + _isConnected = value; + OnPropertyChanged(); } + } - private bool _isConnecting; - public bool IsConnecting + private bool _isConnecting; + public bool IsConnecting + { + get => _isConnecting; + set { - get => _isConnecting; - set - { - if (value == _isConnecting) - return; + if (value == _isConnecting) + return; - _isConnecting = value; - OnPropertyChanged(); - } + _isConnecting = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load - public PowerShellControl(PowerShellSessionInfo info) - { - InitializeComponent(); - DataContext = this; + #region Constructor, load + public PowerShellControl(PowerShellSessionInfo info) + { + InitializeComponent(); + DataContext = this; - _dialogCoordinator = DialogCoordinator.Instance; + _dialogCoordinator = DialogCoordinator.Instance; - _sessionInfo = info; + _sessionInfo = info; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - // Connect after the control is drawn and only on the first init - if (_initialized) - return; + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Connect after the control is drawn and only on the first init + if (_initialized) + return; - // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly - WindowHost.Height = (int)ActualHeight; - WindowHost.Width = (int)ActualWidth; + // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly + WindowHost.Height = (int)ActualHeight; + WindowHost.Width = (int)ActualWidth; - Connect(); - _initialized = true; - } + Connect(); + _initialized = true; + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) - { - CloseTab(); - } - #endregion + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + CloseTab(); + } + #endregion - #region ICommands & Actions - public ICommand ReconnectCommand - { - get { return new RelayCommand(p => ReconnectAction()); } - } + #region ICommands & Actions + public ICommand ReconnectCommand + { + get { return new RelayCommand(p => ReconnectAction()); } + } + + private void ReconnectAction() + { + Reconnect(); + } + #endregion + + #region Methods + private async Task Connect() + { + IsConnecting = true; - private void ReconnectAction() + var info = new ProcessStartInfo { - Reconnect(); - } - #endregion + FileName = _sessionInfo.ApplicationFilePath, + Arguments = PowerShell.BuildCommandLine(_sessionInfo) + }; - #region Methods - private async Task Connect() + try { - IsConnecting = true; + _process = Process.Start(info); - var info = new ProcessStartInfo + if (_process != null) { - FileName = _sessionInfo.ApplicationFilePath, - Arguments = PowerShell.BuildCommandLine(_sessionInfo) - }; + _process.EnableRaisingEvents = true; + _process.Exited += Process_Exited; - try - { - _process = Process.Start(info); + // Embed window into panel, remove border etc. + // _process.WaitForInputIdle(); + _appWin = _process.MainWindowHandle; - if (_process != null) + if (_appWin == IntPtr.Zero) { - _process.EnableRaisingEvents = true; - _process.Exited += Process_Exited; + var startTime = DateTime.Now; - // Embed window into panel, remove border etc. - // _process.WaitForInputIdle(); - _appWin = _process.MainWindowHandle; - - if (_appWin == IntPtr.Zero) + while ((DateTime.Now - startTime).TotalSeconds < 10) { - var startTime = DateTime.Now; - - while ((DateTime.Now - startTime).TotalSeconds < 10) - { - _process.Refresh(); - - if (_process.HasExited) - break; - - - _appWin = _process.MainWindowHandle; - - if (IntPtr.Zero != _appWin) - break; + _process.Refresh(); - await Task.Delay(100); - } - } - - if (_appWin != IntPtr.Zero) - { - NativeMethods.SetParent(_appWin, WindowHost.Handle); + if (_process.HasExited) + break; + - // Show window before set style and resize - NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); + _appWin = _process.MainWindowHandle; - // Remove border etc. - long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); - style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); - NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); - - IsConnected = true; + if (IntPtr.Zero != _appWin) + break; - // Resize embedded application & refresh - // Requires a short delay because it's not applied immediately - await Task.Delay(250); - ResizeEmbeddedWindow(); + await Task.Delay(100); } } - else + + if (_appWin != IntPtr.Zero) { - throw new Exception("Process could not be started!"); + NativeMethods.SetParent(_appWin, WindowHost.Handle); + + // Show window before set style and resize + NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); + + // Remove border etc. + long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); + style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); + NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); + + IsConnected = true; + + // Resize embedded application & refresh + // Requires a short delay because it's not applied immediately + await Task.Delay(250); + ResizeEmbeddedWindow(); } } - catch (Exception ex) + else { - if (!_closing) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + throw new Exception("Process could not be started!"); + } + } + catch (Exception ex) + { + if (!_closing) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - ConfigurationManager.Current.IsDialogOpen = true; + ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, - ex.Message, MessageDialogStyle.Affirmative, settings); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, + ex.Message, MessageDialogStyle.Affirmative, settings); - ConfigurationManager.Current.IsDialogOpen = false; - } + ConfigurationManager.Current.IsDialogOpen = false; } - - IsConnecting = false; } - private void Process_Exited(object sender, EventArgs e) - { - // This happens when the user exit the process - IsConnected = false; - } + IsConnecting = false; + } - public void FocusEmbeddedWindow() - { - if (IsConnected) - NativeMethods.SetForegroundWindow(_process.MainWindowHandle); - } + private void Process_Exited(object sender, EventArgs e) + { + // This happens when the user exit the process + IsConnected = false; + } - public void ResizeEmbeddedWindow() - { - if (IsConnected) - NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); - } + public void FocusEmbeddedWindow() + { + if (IsConnected) + NativeMethods.SetForegroundWindow(_process.MainWindowHandle); + } - public void Disconnect() - { - if (IsConnected) - _process.Kill(); - } + public void ResizeEmbeddedWindow() + { + if (IsConnected) + NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); + } - private void Reconnect() - { - if (IsConnected) - Disconnect(); + public void Disconnect() + { + if (IsConnected) + _process.Kill(); + } - Connect(); - } + private void Reconnect() + { + if (IsConnected) + Disconnect(); - public void CloseTab() - { - _closing = true; + Connect(); + } - Disconnect(); - } - #endregion + public void CloseTab() + { + _closing = true; - #region Events - private void WindowGrid_SizeChanged(object sender, SizeChangedEventArgs e) - { - if (IsConnected) - ResizeEmbeddedWindow(); - } - #endregion + Disconnect(); + } + #endregion + + #region Events + private void WindowGrid_SizeChanged(object sender, SizeChangedEventArgs e) + { + if (IsConnected) + ResizeEmbeddedWindow(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/Controls/PuTTYControl.xaml.cs b/Source/NETworkManager/Controls/PuTTYControl.xaml.cs index 59ddc38dbe..9d6aa21900 100644 --- a/Source/NETworkManager/Controls/PuTTYControl.xaml.cs +++ b/Source/NETworkManager/Controls/PuTTYControl.xaml.cs @@ -14,258 +14,257 @@ using NETworkManager.Settings; using PuTTY = NETworkManager.Models.PuTTY.PuTTY; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class PuTTYControl : INotifyPropertyChanged { - public partial class PuTTYControl : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private bool _initialized; - private bool _closing; // When the tab is closed --> OnClose() + #region Variables + private bool _initialized; + private bool _closing; // When the tab is closed --> OnClose() - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - private readonly PuTTYSessionInfo _sessionInfo; + private readonly PuTTYSessionInfo _sessionInfo; - private Process _process; - private IntPtr _appWin; + private Process _process; + private IntPtr _appWin; - private bool _isConnected; - public bool IsConnected + private bool _isConnected; + public bool IsConnected + { + get => _isConnected; + set { - get => _isConnected; - set - { - if (value == _isConnected) - return; + if (value == _isConnected) + return; - _isConnected = value; - OnPropertyChanged(); - } + _isConnected = value; + OnPropertyChanged(); } + } - private bool _isConnecting; - public bool IsConnecting + private bool _isConnecting; + public bool IsConnecting + { + get => _isConnecting; + set { - get => _isConnecting; - set - { - if (value == _isConnecting) - return; + if (value == _isConnecting) + return; - _isConnecting = value; - OnPropertyChanged(); - } + _isConnecting = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load - public PuTTYControl(PuTTYSessionInfo info) - { - InitializeComponent(); - DataContext = this; + #region Constructor, load + public PuTTYControl(PuTTYSessionInfo info) + { + InitializeComponent(); + DataContext = this; - _dialogCoordinator = DialogCoordinator.Instance; + _dialogCoordinator = DialogCoordinator.Instance; - _sessionInfo = info; + _sessionInfo = info; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - // Connect after the control is drawn and only on the first init - if (_initialized) - return; + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Connect after the control is drawn and only on the first init + if (_initialized) + return; - // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly - WindowHost.Height = (int)ActualHeight; - WindowHost.Width = (int)ActualWidth; + // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly + WindowHost.Height = (int)ActualHeight; + WindowHost.Width = (int)ActualWidth; - Connect(); + Connect(); - _initialized = true; - } + _initialized = true; + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) - { - CloseTab(); - } - #endregion + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + CloseTab(); + } + #endregion - #region ICommands & Actions - public ICommand ReconnectCommand - { - get { return new RelayCommand(p => ReconnectAction()); } - } + #region ICommands & Actions + public ICommand ReconnectCommand + { + get { return new RelayCommand(p => ReconnectAction()); } + } - private void ReconnectAction() - { - Reconnect(); - } - #endregion + private void ReconnectAction() + { + Reconnect(); + } + #endregion + + #region Methods + private async Task Connect() + { + IsConnecting = true; + + // Create log path + DirectoryHelper.CreateWithEnvironmentVariables(_sessionInfo.LogPath); - #region Methods - private async Task Connect() + var info = new ProcessStartInfo { - IsConnecting = true; + FileName = _sessionInfo.ApplicationFilePath, + Arguments = PuTTY.BuildCommandLine(_sessionInfo) + }; - // Create log path - DirectoryHelper.CreateWithEnvironmentVariables(_sessionInfo.LogPath); + try + { + _process = Process.Start(info); - var info = new ProcessStartInfo + if (_process != null) { - FileName = _sessionInfo.ApplicationFilePath, - Arguments = PuTTY.BuildCommandLine(_sessionInfo) - }; + _process.EnableRaisingEvents = true; + _process.Exited += Process_Exited; - try - { - _process = Process.Start(info); + _appWin = _process.MainWindowHandle; - if (_process != null) + if (_appWin == IntPtr.Zero) { - _process.EnableRaisingEvents = true; - _process.Exited += Process_Exited; - - _appWin = _process.MainWindowHandle; + var startTime = DateTime.Now; - if (_appWin == IntPtr.Zero) + while ((DateTime.Now - startTime).TotalSeconds < 10) { - var startTime = DateTime.Now; - - while ((DateTime.Now - startTime).TotalSeconds < 10) - { - _process.Refresh(); - - if (_process.HasExited) - break; - + _process.Refresh(); + + if (_process.HasExited) + break; + - _appWin = _process.MainWindowHandle; + _appWin = _process.MainWindowHandle; - if (IntPtr.Zero != _appWin) - break; + if (IntPtr.Zero != _appWin) + break; - await Task.Delay(100); - } + await Task.Delay(100); } + } - if (_appWin != IntPtr.Zero) + if (_appWin != IntPtr.Zero) + { + while (!_process.HasExited && _process.MainWindowTitle.IndexOf(" - PuTTY", StringComparison.Ordinal) == -1) { - while (!_process.HasExited && _process.MainWindowTitle.IndexOf(" - PuTTY", StringComparison.Ordinal) == -1) - { - await Task.Delay(100); + await Task.Delay(100); - _process.Refresh(); - } + _process.Refresh(); + } - if (!_process.HasExited) - { - NativeMethods.SetParent(_appWin, WindowHost.Handle); + if (!_process.HasExited) + { + NativeMethods.SetParent(_appWin, WindowHost.Handle); - // Show window before set style and resize - NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); + // Show window before set style and resize + NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); - // Remove border etc. - long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); - style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); // NativeMethods.WS_POPUP --> Overflow? (https://github.com/BornToBeRoot/NETworkManager/issues/167) - NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); + // Remove border etc. + long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); + style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); // NativeMethods.WS_POPUP --> Overflow? (https://github.com/BornToBeRoot/NETworkManager/issues/167) + NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); - IsConnected = true; + IsConnected = true; - // Resize embedded application & refresh - // Requires a short delay because it's not applied immediately - await Task.Delay(250); - - ResizeEmbeddedWindow(); - } + // Resize embedded application & refresh + // Requires a short delay because it's not applied immediately + await Task.Delay(250); + + ResizeEmbeddedWindow(); } } - else - { - throw new Exception("Process could not be started!"); - } } - catch (Exception ex) + else { - if (!_closing) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + throw new Exception("Process could not be started!"); + } + } + catch (Exception ex) + { + if (!_closing) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - ConfigurationManager.Current.IsDialogOpen = true; + ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMessageAsync(this, NETworkManager.Localization.Resources.Strings.Error, - ex.Message, MessageDialogStyle.Affirmative, settings); + await _dialogCoordinator.ShowMessageAsync(this, NETworkManager.Localization.Resources.Strings.Error, + ex.Message, MessageDialogStyle.Affirmative, settings); - ConfigurationManager.Current.IsDialogOpen = false; - } + ConfigurationManager.Current.IsDialogOpen = false; } - - IsConnecting = false; } - private void Process_Exited(object sender, EventArgs e) - { - // This happens when the user exit the process - IsConnected = false; - } + IsConnecting = false; + } - public void FocusEmbeddedWindow() - { - if (IsConnected) - NativeMethods.SetForegroundWindow(_process.MainWindowHandle); - } + private void Process_Exited(object sender, EventArgs e) + { + // This happens when the user exit the process + IsConnected = false; + } - public void ResizeEmbeddedWindow() - { - if (IsConnected) - NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); - } + public void FocusEmbeddedWindow() + { + if (IsConnected) + NativeMethods.SetForegroundWindow(_process.MainWindowHandle); + } - public void Disconnect() - { - if (IsConnected) - _process.Kill(); - } + public void ResizeEmbeddedWindow() + { + if (IsConnected) + NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); + } - private void Reconnect() - { - if (IsConnected) - Disconnect(); + public void Disconnect() + { + if (IsConnected) + _process.Kill(); + } - Connect(); - } + private void Reconnect() + { + if (IsConnected) + Disconnect(); - public void RestartSession() - { - if (IsConnected) - NativeMethods.SendMessage(_process.MainWindowHandle, (uint)NativeMethods.WM.SYSCOMMAND, new IntPtr(64), new IntPtr(0)); - } + Connect(); + } - public void CloseTab() - { - _closing = true; + public void RestartSession() + { + if (IsConnected) + NativeMethods.SendMessage(_process.MainWindowHandle, (uint)NativeMethods.WM.SYSCOMMAND, new IntPtr(64), new IntPtr(0)); + } - Disconnect(); - } - #endregion + public void CloseTab() + { + _closing = true; - #region Events - private void WindowGrid_SizeChanged(object sender, SizeChangedEventArgs e) - { - if (IsConnected) - ResizeEmbeddedWindow(); - } - #endregion + Disconnect(); + } + #endregion + + #region Events + private void WindowGrid_SizeChanged(object sender, SizeChangedEventArgs e) + { + if (IsConnected) + ResizeEmbeddedWindow(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/Controls/RemoteDesktopControl.xaml.cs b/Source/NETworkManager/Controls/RemoteDesktopControl.xaml.cs index 479f61ba0a..e1000520e2 100644 --- a/Source/NETworkManager/Controls/RemoteDesktopControl.xaml.cs +++ b/Source/NETworkManager/Controls/RemoteDesktopControl.xaml.cs @@ -9,461 +9,460 @@ using System.Threading.Tasks; using NETworkManager.Utilities; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class RemoteDesktopControl : INotifyPropertyChanged { - public partial class RemoteDesktopControl : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private bool _initialized; + #region Variables + private bool _initialized; - private readonly RemoteDesktopSessionInfo _rdpSessionInfo; + private readonly RemoteDesktopSessionInfo _rdpSessionInfo; - // Fix WindowsFormsHost width - private double _rdpClientWidth; - public double RdpClientWidth + // Fix WindowsFormsHost width + private double _rdpClientWidth; + public double RdpClientWidth + { + get => _rdpClientWidth; + set { - get => _rdpClientWidth; - set - { - if (value == _rdpClientWidth) - return; - - _rdpClientWidth = value; - OnPropertyChanged(); - } - } + if (value == _rdpClientWidth) + return; - // Fix WindowsFormsHost height - private double _rdpClientHeight; - public double RdpClientHeight - { - get => _rdpClientHeight; - set - { - if (value == _rdpClientHeight) - return; - - _rdpClientHeight = value; - OnPropertyChanged(); - } + _rdpClientWidth = value; + OnPropertyChanged(); } + } - private bool _isConnected; - public bool IsConnected + // Fix WindowsFormsHost height + private double _rdpClientHeight; + public double RdpClientHeight + { + get => _rdpClientHeight; + set { - get => _isConnected; - set - { - if (value == _isConnected) - return; - - _isConnected = value; - OnPropertyChanged(); - } - } + if (value == _rdpClientHeight) + return; - private bool _isConnecting; - public bool IsConnecting - { - get => _isConnecting; - set - { - if (value == _isConnecting) - return; - - _isConnecting = value; - OnPropertyChanged(); - } + _rdpClientHeight = value; + OnPropertyChanged(); } + } - private string _disconnectReason; - public string DisconnectReason + private bool _isConnected; + public bool IsConnected + { + get => _isConnected; + set { - get => _disconnectReason; - set - { - if (value == _disconnectReason) - return; - - _disconnectReason = value; - OnPropertyChanged(); - } - } + if (value == _isConnected) + return; - private bool _isReconnecting; - public bool IsReconnecting - { - get => _isReconnecting; - set - { - if (value == _isReconnecting) - return; - - _isReconnecting = value; - OnPropertyChanged(); - } + _isConnected = value; + OnPropertyChanged(); } - #endregion + } - #region Constructor, load - public RemoteDesktopControl(RemoteDesktopSessionInfo info) + private bool _isConnecting; + public bool IsConnecting + { + get => _isConnecting; + set { - InitializeComponent(); - DataContext = this; - - _rdpSessionInfo = info; + if (value == _isConnecting) + return; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + _isConnecting = value; + OnPropertyChanged(); } + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) + private string _disconnectReason; + public string DisconnectReason + { + get => _disconnectReason; + set { - // Connect after the control is drawn and only on the first init - if (_initialized) + if (value == _disconnectReason) return; - Connect(); - _initialized = true; + _disconnectReason = value; + OnPropertyChanged(); } + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + private bool _isReconnecting; + public bool IsReconnecting + { + get => _isReconnecting; + set { - CloseTab(); - } - #endregion + if (value == _isReconnecting) + return; - #region ICommands & Actions - public ICommand ReconnectCommand - { - get { return new RelayCommand(p => ReconnectAction()); } + _isReconnecting = value; + OnPropertyChanged(); } + } + #endregion - private void ReconnectAction() - { - Reconnect(); - } + #region Constructor, load + public RemoteDesktopControl(RemoteDesktopSessionInfo info) + { + InitializeComponent(); + DataContext = this; - public ICommand DisconnectCommand - { - get { return new RelayCommand(p => DisconnectAction()); } - } + _rdpSessionInfo = info; - private void DisconnectAction() - { - Disconnect(); - } - #endregion + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - #region Methods - private void Connect() - { - IsConnecting = true; + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Connect after the control is drawn and only on the first init + if (_initialized) + return; - RdpClient.CreateControl(); + Connect(); + _initialized = true; + } - RdpClient.Server = _rdpSessionInfo.Hostname; - RdpClient.AdvancedSettings9.RDPPort = _rdpSessionInfo.Port; + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + CloseTab(); + } + #endregion - if (_rdpSessionInfo.CustomCredentials) - { - RdpClient.UserName = _rdpSessionInfo.Username; - RdpClient.AdvancedSettings9.ClearTextPassword = SecureStringHelper.ConvertToString(_rdpSessionInfo.Password); - } + #region ICommands & Actions + public ICommand ReconnectCommand + { + get { return new RelayCommand(p => ReconnectAction()); } + } - // AdvancedSettings - RdpClient.AdvancedSettings9.AuthenticationLevel = _rdpSessionInfo.AuthenticationLevel; - RdpClient.AdvancedSettings9.EnableCredSspSupport = _rdpSessionInfo.EnableCredSspSupport; + private void ReconnectAction() + { + Reconnect(); + } + + public ICommand DisconnectCommand + { + get { return new RelayCommand(p => DisconnectAction()); } + } - // Keyboard - RdpClient.SecuredSettings3.KeyboardHookMode = (int)_rdpSessionInfo.KeyboardHookMode; + private void DisconnectAction() + { + Disconnect(); + } + #endregion - // Devices and resources - RdpClient.AdvancedSettings9.RedirectClipboard = _rdpSessionInfo.RedirectClipboard; - RdpClient.AdvancedSettings9.RedirectDevices = _rdpSessionInfo.RedirectDevices; - RdpClient.AdvancedSettings9.RedirectDrives = _rdpSessionInfo.RedirectDrives; - RdpClient.AdvancedSettings9.RedirectPorts = _rdpSessionInfo.RedirectPorts; - RdpClient.AdvancedSettings9.RedirectSmartCards = _rdpSessionInfo.RedirectSmartCards; - RdpClient.AdvancedSettings9.RedirectPrinters = _rdpSessionInfo.RedirectPrinters; + #region Methods + private void Connect() + { + IsConnecting = true; - // Audio - RdpClient.AdvancedSettings9.AudioRedirectionMode = (uint)_rdpSessionInfo.AudioRedirectionMode; - RdpClient.AdvancedSettings9.AudioCaptureRedirectionMode = _rdpSessionInfo.AudioCaptureRedirectionMode == 0; + RdpClient.CreateControl(); - // Performance - RdpClient.AdvancedSettings9.BitmapPeristence = _rdpSessionInfo.PersistentBitmapCaching ? 1 : 0; - RdpClient.AdvancedSettings9.EnableAutoReconnect = _rdpSessionInfo.ReconnectIfTheConnectionIsDropped; + RdpClient.Server = _rdpSessionInfo.Hostname; + RdpClient.AdvancedSettings9.RDPPort = _rdpSessionInfo.Port; - // Experience - if (_rdpSessionInfo.NetworkConnectionType != 0) - { - RdpClient.AdvancedSettings9.NetworkConnectionType = (uint)_rdpSessionInfo.NetworkConnectionType; + if (_rdpSessionInfo.CustomCredentials) + { + RdpClient.UserName = _rdpSessionInfo.Username; + RdpClient.AdvancedSettings9.ClearTextPassword = SecureStringHelper.ConvertToString(_rdpSessionInfo.Password); + } - if (!_rdpSessionInfo.DesktopBackground) - RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_WALLPAPER; + // AdvancedSettings + RdpClient.AdvancedSettings9.AuthenticationLevel = _rdpSessionInfo.AuthenticationLevel; + RdpClient.AdvancedSettings9.EnableCredSspSupport = _rdpSessionInfo.EnableCredSspSupport; - if (_rdpSessionInfo.FontSmoothing) - RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_ENABLE_FONT_SMOOTHING; + // Keyboard + RdpClient.SecuredSettings3.KeyboardHookMode = (int)_rdpSessionInfo.KeyboardHookMode; - if (_rdpSessionInfo.DesktopComposition) - RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_ENABLE_DESKTOP_COMPOSITION; + // Devices and resources + RdpClient.AdvancedSettings9.RedirectClipboard = _rdpSessionInfo.RedirectClipboard; + RdpClient.AdvancedSettings9.RedirectDevices = _rdpSessionInfo.RedirectDevices; + RdpClient.AdvancedSettings9.RedirectDrives = _rdpSessionInfo.RedirectDrives; + RdpClient.AdvancedSettings9.RedirectPorts = _rdpSessionInfo.RedirectPorts; + RdpClient.AdvancedSettings9.RedirectSmartCards = _rdpSessionInfo.RedirectSmartCards; + RdpClient.AdvancedSettings9.RedirectPrinters = _rdpSessionInfo.RedirectPrinters; - if (!_rdpSessionInfo.ShowWindowContentsWhileDragging) - RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_FULLWINDOWDRAG; + // Audio + RdpClient.AdvancedSettings9.AudioRedirectionMode = (uint)_rdpSessionInfo.AudioRedirectionMode; + RdpClient.AdvancedSettings9.AudioCaptureRedirectionMode = _rdpSessionInfo.AudioCaptureRedirectionMode == 0; - if (!_rdpSessionInfo.MenuAndWindowAnimation) - RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_MENUANIMATIONS; + // Performance + RdpClient.AdvancedSettings9.BitmapPeristence = _rdpSessionInfo.PersistentBitmapCaching ? 1 : 0; + RdpClient.AdvancedSettings9.EnableAutoReconnect = _rdpSessionInfo.ReconnectIfTheConnectionIsDropped; - if (!_rdpSessionInfo.VisualStyles) - RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_THEMING; - } + // Experience + if (_rdpSessionInfo.NetworkConnectionType != 0) + { + RdpClient.AdvancedSettings9.NetworkConnectionType = (uint)_rdpSessionInfo.NetworkConnectionType; - // Display - RdpClient.ColorDepth = _rdpSessionInfo.ColorDepth; // 8, 15, 16, 24 + if (!_rdpSessionInfo.DesktopBackground) + RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_WALLPAPER; - if (_rdpSessionInfo.AdjustScreenAutomatically || _rdpSessionInfo.UseCurrentViewSize) - { - RdpClient.DesktopWidth = (int)RdpGrid.ActualWidth; - RdpClient.DesktopHeight = (int)RdpGrid.ActualHeight; - } - else - { - RdpClient.DesktopWidth = _rdpSessionInfo.DesktopWidth; - RdpClient.DesktopHeight = _rdpSessionInfo.DesktopHeight; - } + if (_rdpSessionInfo.FontSmoothing) + RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_ENABLE_FONT_SMOOTHING; - FixWindowsFormsHostSize(); + if (_rdpSessionInfo.DesktopComposition) + RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_ENABLE_DESKTOP_COMPOSITION; - // Events - RdpClient.OnConnected += RdpClient_OnConnected; - RdpClient.OnDisconnected += RdpClient_OnDisconnected; + if (!_rdpSessionInfo.ShowWindowContentsWhileDragging) + RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_FULLWINDOWDRAG; - RdpClient.AdvancedSettings9.EnableWindowsKey = 1; // Enable window key - RdpClient.AdvancedSettings9.allowBackgroundInput = 1; // Background input to send keystrokes like ctrl+alt+del + if (!_rdpSessionInfo.MenuAndWindowAnimation) + RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_MENUANIMATIONS; - RdpClient.Connect(); + if (!_rdpSessionInfo.VisualStyles) + RdpClient.AdvancedSettings9.PerformanceFlags |= RemoteDesktopPerformanceConstants.TS_PERF_DISABLE_THEMING; } - private void Reconnect() + // Display + RdpClient.ColorDepth = _rdpSessionInfo.ColorDepth; // 8, 15, 16, 24 + + if (_rdpSessionInfo.AdjustScreenAutomatically || _rdpSessionInfo.UseCurrentViewSize) { - if (IsConnected) - return; + RdpClient.DesktopWidth = (int)RdpGrid.ActualWidth; + RdpClient.DesktopHeight = (int)RdpGrid.ActualHeight; + } + else + { + RdpClient.DesktopWidth = _rdpSessionInfo.DesktopWidth; + RdpClient.DesktopHeight = _rdpSessionInfo.DesktopHeight; + } - IsConnecting = true; + FixWindowsFormsHostSize(); - if (_rdpSessionInfo.AdjustScreenAutomatically) - { - RdpClient.DesktopWidth = (int)RdpGrid.ActualWidth; - RdpClient.DesktopHeight = (int)RdpGrid.ActualHeight; - } + // Events + RdpClient.OnConnected += RdpClient_OnConnected; + RdpClient.OnDisconnected += RdpClient_OnDisconnected; - FixWindowsFormsHostSize(); + RdpClient.AdvancedSettings9.EnableWindowsKey = 1; // Enable window key + RdpClient.AdvancedSettings9.allowBackgroundInput = 1; // Background input to send keystrokes like ctrl+alt+del - RdpClient.Connect(); - } + RdpClient.Connect(); + } - public void FullScreen() - { - if (!IsConnected) - return; + private void Reconnect() + { + if (IsConnected) + return; - RdpClient.FullScreen = true; - } + IsConnecting = true; - public void AdjustScreen() + if (_rdpSessionInfo.AdjustScreenAutomatically) { - if (!IsConnected) - return; + RdpClient.DesktopWidth = (int)RdpGrid.ActualWidth; + RdpClient.DesktopHeight = (int)RdpGrid.ActualHeight; + } - RdpClient.Reconnect((uint)RdpGrid.ActualWidth, (uint)RdpGrid.ActualHeight); + FixWindowsFormsHostSize(); - FixWindowsFormsHostSize(); - } + RdpClient.Connect(); + } - private void FixWindowsFormsHostSize() - { - RdpClientWidth = RdpClient.DesktopWidth; - RdpClientHeight = RdpClient.DesktopHeight; - } + public void FullScreen() + { + if (!IsConnected) + return; - public void SendKey(Keystroke keystroke) - { - if (!IsConnected) - return; + RdpClient.FullScreen = true; + } - MSTSCLib.IMsRdpClientNonScriptable ocx = (MSTSCLib.IMsRdpClientNonScriptable)RdpClient.GetOcx(); + public void AdjustScreen() + { + if (!IsConnected) + return; - var info = RemoteDesktop.GetKeystroke(keystroke); + RdpClient.Reconnect((uint)RdpGrid.ActualWidth, (uint)RdpGrid.ActualHeight); - RdpClient.Focus(); + FixWindowsFormsHostSize(); + } - ocx.SendKeys(info.KeyData.Length, info.ArrayKeyUp, info.KeyData); - } + private void FixWindowsFormsHostSize() + { + RdpClientWidth = RdpClient.DesktopWidth; + RdpClientHeight = RdpClient.DesktopHeight; + } - private void Disconnect() - { - if (!IsConnected) - return; + public void SendKey(Keystroke keystroke) + { + if (!IsConnected) + return; - RdpClient.Disconnect(); - } + MSTSCLib.IMsRdpClientNonScriptable ocx = (MSTSCLib.IMsRdpClientNonScriptable)RdpClient.GetOcx(); - public void CloseTab() - { - Disconnect(); - } + var info = RemoteDesktop.GetKeystroke(keystroke); - private static string GetDisconnectReason(int reason) - { - switch (reason) - { - case 0: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_NoInfo; - case 1: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_LocalNotError; - case 2: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_RemoteByUser; - case 3: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ByServer; - case 4: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_TotalLoginTimeLimitReached; - case 260: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_DNSLookupFailed; - case 262: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_OutOfMemory; - case 264: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ConnectionTimedOut; - case 516: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SocketConnectFailed; - case 518: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_OutOfMemory2; - case 520: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_HostNotFound; - case 772: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_WinsockSendFailed; - case 774: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_OutOfMemory3; - case 776: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidIPAddr; - case 1028: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SocketRecvFailed; - case 1030: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidSecurityData; - case 1032: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InternalError; - case 1286: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidEncryption; - case 1288: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_DNSLookupFailed2; - case 1540: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_GetHostByNameFailed; - case 1542: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidServerSecurityInfo; - case 1544: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_TimerError; - case 1796: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_TimeoutOccurred; - case 1798: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ServerCertificateUnpackErr; - case 2052: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidIP; - case 2055: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrLogonFailure; - case 2056: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_LicensingFailed; - case 2308: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_AtClientWinsockFDCLOSE; - case 2310: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InternalSecurityError; - case 2312: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_LicensingTimeout; - case 2566: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InternalSecurityError2; - case 2567: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrNoSuchUser; - case 2822: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_EncryptionError; - case 2823: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountDisabled; - case 3078: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_DecryptionError; - case 3079: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountRestriction; - case 3080: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ClientDecompressionError; - case 3335: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountLockedOut; - case 3591: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountExpired; - case 3847: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrPasswordExpired; - case 4360: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_UnableToReconnectToRemoteSession; - case 4615: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrPasswordMustChange; - case 5639: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrDelegationPolicy; - case 5895: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrPolicyNTLMOnly; - case 6151: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrNoAuthenticatingAuthority; - case 6919: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrCertExpired; - case 7175: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrSmartcardWrongPIN; - case 8455: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrFreshCredRequiredByServer; - case 8711: - return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrSmartcardCardBlocked; - default: - return "Disconnect reason code " + reason + " not found in resources!" + Environment.NewLine + "(You can report this on GitHub)"; - } - } - #endregion + RdpClient.Focus(); - #region Events - private void RdpClient_OnConnected(object sender, EventArgs e) - { - IsConnected = true; - IsConnecting = false; - } + ocx.SendKeys(info.KeyData.Length, info.ArrayKeyUp, info.KeyData); + } - private void RdpClient_OnDisconnected(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e) - { - IsConnected = false; - IsConnecting = false; + private void Disconnect() + { + if (!IsConnected) + return; - DisconnectReason = GetDisconnectReason(e.discReason); - } + RdpClient.Disconnect(); + } - private void RdpGrid_SizeChanged(object sender, SizeChangedEventArgs e) + public void CloseTab() + { + Disconnect(); + } + + private static string GetDisconnectReason(int reason) + { + switch (reason) { - if (IsConnected && _rdpSessionInfo.AdjustScreenAutomatically && !IsReconnecting) - InitiateReconnection(); + case 0: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_NoInfo; + case 1: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_LocalNotError; + case 2: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_RemoteByUser; + case 3: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ByServer; + case 4: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_TotalLoginTimeLimitReached; + case 260: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_DNSLookupFailed; + case 262: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_OutOfMemory; + case 264: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ConnectionTimedOut; + case 516: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SocketConnectFailed; + case 518: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_OutOfMemory2; + case 520: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_HostNotFound; + case 772: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_WinsockSendFailed; + case 774: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_OutOfMemory3; + case 776: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidIPAddr; + case 1028: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SocketRecvFailed; + case 1030: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidSecurityData; + case 1032: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InternalError; + case 1286: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidEncryption; + case 1288: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_DNSLookupFailed2; + case 1540: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_GetHostByNameFailed; + case 1542: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidServerSecurityInfo; + case 1544: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_TimerError; + case 1796: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_TimeoutOccurred; + case 1798: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ServerCertificateUnpackErr; + case 2052: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InvalidIP; + case 2055: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrLogonFailure; + case 2056: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_LicensingFailed; + case 2308: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_AtClientWinsockFDCLOSE; + case 2310: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InternalSecurityError; + case 2312: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_LicensingTimeout; + case 2566: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_InternalSecurityError2; + case 2567: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrNoSuchUser; + case 2822: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_EncryptionError; + case 2823: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountDisabled; + case 3078: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_DecryptionError; + case 3079: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountRestriction; + case 3080: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_ClientDecompressionError; + case 3335: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountLockedOut; + case 3591: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrAccountExpired; + case 3847: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrPasswordExpired; + case 4360: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_UnableToReconnectToRemoteSession; + case 4615: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrPasswordMustChange; + case 5639: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrDelegationPolicy; + case 5895: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrPolicyNTLMOnly; + case 6151: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrNoAuthenticatingAuthority; + case 6919: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrCertExpired; + case 7175: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrSmartcardWrongPIN; + case 8455: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrFreshCredRequiredByServer; + case 8711: + return Localization.Resources.Strings.RemoteDesktopDisconnectReason_SslErrSmartcardCardBlocked; + default: + return "Disconnect reason code " + reason + " not found in resources!" + Environment.NewLine + "(You can report this on GitHub)"; } + } + #endregion - private async Task InitiateReconnection() - { - IsReconnecting = true; + #region Events + private void RdpClient_OnConnected(object sender, EventArgs e) + { + IsConnected = true; + IsConnecting = false; + } + + private void RdpClient_OnDisconnected(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e) + { + IsConnected = false; + IsConnecting = false; + + DisconnectReason = GetDisconnectReason(e.discReason); + } - do // Prevent to many requests - { - await Task.Delay(250); + private void RdpGrid_SizeChanged(object sender, SizeChangedEventArgs e) + { + if (IsConnected && _rdpSessionInfo.AdjustScreenAutomatically && !IsReconnecting) + InitiateReconnection(); + } - } while (Mouse.LeftButton == MouseButtonState.Pressed); + private async Task InitiateReconnection() + { + IsReconnecting = true; - AdjustScreen(); + do // Prevent to many requests + { + await Task.Delay(250); - IsReconnecting = false; - } - #endregion + } while (Mouse.LeftButton == MouseButtonState.Pressed); + + AdjustScreen(); + + IsReconnecting = false; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/Controls/TightVNCControl.xaml.cs b/Source/NETworkManager/Controls/TightVNCControl.xaml.cs index d429927d1d..9f5f37ea0d 100644 --- a/Source/NETworkManager/Controls/TightVNCControl.xaml.cs +++ b/Source/NETworkManager/Controls/TightVNCControl.xaml.cs @@ -13,243 +13,242 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.Settings; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class TigerVNCControl : INotifyPropertyChanged { - public partial class TigerVNCControl : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private bool _initialized; - private bool _closing; // When the tab is closed --> OnClose() + #region Variables + private bool _initialized; + private bool _closing; // When the tab is closed --> OnClose() - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - private readonly TigerVNCSessionInfo _sessionInfo; + private readonly TigerVNCSessionInfo _sessionInfo; - private Process _process; - private IntPtr _appWin; + private Process _process; + private IntPtr _appWin; - private bool _isConnected; - public bool IsConnected + private bool _isConnected; + public bool IsConnected + { + get => _isConnected; + set { - get => _isConnected; - set - { - if (value == _isConnected) - return; + if (value == _isConnected) + return; - _isConnected = value; - OnPropertyChanged(); - } + _isConnected = value; + OnPropertyChanged(); } + } - private bool _isConnecting; - public bool IsConnecting + private bool _isConnecting; + public bool IsConnecting + { + get => _isConnecting; + set { - get => _isConnecting; - set - { - if (value == _isConnecting) - return; + if (value == _isConnecting) + return; - _isConnecting = value; - OnPropertyChanged(); - } + _isConnecting = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load - public TigerVNCControl(TigerVNCSessionInfo info) - { - InitializeComponent(); - DataContext = this; + #region Constructor, load + public TigerVNCControl(TigerVNCSessionInfo info) + { + InitializeComponent(); + DataContext = this; - _dialogCoordinator = DialogCoordinator.Instance; + _dialogCoordinator = DialogCoordinator.Instance; - _sessionInfo = info; + _sessionInfo = info; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - // Connect after the control is drawn and only on the first init - if (_initialized) - return; + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Connect after the control is drawn and only on the first init + if (_initialized) + return; - // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly - WindowHost.Height = (int)ActualHeight; - WindowHost.Width = (int)ActualWidth; + // Fix: The control is not visible by default, thus height and width is not set. If the values are not set, the size does not scale properly + WindowHost.Height = (int)ActualHeight; + WindowHost.Width = (int)ActualWidth; - Connect(); + Connect(); - _initialized = true; - } + _initialized = true; + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) - { - CloseTab(); - } - #endregion + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + CloseTab(); + } + #endregion - #region ICommands & Actions - public ICommand ReconnectCommand - { - get { return new RelayCommand(p => ReconnectAction()); } - } + #region ICommands & Actions + public ICommand ReconnectCommand + { + get { return new RelayCommand(p => ReconnectAction()); } + } + + private void ReconnectAction() + { + Reconnect(); + } + #endregion - private void ReconnectAction() + #region Methods + private async Task Connect() + { + IsConnecting = true; + + var info = new ProcessStartInfo { - Reconnect(); - } - #endregion + FileName = _sessionInfo.ApplicationFilePath, + Arguments = TigerVNC.BuildCommandLine(_sessionInfo) + }; - #region Methods - private async Task Connect() + try { - IsConnecting = true; + _process = Process.Start(info); - var info = new ProcessStartInfo + if (_process != null) { - FileName = _sessionInfo.ApplicationFilePath, - Arguments = TigerVNC.BuildCommandLine(_sessionInfo) - }; + _process.EnableRaisingEvents = true; + _process.Exited += Process_Exited; - try - { - _process = Process.Start(info); + _appWin = _process.MainWindowHandle; - if (_process != null) + if (_appWin == IntPtr.Zero) { - _process.EnableRaisingEvents = true; - _process.Exited += Process_Exited; - - _appWin = _process.MainWindowHandle; + var startTime = DateTime.Now; - if (_appWin == IntPtr.Zero) + while ((DateTime.Now - startTime).TotalSeconds < 10) { - var startTime = DateTime.Now; + _process.Refresh(); - while ((DateTime.Now - startTime).TotalSeconds < 10) - { - _process.Refresh(); + if (_process.HasExited) + break; - if (_process.HasExited) - break; + _appWin = _process.MainWindowHandle; - _appWin = _process.MainWindowHandle; + if (IntPtr.Zero != _appWin) + break; - if (IntPtr.Zero != _appWin) - break; - - await Task.Delay(100); - } + await Task.Delay(100); } + } - if (_appWin != IntPtr.Zero) + if (_appWin != IntPtr.Zero) + { + while (!_process.HasExited && _process.MainWindowTitle.IndexOf(" - TigerVNC", StringComparison.Ordinal) == -1) { - while (!_process.HasExited && _process.MainWindowTitle.IndexOf(" - TigerVNC", StringComparison.Ordinal) == -1) - { - await Task.Delay(100); + await Task.Delay(100); - _process.Refresh(); - } + _process.Refresh(); + } - if (!_process.HasExited) - { - // Update the window handle, it changes when there is an authentication dialog - _appWin = _process.MainWindowHandle; + if (!_process.HasExited) + { + // Update the window handle, it changes when there is an authentication dialog + _appWin = _process.MainWindowHandle; - NativeMethods.SetParent(_appWin, WindowHost.Handle); + NativeMethods.SetParent(_appWin, WindowHost.Handle); - // Show window before set style and resize - NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); + // Show window before set style and resize + NativeMethods.ShowWindow(_appWin, NativeMethods.WindowShowStyle.Maximize); - // Remove border etc. - long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); - style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); // NativeMethods.WS_POPUP --> Overflow? (https://github.com/BornToBeRoot/NETworkManager/issues/167) - NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); + // Remove border etc. + long style = (int)NativeMethods.GetWindowLong(_appWin, NativeMethods.GWL_STYLE); + style &= ~(NativeMethods.WS_CAPTION | NativeMethods.WS_POPUP | NativeMethods.WS_THICKFRAME); // NativeMethods.WS_POPUP --> Overflow? (https://github.com/BornToBeRoot/NETworkManager/issues/167) + NativeMethods.SetWindowLongPtr(_appWin, NativeMethods.GWL_STYLE, new IntPtr(style)); - IsConnected = true; + IsConnected = true; - // Resize embedded application & refresh - // Requires a short delay because it's not applied immediately - await Task.Delay(250); - ResizeEmbeddedWindow(); - } + // Resize embedded application & refresh + // Requires a short delay because it's not applied immediately + await Task.Delay(250); + ResizeEmbeddedWindow(); } } - else - { - throw new Exception("Process could not be started!"); - } } - catch (Exception ex) + else { - if (!_closing) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - ConfigurationManager.Current.IsDialogOpen = true; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, - ex.Message, MessageDialogStyle.Affirmative, settings); - - ConfigurationManager.Current.IsDialogOpen = false; - } + throw new Exception("Process could not be started!"); } - - IsConnecting = false; } - - private void Process_Exited(object sender, EventArgs e) + catch (Exception ex) { - // This happens when the user exit the process - IsConnected = false; - } + if (!_closing) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + ConfigurationManager.Current.IsDialogOpen = true; - private void ResizeEmbeddedWindow() - { - if (IsConnected) - NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, + ex.Message, MessageDialogStyle.Affirmative, settings); - public void Disconnect() - { - if (IsConnected) - _process.Kill(); + ConfigurationManager.Current.IsDialogOpen = false; + } } - private void Reconnect() - { - if (IsConnected) - Disconnect(); + IsConnecting = false; + } - Connect(); - } + private void Process_Exited(object sender, EventArgs e) + { + // This happens when the user exit the process + IsConnected = false; + } - public void CloseTab() - { - _closing = true; + private void ResizeEmbeddedWindow() + { + if (IsConnected) + NativeMethods.SetWindowPos(_process.MainWindowHandle, IntPtr.Zero, 0, 0, WindowHost.ClientSize.Width, WindowHost.ClientSize.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE); + } + public void Disconnect() + { + if (IsConnected) + _process.Kill(); + } + + private void Reconnect() + { + if (IsConnected) Disconnect(); - } - #endregion - #region Events - private void TigerVNCGrid_SizeChanged(object sender, SizeChangedEventArgs e) - { - if (IsConnected) - ResizeEmbeddedWindow(); - } - #endregion + Connect(); + } + + public void CloseTab() + { + _closing = true; + + Disconnect(); + } + #endregion + + #region Events + private void TigerVNCGrid_SizeChanged(object sender, SizeChangedEventArgs e) + { + if (IsConnected) + ResizeEmbeddedWindow(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/Controls/WebConsoleControl.xaml.cs b/Source/NETworkManager/Controls/WebConsoleControl.xaml.cs index 34ff0d4129..26c1dcbea1 100644 --- a/Source/NETworkManager/Controls/WebConsoleControl.xaml.cs +++ b/Source/NETworkManager/Controls/WebConsoleControl.xaml.cs @@ -9,198 +9,197 @@ using Microsoft.Web.WebView2.Core; using NETworkManager.Settings; -namespace NETworkManager.Controls +namespace NETworkManager.Controls; + +public partial class WebConsoleControl : INotifyPropertyChanged { - public partial class WebConsoleControl : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private bool _initialized; + #region Variables + private bool _initialized; - private readonly WebConsoleSessionInfo _sessionInfo; + private readonly WebConsoleSessionInfo _sessionInfo; - private bool _isLoading; - public bool IsLoading + private bool _isLoading; + public bool IsLoading + { + get => _isLoading; + set { - get => _isLoading; - set - { - if (value == _isLoading) - return; - - _isLoading = value; - OnPropertyChanged(); - } + if (value == _isLoading) + return; + + _isLoading = value; + OnPropertyChanged(); } + } - private bool _firstLoad = true; - public bool FirstLoad + private bool _firstLoad = true; + public bool FirstLoad + { + get => _firstLoad; + set { - get => _firstLoad; - set - { - if (value == _firstLoad) - return; - - _firstLoad = value; - OnPropertyChanged(); - } + if (value == _firstLoad) + return; + + _firstLoad = value; + OnPropertyChanged(); } + } - private string _url; - public string Url + private string _url; + public string Url + { + get => _url; + set { - get => _url; - set - { - if (value == _url) - return; - - _url = value; - OnPropertyChanged(); - } + if (value == _url) + return; + + _url = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load - public WebConsoleControl(WebConsoleSessionInfo info) - { - InitializeComponent(); - DataContext = this; + #region Constructor, load + public WebConsoleControl(WebConsoleSessionInfo info) + { + InitializeComponent(); + DataContext = this; - _sessionInfo = info; + _sessionInfo = info; - Browser2.NavigationStarting += Browser2_NavigationStarting; - Browser2.NavigationCompleted += Browser2_NavigationCompleted; - Browser2.WebMessageReceived += Browser2_WebMessageReceived; + Browser2.NavigationStarting += Browser2_NavigationStarting; + Browser2.NavigationCompleted += Browser2_NavigationCompleted; + Browser2.WebMessageReceived += Browser2_WebMessageReceived; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private async void UserControl_Loaded(object sender, RoutedEventArgs e) - { - // Connect after the control is drawn and only on the first init - if (_initialized) - return; - - // Set user data folder - Fix #382 - var webView2Environment = await CoreWebView2Environment.CreateAsync(null, GlobalStaticConfiguration.WebConsole_Cache); - await Browser2.EnsureCoreWebView2Async(webView2Environment); + private async void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Connect after the control is drawn and only on the first init + if (_initialized) + return; + + // Set user data folder - Fix #382 + var webView2Environment = await CoreWebView2Environment.CreateAsync(null, GlobalStaticConfiguration.WebConsole_Cache); + await Browser2.EnsureCoreWebView2Async(webView2Environment); - Connect(); + Connect(); - _initialized = true; - } + _initialized = true; + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) - { - CloseTab(); - } - #endregion + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + CloseTab(); + } + #endregion - #region ICommands & Actions - public ICommand NavigateCommand - { - get { return new RelayCommand(p => NavigateAction(), NavigateCommand_CanExecute); } - } + #region ICommands & Actions + public ICommand NavigateCommand + { + get { return new RelayCommand(p => NavigateAction(), NavigateCommand_CanExecute); } + } - private bool NavigateCommand_CanExecute(object obj) - { - return !IsLoading; - } + private bool NavigateCommand_CanExecute(object obj) + { + return !IsLoading; + } - private void NavigateAction() - { - Browser2.CoreWebView2.Navigate(Url); - } + private void NavigateAction() + { + Browser2.CoreWebView2.Navigate(Url); + } - public ICommand ReloadCommand - { - get { return new RelayCommand(p => ReloadAction(), ReloadCommand_CanExecute); } - } + public ICommand ReloadCommand + { + get { return new RelayCommand(p => ReloadAction(), ReloadCommand_CanExecute); } + } - private bool ReloadCommand_CanExecute(object obj) - { - return !IsLoading; - } + private bool ReloadCommand_CanExecute(object obj) + { + return !IsLoading; + } - private void ReloadAction() - { - Browser2.Reload(); - } + private void ReloadAction() + { + Browser2.Reload(); + } - public ICommand GoBackCommand - { - get { return new RelayCommand(p => GoBackAction(), GoBackCommand_CanExecute); } - } + public ICommand GoBackCommand + { + get { return new RelayCommand(p => GoBackAction(), GoBackCommand_CanExecute); } + } - private bool GoBackCommand_CanExecute(object obj) - { - return !IsLoading && Browser2.CanGoBack; - } + private bool GoBackCommand_CanExecute(object obj) + { + return !IsLoading && Browser2.CanGoBack; + } - private void GoBackAction() - { - Browser2.GoBack(); - } + private void GoBackAction() + { + Browser2.GoBack(); + } - public ICommand GoForwardCommand - { - get { return new RelayCommand(p => GoForwardAction(), GoForwardCommand_CanExecute); } - } + public ICommand GoForwardCommand + { + get { return new RelayCommand(p => GoForwardAction(), GoForwardCommand_CanExecute); } + } - private bool GoForwardCommand_CanExecute(object obj) - { - return !IsLoading && Browser2.CanGoForward; - } + private bool GoForwardCommand_CanExecute(object obj) + { + return !IsLoading && Browser2.CanGoForward; + } - private void GoForwardAction() - { - Browser2.GoForward(); - } - #endregion + private void GoForwardAction() + { + Browser2.GoForward(); + } + #endregion - #region Methods - private void Connect() - { - Browser2.Source = new Uri(_sessionInfo.Url); - } + #region Methods + private void Connect() + { + Browser2.Source = new Uri(_sessionInfo.Url); + } - public void CloseTab() - { + public void CloseTab() + { - } - #endregion + } + #endregion - #region Events - private void Browser2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) - { - if (FirstLoad) - FirstLoad = false; + #region Events + private void Browser2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) + { + if (FirstLoad) + FirstLoad = false; - IsLoading = false; - } + IsLoading = false; + } - private void Browser2_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e) - { - IsLoading = true; + private void Browser2_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e) + { + IsLoading = true; - Url = e.Uri.ToString(); - } + Url = e.Uri.ToString(); + } - private void Browser2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) - { - string uri = e.TryGetWebMessageAsString(); - Url = uri; - } - #endregion + private void Browser2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) + { + string uri = e.TryGetWebMessageAsString(); + Url = uri; } + #endregion } diff --git a/Source/NETworkManager/MainWindow.xaml.cs b/Source/NETworkManager/MainWindow.xaml.cs index ed34edb6ab..e27326d907 100644 --- a/Source/NETworkManager/MainWindow.xaml.cs +++ b/Source/NETworkManager/MainWindow.xaml.cs @@ -37,1668 +37,1667 @@ using NETworkManager.Models.PowerShell; using log4net; -namespace NETworkManager +namespace NETworkManager; + +public partial class MainWindow : INotifyPropertyChanged { - public partial class MainWindow : INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private static readonly ILog _log = LogManager.GetLogger(typeof(MainWindow)); + #region Variables + private static readonly ILog _log = LogManager.GetLogger(typeof(MainWindow)); - private NotifyIcon _notifyIcon; - private StatusWindow _statusWindow; + private NotifyIcon _notifyIcon; + private StatusWindow _statusWindow; - private readonly bool _isLoading; - private bool _isProfileLoading; - private bool _isProfileUpdating; - private bool _isApplicationListLoading; - private bool _isNetworkChanging; + private readonly bool _isLoading; + private bool _isProfileLoading; + private bool _isProfileUpdating; + private bool _isApplicationListLoading; + private bool _isNetworkChanging; - private bool _isInTray; - private bool _closeApplication; + private bool _isInTray; + private bool _closeApplication; - private bool _expandApplicationView; - public bool ExpandApplicationView + private bool _expandApplicationView; + public bool ExpandApplicationView + { + get => _expandApplicationView; + set { - get => _expandApplicationView; - set - { - if (value == _expandApplicationView) - return; + if (value == _expandApplicationView) + return; - if (!_isLoading) - SettingsManager.Current.ExpandApplicationView = value; + if (!_isLoading) + SettingsManager.Current.ExpandApplicationView = value; - if (!value) - ClearSearchOnApplicationListMinimize(); + if (!value) + ClearSearchOnApplicationListMinimize(); - _expandApplicationView = value; - OnPropertyChanged(); - } + _expandApplicationView = value; + OnPropertyChanged(); } + } - private bool _isTextBoxSearchFocused; - public bool IsTextBoxSearchFocused + private bool _isTextBoxSearchFocused; + public bool IsTextBoxSearchFocused + { + get => _isTextBoxSearchFocused; + set { - get => _isTextBoxSearchFocused; - set - { - if (value == _isTextBoxSearchFocused) - return; + if (value == _isTextBoxSearchFocused) + return; - if (!value) - ClearSearchOnApplicationListMinimize(); + if (!value) + ClearSearchOnApplicationListMinimize(); - _isTextBoxSearchFocused = value; - OnPropertyChanged(); - } + _isTextBoxSearchFocused = value; + OnPropertyChanged(); } + } - private bool _isApplicationListOpen; - public bool IsApplicationListOpen + private bool _isApplicationListOpen; + public bool IsApplicationListOpen + { + get => _isApplicationListOpen; + set { - get => _isApplicationListOpen; - set - { - if (value == _isApplicationListOpen) - return; + if (value == _isApplicationListOpen) + return; - if (!value) - ClearSearchOnApplicationListMinimize(); + if (!value) + ClearSearchOnApplicationListMinimize(); - _isApplicationListOpen = value; - OnPropertyChanged(); - } + _isApplicationListOpen = value; + OnPropertyChanged(); } + } - private bool _isMouseOverApplicationList; - public bool IsMouseOverApplicationList + private bool _isMouseOverApplicationList; + public bool IsMouseOverApplicationList + { + get => _isMouseOverApplicationList; + set { - get => _isMouseOverApplicationList; - set - { - if (value == _isMouseOverApplicationList) - return; + if (value == _isMouseOverApplicationList) + return; - if (!value) - ClearSearchOnApplicationListMinimize(); + if (!value) + ClearSearchOnApplicationListMinimize(); - _isMouseOverApplicationList = value; - OnPropertyChanged(); - } + _isMouseOverApplicationList = value; + OnPropertyChanged(); } + } - private ICollectionView _applications; - public ICollectionView Applications + private ICollectionView _applications; + public ICollectionView Applications + { + get => _applications; + set { - get => _applications; - set - { - if (value == _applications) - return; + if (value == _applications) + return; - _applications = value; - OnPropertyChanged(); - } + _applications = value; + OnPropertyChanged(); } + } - private ApplicationInfo _selectedApplication; - public ApplicationInfo SelectedApplication + private ApplicationInfo _selectedApplication; + public ApplicationInfo SelectedApplication + { + get => _selectedApplication; + set { - get => _selectedApplication; - set - { - if (_isApplicationListLoading) - return; + if (_isApplicationListLoading) + return; - if (Equals(value, _selectedApplication)) - return; + if (Equals(value, _selectedApplication)) + return; - if (_selectedApplication != null) - OnApplicationViewHide(_selectedApplication.Name); + if (_selectedApplication != null) + OnApplicationViewHide(_selectedApplication.Name); - if (value != null) - OnApplicationViewVisible(value.Name); + if (value != null) + OnApplicationViewVisible(value.Name); - _selectedApplication = value; - OnPropertyChanged(); - } + _selectedApplication = value; + OnPropertyChanged(); } + } - private ApplicationName _filterLastViewName; - private int? _filterLastCount; + private ApplicationName _filterLastViewName; + private int? _filterLastCount; - private string _search = string.Empty; - public string Search + private string _search = string.Empty; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - if (SelectedApplication != null) - _filterLastViewName = SelectedApplication.Name; + if (SelectedApplication != null) + _filterLastViewName = SelectedApplication.Name; - Applications.Refresh(); + Applications.Refresh(); - var sourceCollection = Applications.SourceCollection.Cast(); - var filteredCollection = Applications.Cast(); + var sourceCollection = Applications.SourceCollection.Cast(); + var filteredCollection = Applications.Cast(); - var sourceInfos = sourceCollection as ApplicationInfo[] ?? sourceCollection.ToArray(); - var filteredInfos = filteredCollection as ApplicationInfo[] ?? filteredCollection.ToArray(); + var sourceInfos = sourceCollection as ApplicationInfo[] ?? sourceCollection.ToArray(); + var filteredInfos = filteredCollection as ApplicationInfo[] ?? filteredCollection.ToArray(); - if (_filterLastCount == null) - _filterLastCount = sourceInfos.Length; + if (_filterLastCount == null) + _filterLastCount = sourceInfos.Length; - SelectedApplication = _filterLastCount > filteredInfos.Length ? filteredInfos.FirstOrDefault() : sourceInfos.FirstOrDefault(x => x.Name == _filterLastViewName); + SelectedApplication = _filterLastCount > filteredInfos.Length ? filteredInfos.FirstOrDefault() : sourceInfos.FirstOrDefault(x => x.Name == _filterLastViewName); - _filterLastCount = filteredInfos.Length; + _filterLastCount = filteredInfos.Length; - // Show note when there was nothing found - SearchNothingFound = filteredInfos.Length == 0; + // Show note when there was nothing found + SearchNothingFound = filteredInfos.Length == 0; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _searchNothingFound; - public bool SearchNothingFound + private bool _searchNothingFound; + public bool SearchNothingFound + { + get => _searchNothingFound; + set { - get => _searchNothingFound; - set - { - if (value == _searchNothingFound) - return; + if (value == _searchNothingFound) + return; - _searchNothingFound = value; - OnPropertyChanged(); - } + _searchNothingFound = value; + OnPropertyChanged(); } + } - private SettingsView _settingsView; + private SettingsView _settingsView; - private bool _showSettingsView; - public bool ShowSettingsView + private bool _showSettingsView; + public bool ShowSettingsView + { + get => _showSettingsView; + set { - get => _showSettingsView; - set - { - if (value == _showSettingsView) - return; + if (value == _showSettingsView) + return; - _showSettingsView = value; - OnPropertyChanged(); - } + _showSettingsView = value; + OnPropertyChanged(); } + } - private bool _isRestartRequired; - public bool IsRestartRequired + private bool _isRestartRequired; + public bool IsRestartRequired + { + get => _isRestartRequired; + set { - get => _isRestartRequired; - set - { - if (value == _isRestartRequired) - return; + if (value == _isRestartRequired) + return; - _isRestartRequired = value; - OnPropertyChanged(); - } + _isRestartRequired = value; + OnPropertyChanged(); } + } - private bool _isUpdateAvailable; - public bool IsUpdateAvailable + private bool _isUpdateAvailable; + public bool IsUpdateAvailable + { + get => _isUpdateAvailable; + set { - get => _isUpdateAvailable; - set - { - if (value == _isUpdateAvailable) - return; + if (value == _isUpdateAvailable) + return; - _isUpdateAvailable = value; - OnPropertyChanged(); - } + _isUpdateAvailable = value; + OnPropertyChanged(); } + } - private string _updateReleaseUrl; - public string UpdateReleaseUrl + private string _updateReleaseUrl; + public string UpdateReleaseUrl + { + get => _updateReleaseUrl; + set { - get => _updateReleaseUrl; - set - { - if (value == _updateReleaseUrl) - return; + if (value == _updateReleaseUrl) + return; - _updateReleaseUrl = value; - OnPropertyChanged(); - } + _updateReleaseUrl = value; + OnPropertyChanged(); } + } - private ICollectionView _profileFiles; - public ICollectionView ProfileFiles + private ICollectionView _profileFiles; + public ICollectionView ProfileFiles + { + get => _profileFiles; + set { - get => _profileFiles; - set - { - if (value == _profileFiles) - return; + if (value == _profileFiles) + return; - _profileFiles = value; - OnPropertyChanged(); - } + _profileFiles = value; + OnPropertyChanged(); } + } - private ProfileFileInfo _selectedProfileFile = null; - public ProfileFileInfo SelectedProfileFile + private ProfileFileInfo _selectedProfileFile = null; + public ProfileFileInfo SelectedProfileFile + { + get => _selectedProfileFile; + set { - get => _selectedProfileFile; - set - { - if (_isProfileLoading) - return; - - if (value != null && value.Equals(_selectedProfileFile)) - return; + if (_isProfileLoading) + return; - _selectedProfileFile = value; + if (value != null && value.Equals(_selectedProfileFile)) + return; - if (value != null) - { - if (!_isProfileUpdating) - LoadProfile(value); + _selectedProfileFile = value; - if (SettingsManager.Current.Profiles_LastSelected != value.Name) - SettingsManager.Current.Profiles_LastSelected = value.Name; - } + if (value != null) + { + if (!_isProfileUpdating) + LoadProfile(value); - OnPropertyChanged(); + if (SettingsManager.Current.Profiles_LastSelected != value.Name) + SettingsManager.Current.Profiles_LastSelected = value.Name; } + + OnPropertyChanged(); } + } - private bool _isProfileFileDropDownOpened; - public bool IsProfileFileDropDownOpened + private bool _isProfileFileDropDownOpened; + public bool IsProfileFileDropDownOpened + { + get => _isProfileFileDropDownOpened; + set { - get => _isProfileFileDropDownOpened; - set - { - if (value == _isProfileFileDropDownOpened) - return; + if (value == _isProfileFileDropDownOpened) + return; - _isProfileFileDropDownOpened = value; - OnPropertyChanged(); - } + _isProfileFileDropDownOpened = value; + OnPropertyChanged(); } + } - private bool _isProfileFileLocked; - public bool IsProfileFileLocked + private bool _isProfileFileLocked; + public bool IsProfileFileLocked + { + get => _isProfileFileLocked; + set { - get => _isProfileFileLocked; - set - { - if (value == _isProfileFileLocked) - return; + if (value == _isProfileFileLocked) + return; - _isProfileFileLocked = value; - OnPropertyChanged(); - } + _isProfileFileLocked = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, window load and close events - public MainWindow() - { - _isLoading = true; + #region Constructor, window load and close events + public MainWindow() + { + _isLoading = true; - InitializeComponent(); - DataContext = this; + InitializeComponent(); + DataContext = this; - // Language Meta - LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(LocalizationManager.GetInstance().Culture.IetfLanguageTag))); + // Language Meta + LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(LocalizationManager.GetInstance().Culture.IetfLanguageTag))); - // Load and change appearance - AppearanceManager.Load(); + // Load and change appearance + AppearanceManager.Load(); - // Load and configure DNS - ConfigureDNS(); + // Load and configure DNS + ConfigureDNS(); - // Set window title - Title = $"NETworkManager {AssemblyManager.Current.Version}"; + // Set window title + Title = $"NETworkManager {AssemblyManager.Current.Version}"; - // Load settings - ExpandApplicationView = SettingsManager.Current.ExpandApplicationView; + // Load settings + ExpandApplicationView = SettingsManager.Current.ExpandApplicationView; - // Register event system... - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - //EventSystem.RedirectProfileToApplicationEvent += EventSystem_RedirectProfileToApplicationEvent; - EventSystem.OnRedirectDataToApplicationEvent += EventSystem_RedirectDataToApplicationEvent; - EventSystem.OnRedirectToSettingsEvent += EventSystem_RedirectToSettingsEvent; + // Register event system... + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + //EventSystem.RedirectProfileToApplicationEvent += EventSystem_RedirectProfileToApplicationEvent; + EventSystem.OnRedirectDataToApplicationEvent += EventSystem_RedirectDataToApplicationEvent; + EventSystem.OnRedirectToSettingsEvent += EventSystem_RedirectToSettingsEvent; - _isLoading = false; - } + _isLoading = false; + } - protected override async void OnContentRendered(EventArgs e) - { - base.OnContentRendered(e); + protected override async void OnContentRendered(EventArgs e) + { + base.OnContentRendered(e); - // Show a note if settings have been reset - if (ConfigurationManager.Current.ShowSettingsResetNoteOnStartup) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + // Show a note if settings have been reset + if (ConfigurationManager.Current.ShowSettingsResetNoteOnStartup) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - ConfigurationManager.Current.IsDialogOpen = true; + ConfigurationManager.Current.IsDialogOpen = true; - await this.ShowMessageAsync(Localization.Resources.Strings.SettingsHaveBeenReset, Localization.Resources.Strings.SettingsFileFoundWasCorruptOrNotCompatibleMessage, MessageDialogStyle.Affirmative, settings); + await this.ShowMessageAsync(Localization.Resources.Strings.SettingsHaveBeenReset, Localization.Resources.Strings.SettingsFileFoundWasCorruptOrNotCompatibleMessage, MessageDialogStyle.Affirmative, settings); - ConfigurationManager.Current.IsDialogOpen = false; - } + ConfigurationManager.Current.IsDialogOpen = false; + } - // Show a note on the first run - if (SettingsManager.Current.FirstRun) + // Show a note on the first run + if (SettingsManager.Current.FirstRun) + { + // Show first run dialog... + var customDialog = new CustomDialog { - // Show first run dialog... - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Welcome - }; + Title = Localization.Resources.Strings.Welcome + }; - var firstRunViewModel = new FirstRunViewModel(async instance => + var firstRunViewModel = new FirstRunViewModel(async instance => + { + await this.HideMetroDialogAsync(customDialog); + + // Set settings based on user choice + SettingsManager.Current.Update_CheckForUpdatesAtStartup = instance.CheckForUpdatesAtStartup; + SettingsManager.Current.Dashboard_CheckPublicIPAddress = instance.CheckPublicIPAddress; + SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile = instance.PowerShellModifyGlobalProfile; + + // Generate lists at runtime + SettingsManager.Current.General_ApplicationList = new ObservableSetCollection(ApplicationManager.GetList()); + SettingsManager.Current.IPScanner_CustomCommands = new ObservableCollection(IPScannerCustomCommand.GetDefaultList()); + SettingsManager.Current.PortScanner_PortProfiles = new ObservableCollection(PortProfile.GetDefaultList()); + SettingsManager.Current.DNSLookup_DNSServers_v2 = new ObservableCollection(DNSServer.GetDefaultList()); + SettingsManager.Current.AWSSessionManager_AWSProfiles = new ObservableCollection(AWSProfile.GetDefaultList()); + SettingsManager.Current.SNTPLookup_SNTPServers = new ObservableCollection(SNTPServer.GetDefaultList()); + + // Check if PowerShell is installed + foreach (var file in PowerShell.GetDefaultIntallationPaths) { - await this.HideMetroDialogAsync(customDialog); - - // Set settings based on user choice - SettingsManager.Current.Update_CheckForUpdatesAtStartup = instance.CheckForUpdatesAtStartup; - SettingsManager.Current.Dashboard_CheckPublicIPAddress = instance.CheckPublicIPAddress; - SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile = instance.PowerShellModifyGlobalProfile; - - // Generate lists at runtime - SettingsManager.Current.General_ApplicationList = new ObservableSetCollection(ApplicationManager.GetList()); - SettingsManager.Current.IPScanner_CustomCommands = new ObservableCollection(IPScannerCustomCommand.GetDefaultList()); - SettingsManager.Current.PortScanner_PortProfiles = new ObservableCollection(PortProfile.GetDefaultList()); - SettingsManager.Current.DNSLookup_DNSServers_v2 = new ObservableCollection(DNSServer.GetDefaultList()); - SettingsManager.Current.AWSSessionManager_AWSProfiles = new ObservableCollection(AWSProfile.GetDefaultList()); - SettingsManager.Current.SNTPLookup_SNTPServers = new ObservableCollection(SNTPServer.GetDefaultList()); - - // Check if PowerShell is installed - foreach (var file in PowerShell.GetDefaultIntallationPaths) + if (File.Exists(file)) { - if (File.Exists(file)) - { - SettingsManager.Current.PowerShell_ApplicationFilePath = file; - SettingsManager.Current.AWSSessionManager_ApplicationFilePath = file; + SettingsManager.Current.PowerShell_ApplicationFilePath = file; + SettingsManager.Current.AWSSessionManager_ApplicationFilePath = file; - break; - } + break; } + } - // Check if PuTTY is installed - foreach (var file in Models.PuTTY.PuTTY.GetDefaultInstallationPaths) + // Check if PuTTY is installed + foreach (var file in Models.PuTTY.PuTTY.GetDefaultInstallationPaths) + { + if (File.Exists(file)) { - if (File.Exists(file)) - { - SettingsManager.Current.PuTTY_ApplicationFilePath = file; - break; - } + SettingsManager.Current.PuTTY_ApplicationFilePath = file; + break; } + } - SettingsManager.Current.FirstRun = false; - - // Save it to create a settings file - SettingsManager.Save(); + SettingsManager.Current.FirstRun = false; - AfterContentRendered(); - }); + // Save it to create a settings file + SettingsManager.Save(); - customDialog.Content = new FirstRunDialog - { - DataContext = firstRunViewModel - }; + AfterContentRendered(); + }); - await this.ShowMetroDialogAsync(customDialog).ConfigureAwait(true); - } - else + customDialog.Content = new FirstRunDialog { - AfterContentRendered(); - } - } + DataContext = firstRunViewModel + }; - private void AfterContentRendered() + await this.ShowMetroDialogAsync(customDialog).ConfigureAwait(true); + } + else { - // Load the profiles before the applications are loaded so that we can use them (e.g. for synchronization) - LoadProfiles(); - - // Load application list, filter, sort, etc. - LoadApplicationList(); + AfterContentRendered(); + } + } - // Init notify icon - if (SettingsManager.Current.TrayIcon_AlwaysShowIcon) - InitNotifyIcon(); + private void AfterContentRendered() + { + // Load the profiles before the applications are loaded so that we can use them (e.g. for synchronization) + LoadProfiles(); - // Hide to tray after the window shows up... not nice, but otherwise the hotkeys do not work - if (CommandLineManager.Current.Autostart && SettingsManager.Current.Autostart_StartMinimizedInTray) - HideWindowToTray(); + // Load application list, filter, sort, etc. + LoadApplicationList(); - // Init status window - _statusWindow = new StatusWindow(this); + // Init notify icon + if (SettingsManager.Current.TrayIcon_AlwaysShowIcon) + InitNotifyIcon(); - // Detect network changes... - NetworkChange.NetworkAvailabilityChanged += (sender, args) => OnNetworkHasChanged(); - NetworkChange.NetworkAddressChanged += (sender, args) => OnNetworkHasChanged(); + // Hide to tray after the window shows up... not nice, but otherwise the hotkeys do not work + if (CommandLineManager.Current.Autostart && SettingsManager.Current.Autostart_StartMinimizedInTray) + HideWindowToTray(); - // Set PowerShell global profile - WriteDefaultPowerShellProfileToRegistry(); + // Init status window + _statusWindow = new StatusWindow(this); - // Search for updates... - if (SettingsManager.Current.Update_CheckForUpdatesAtStartup) - CheckForUpdates(); - } - private async void MetroWindowMain_Closing(object sender, CancelEventArgs e) - { - // Force restart --> e.g. Import or reset settings - // Restart --> e.g. change profile path - if (!_closeApplication && ConfigurationManager.Current.Restart) - { - e.Cancel = true; + // Detect network changes... + NetworkChange.NetworkAvailabilityChanged += (sender, args) => OnNetworkHasChanged(); + NetworkChange.NetworkAddressChanged += (sender, args) => OnNetworkHasChanged(); - RestartApplication(); + // Set PowerShell global profile + WriteDefaultPowerShellProfileToRegistry(); - return; - } + // Search for updates... + if (SettingsManager.Current.Update_CheckForUpdatesAtStartup) + CheckForUpdates(); + } + private async void MetroWindowMain_Closing(object sender, CancelEventArgs e) + { + // Force restart --> e.g. Import or reset settings + // Restart --> e.g. change profile path + if (!_closeApplication && ConfigurationManager.Current.Restart) + { + e.Cancel = true; - // Hide the application to tray - if (!_closeApplication && (SettingsManager.Current.Window_MinimizeInsteadOfTerminating && WindowState != WindowState.Minimized)) - { - e.Cancel = true; + RestartApplication(); - WindowState = WindowState.Minimized; + return; + } - return; - } + // Hide the application to tray + if (!_closeApplication && (SettingsManager.Current.Window_MinimizeInsteadOfTerminating && WindowState != WindowState.Minimized)) + { + e.Cancel = true; - // Confirm close - if (!_closeApplication && SettingsManager.Current.Window_ConfirmClose) - { - e.Cancel = true; + WindowState = WindowState.Minimized; - // If the window is minimized, bring it to front - if (WindowState == WindowState.Minimized) - BringWindowToFront(); + return; + } - var settings = AppearanceManager.MetroDialog; + // Confirm close + if (!_closeApplication && SettingsManager.Current.Window_ConfirmClose) + { + e.Cancel = true; - settings.AffirmativeButtonText = Localization.Resources.Strings.Close; - settings.NegativeButtonText = Localization.Resources.Strings.Cancel; - settings.DefaultButtonFocus = MessageDialogResult.Affirmative; + // If the window is minimized, bring it to front + if (WindowState == WindowState.Minimized) + BringWindowToFront(); - // Fix airspace issues - ConfigurationManager.Current.IsDialogOpen = true; + var settings = AppearanceManager.MetroDialog; - var result = await this.ShowMessageAsync(Localization.Resources.Strings.Confirm, Localization.Resources.Strings.ConfirmCloseMessage, MessageDialogStyle.AffirmativeAndNegative, settings); + settings.AffirmativeButtonText = Localization.Resources.Strings.Close; + settings.NegativeButtonText = Localization.Resources.Strings.Cancel; + settings.DefaultButtonFocus = MessageDialogResult.Affirmative; - ConfigurationManager.Current.IsDialogOpen = false; + // Fix airspace issues + ConfigurationManager.Current.IsDialogOpen = true; - if (result != MessageDialogResult.Affirmative) - return; + var result = await this.ShowMessageAsync(Localization.Resources.Strings.Confirm, Localization.Resources.Strings.ConfirmCloseMessage, MessageDialogStyle.AffirmativeAndNegative, settings); - _closeApplication = true; - Close(); + ConfigurationManager.Current.IsDialogOpen = false; + if (result != MessageDialogResult.Affirmative) return; - } - // Unregister HotKeys - if (_registeredHotKeys.Count > 0) - UnregisterHotKeys(); + _closeApplication = true; + Close(); - // Dispose the notify icon to prevent errors - _notifyIcon?.Dispose(); + return; } - #endregion - #region Application - private void LoadApplicationList() - { - _isApplicationListLoading = true; + // Unregister HotKeys + if (_registeredHotKeys.Count > 0) + UnregisterHotKeys(); - Applications = new CollectionViewSource { Source = SettingsManager.Current.General_ApplicationList }.View; - Applications.SortDescriptions.Add(new SortDescription(nameof(ApplicationInfo.Name), ListSortDirection.Ascending)); + // Dispose the notify icon to prevent errors + _notifyIcon?.Dispose(); + } + #endregion - Applications.Filter = o => - { - if (o is not ApplicationInfo info) - return false; + #region Application + private void LoadApplicationList() + { + _isApplicationListLoading = true; - if (string.IsNullOrEmpty(Search)) - return info.IsVisible; + Applications = new CollectionViewSource { Source = SettingsManager.Current.General_ApplicationList }.View; + Applications.SortDescriptions.Add(new SortDescription(nameof(ApplicationInfo.Name), ListSortDirection.Ascending)); - var regex = new Regex(@" |-"); + Applications.Filter = o => + { + if (o is not ApplicationInfo info) + return false; - var search = regex.Replace(Search, ""); + if (string.IsNullOrEmpty(Search)) + return info.IsVisible; - // Search by TranslatedName and Name - return info.IsVisible && (regex.Replace(ApplicationNameTranslator.GetInstance().Translate(info.Name), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || regex.Replace(info.Name.ToString(), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0); - }; + var regex = new Regex(@" |-"); - SettingsManager.Current.General_ApplicationList.CollectionChanged += (sender, args) => Applications.Refresh(); + var search = regex.Replace(Search, ""); - _isApplicationListLoading = false; + // Search by TranslatedName and Name + return info.IsVisible && (regex.Replace(ApplicationNameTranslator.GetInstance().Translate(info.Name), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || regex.Replace(info.Name.ToString(), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0); + }; - // Select the application - SelectedApplication = Applications.SourceCollection.Cast().FirstOrDefault(x => x.Name == (CommandLineManager.Current.Application != ApplicationName.None ? CommandLineManager.Current.Application : SettingsManager.Current.General_DefaultApplicationViewName)); + SettingsManager.Current.General_ApplicationList.CollectionChanged += (sender, args) => Applications.Refresh(); - // Scroll into view - if (SelectedApplication != null) - ListViewApplication.ScrollIntoView(SelectedApplication); - } + _isApplicationListLoading = false; - private DashboardView _dashboardView; - private NetworkInterfaceView _networkInterfaceView; - private WiFiView _wiFiView; - private IPScannerHostView _ipScannerHostView; - private PortScannerHostView _portScannerHostView; - private PingMonitorHostView _pingMonitorHostView; - private TracerouteHostView _tracerouteHostView; - private DNSLookupHostView _dnsLookupHostView; - private RemoteDesktopHostView _remoteDesktopHostView; - private PowerShellHostView _powerShellHostView; - private PuTTYHostView _puttyHostView; - private AWSSessionManagerHostView _awsSessionManagerHostView; - private TigerVNCHostView _tigerVNCHostView; - private WebConsoleHostView _webConsoleHostView; - private SNMPHostView _snmpHostView; - private SNTPLookupHostView _sntpLookupHostView; - private DiscoveryProtocolView _discoveryProtocolView; - private WakeOnLANView _wakeOnLanView; - private SubnetCalculatorHostView _subnetCalculatorHostView; - private BitCalculatorView _bitCalculatorView; - private LookupHostView _lookupHostView; - private WhoisHostView _whoisHostView; - private ConnectionsView _connectionsView; - private ListenersView _listenersView; - private ARPTableView _arpTableView; - - - /// - /// Method when the application view becomes visible (again). Either when switching the applications - /// or after opening and closing the settings. - /// - /// Name of the application - /// Indicates whether the settings were previously open - private void OnApplicationViewVisible(ApplicationName name, bool fromSettings = false) - { - switch (name) - { - case ApplicationName.Dashboard: - if (_dashboardView == null) - _dashboardView = new DashboardView(); - else - _dashboardView.OnViewVisible(); - - ContentControlApplication.Content = _dashboardView; - break; - case ApplicationName.NetworkInterface: - if (_networkInterfaceView == null) - _networkInterfaceView = new NetworkInterfaceView(); - else - _networkInterfaceView.OnViewVisible(); - - ContentControlApplication.Content = _networkInterfaceView; - break; - case ApplicationName.WiFi: - if (_wiFiView == null) - _wiFiView = new WiFiView(); - else - _wiFiView.OnViewVisible(); - - ContentControlApplication.Content = _wiFiView; - break; - case ApplicationName.IPScanner: - if (_ipScannerHostView == null) - _ipScannerHostView = new IPScannerHostView(); - else - _ipScannerHostView.OnViewVisible(); - - ContentControlApplication.Content = _ipScannerHostView; - break; - case ApplicationName.PortScanner: - if (_portScannerHostView == null) - _portScannerHostView = new PortScannerHostView(); - else - _portScannerHostView.OnViewVisible(); - - ContentControlApplication.Content = _portScannerHostView; - break; - case ApplicationName.PingMonitor: - if (_pingMonitorHostView == null) - _pingMonitorHostView = new PingMonitorHostView(); - else - _pingMonitorHostView.OnViewVisible(); - - ContentControlApplication.Content = _pingMonitorHostView; - break; - case ApplicationName.Traceroute: - if (_tracerouteHostView == null) - _tracerouteHostView = new TracerouteHostView(); - else - _tracerouteHostView.OnViewVisible(); - - ContentControlApplication.Content = _tracerouteHostView; - break; - case ApplicationName.DNSLookup: - if (_dnsLookupHostView == null) - _dnsLookupHostView = new DNSLookupHostView(); - else - _dnsLookupHostView.OnViewVisible(); - - ContentControlApplication.Content = _dnsLookupHostView; - break; - case ApplicationName.RemoteDesktop: - if (_remoteDesktopHostView == null) - _remoteDesktopHostView = new RemoteDesktopHostView(); - else - _remoteDesktopHostView.OnViewVisible(); - - ContentControlApplication.Content = _remoteDesktopHostView; - break; - case ApplicationName.PowerShell: - if (_powerShellHostView == null) - _powerShellHostView = new PowerShellHostView(); - else - _powerShellHostView.OnViewVisible(); - - ContentControlApplication.Content = _powerShellHostView; - break; - case ApplicationName.PuTTY: - if (_puttyHostView == null) - _puttyHostView = new PuTTYHostView(); - else - _puttyHostView.OnViewVisible(); - - ContentControlApplication.Content = _puttyHostView; - break; - case ApplicationName.AWSSessionManager: - if (_awsSessionManagerHostView == null) - _awsSessionManagerHostView = new AWSSessionManagerHostView(); - else - _awsSessionManagerHostView.OnViewVisible(fromSettings); - - ContentControlApplication.Content = _awsSessionManagerHostView; - break; - case ApplicationName.TigerVNC: - if (_tigerVNCHostView == null) - _tigerVNCHostView = new TigerVNCHostView(); - else - _tigerVNCHostView.OnViewVisible(); - - ContentControlApplication.Content = _tigerVNCHostView; - break; - case ApplicationName.WebConsole: - if (_webConsoleHostView == null) - _webConsoleHostView = new WebConsoleHostView(); - else - _webConsoleHostView.OnViewVisible(); - - ContentControlApplication.Content = _webConsoleHostView; - break; - case ApplicationName.SNMP: - if (_snmpHostView == null) - _snmpHostView = new SNMPHostView(); - else - _snmpHostView.OnViewVisible(); - - ContentControlApplication.Content = _snmpHostView; - break; - case ApplicationName.SNTPLookup: - if (_sntpLookupHostView == null) - _sntpLookupHostView = new SNTPLookupHostView(); - else - _sntpLookupHostView.OnViewVisible(); - - ContentControlApplication.Content = _sntpLookupHostView; - break; - case ApplicationName.DiscoveryProtocol: - if (_discoveryProtocolView == null) - _discoveryProtocolView = new DiscoveryProtocolView(); - else - _discoveryProtocolView.OnViewVisible(); - - ContentControlApplication.Content = _discoveryProtocolView; - break; - case ApplicationName.WakeOnLAN: - if (_wakeOnLanView == null) - _wakeOnLanView = new WakeOnLANView(); - else - _wakeOnLanView.OnViewVisible(); - - ContentControlApplication.Content = _wakeOnLanView; - break; - case ApplicationName.Whois: - if (_whoisHostView == null) - _whoisHostView = new WhoisHostView(); - else - _whoisHostView.OnViewVisible(); - - ContentControlApplication.Content = _whoisHostView; - break; - case ApplicationName.SubnetCalculator: - if (_subnetCalculatorHostView == null) - _subnetCalculatorHostView = new SubnetCalculatorHostView(); - else - _subnetCalculatorHostView.OnViewVisible(); - - ContentControlApplication.Content = _subnetCalculatorHostView; - break; - case ApplicationName.BitCalculator: - if (_bitCalculatorView == null) - _bitCalculatorView = new BitCalculatorView(); - else - _bitCalculatorView.OnViewVisible(); - - ContentControlApplication.Content = _bitCalculatorView; - break; - case ApplicationName.Lookup: - if (_lookupHostView == null) - _lookupHostView = new LookupHostView(); - else - _lookupHostView.OnViewVisible(); - - ContentControlApplication.Content = _lookupHostView; - break; - case ApplicationName.Connections: - if (_connectionsView == null) - _connectionsView = new ConnectionsView(); - else - _connectionsView.OnViewVisible(); - - ContentControlApplication.Content = _connectionsView; - break; - case ApplicationName.Listeners: - if (_listenersView == null) - _listenersView = new ListenersView(); - else - _listenersView.OnViewVisible(); - - ContentControlApplication.Content = _listenersView; - break; - case ApplicationName.ARPTable: - if (_arpTableView == null) - _arpTableView = new ARPTableView(); - else - _arpTableView.OnViewVisible(); - - ContentControlApplication.Content = _arpTableView; - break; - } - } + // Select the application + SelectedApplication = Applications.SourceCollection.Cast().FirstOrDefault(x => x.Name == (CommandLineManager.Current.Application != ApplicationName.None ? CommandLineManager.Current.Application : SettingsManager.Current.General_DefaultApplicationViewName)); - private void OnApplicationViewHide(ApplicationName name) - { - switch (name) - { - case ApplicationName.Dashboard: - _dashboardView?.OnViewHide(); - break; - case ApplicationName.NetworkInterface: - _networkInterfaceView?.OnViewHide(); - break; - case ApplicationName.WiFi: - _wiFiView?.OnViewHide(); - break; - case ApplicationName.IPScanner: - _ipScannerHostView?.OnViewHide(); - break; - case ApplicationName.PortScanner: - _portScannerHostView?.OnViewHide(); - break; - case ApplicationName.PingMonitor: - _pingMonitorHostView?.OnViewHide(); - break; - case ApplicationName.Traceroute: - _tracerouteHostView?.OnViewHide(); - break; - case ApplicationName.DNSLookup: - _dnsLookupHostView?.OnViewHide(); - break; - case ApplicationName.RemoteDesktop: - _remoteDesktopHostView?.OnViewHide(); - break; - case ApplicationName.PowerShell: - _powerShellHostView?.OnViewHide(); - break; - case ApplicationName.PuTTY: - _puttyHostView?.OnViewHide(); - break; - case ApplicationName.AWSSessionManager: - _awsSessionManagerHostView?.OnViewHide(); - break; - case ApplicationName.TigerVNC: - _tigerVNCHostView?.OnViewHide(); - break; - case ApplicationName.WebConsole: - _webConsoleHostView?.OnViewHide(); - break; - case ApplicationName.SNMP: - _snmpHostView?.OnViewHide(); - break; - case ApplicationName.SNTPLookup: - _sntpLookupHostView?.OnViewHide(); - break; - case ApplicationName.DiscoveryProtocol: - _discoveryProtocolView?.OnViewHide(); - break; - case ApplicationName.WakeOnLAN: - _wakeOnLanView?.OnViewHide(); - break; - case ApplicationName.Lookup: - _lookupHostView?.OnViewHide(); - break; - case ApplicationName.SubnetCalculator: - _subnetCalculatorHostView?.OnViewHide(); - break; - case ApplicationName.BitCalculator: - _bitCalculatorView?.OnViewHide(); - break; - case ApplicationName.Connections: - _connectionsView?.OnViewHide(); - break; - case ApplicationName.Listeners: - _listenersView?.OnViewHide(); - break; - case ApplicationName.ARPTable: - _arpTableView?.OnViewHide(); - break; - } - } + // Scroll into view + if (SelectedApplication != null) + ListViewApplication.ScrollIntoView(SelectedApplication); + } - private void ClearSearchOnApplicationListMinimize() + private DashboardView _dashboardView; + private NetworkInterfaceView _networkInterfaceView; + private WiFiView _wiFiView; + private IPScannerHostView _ipScannerHostView; + private PortScannerHostView _portScannerHostView; + private PingMonitorHostView _pingMonitorHostView; + private TracerouteHostView _tracerouteHostView; + private DNSLookupHostView _dnsLookupHostView; + private RemoteDesktopHostView _remoteDesktopHostView; + private PowerShellHostView _powerShellHostView; + private PuTTYHostView _puttyHostView; + private AWSSessionManagerHostView _awsSessionManagerHostView; + private TigerVNCHostView _tigerVNCHostView; + private WebConsoleHostView _webConsoleHostView; + private SNMPHostView _snmpHostView; + private SNTPLookupHostView _sntpLookupHostView; + private DiscoveryProtocolView _discoveryProtocolView; + private WakeOnLANView _wakeOnLanView; + private SubnetCalculatorHostView _subnetCalculatorHostView; + private BitCalculatorView _bitCalculatorView; + private LookupHostView _lookupHostView; + private WhoisHostView _whoisHostView; + private ConnectionsView _connectionsView; + private ListenersView _listenersView; + private ARPTableView _arpTableView; + + + /// + /// Method when the application view becomes visible (again). Either when switching the applications + /// or after opening and closing the settings. + /// + /// Name of the application + /// Indicates whether the settings were previously open + private void OnApplicationViewVisible(ApplicationName name, bool fromSettings = false) + { + switch (name) { - if (ExpandApplicationView) - return; + case ApplicationName.Dashboard: + if (_dashboardView == null) + _dashboardView = new DashboardView(); + else + _dashboardView.OnViewVisible(); - if (IsApplicationListOpen && IsTextBoxSearchFocused) - return; + ContentControlApplication.Content = _dashboardView; + break; + case ApplicationName.NetworkInterface: + if (_networkInterfaceView == null) + _networkInterfaceView = new NetworkInterfaceView(); + else + _networkInterfaceView.OnViewVisible(); - if (IsApplicationListOpen && IsMouseOverApplicationList) - return; + ContentControlApplication.Content = _networkInterfaceView; + break; + case ApplicationName.WiFi: + if (_wiFiView == null) + _wiFiView = new WiFiView(); + else + _wiFiView.OnViewVisible(); + + ContentControlApplication.Content = _wiFiView; + break; + case ApplicationName.IPScanner: + if (_ipScannerHostView == null) + _ipScannerHostView = new IPScannerHostView(); + else + _ipScannerHostView.OnViewVisible(); - Search = string.Empty; + ContentControlApplication.Content = _ipScannerHostView; + break; + case ApplicationName.PortScanner: + if (_portScannerHostView == null) + _portScannerHostView = new PortScannerHostView(); + else + _portScannerHostView.OnViewVisible(); - // Scroll into view - ListViewApplication.ScrollIntoView(SelectedApplication); - } + ContentControlApplication.Content = _portScannerHostView; + break; + case ApplicationName.PingMonitor: + if (_pingMonitorHostView == null) + _pingMonitorHostView = new PingMonitorHostView(); + else + _pingMonitorHostView.OnViewVisible(); - private void EventSystem_RedirectDataToApplicationEvent(object sender, EventArgs e) - { - if (e is not EventSystemRedirectArgs data) - return; + ContentControlApplication.Content = _pingMonitorHostView; + break; + case ApplicationName.Traceroute: + if (_tracerouteHostView == null) + _tracerouteHostView = new TracerouteHostView(); + else + _tracerouteHostView.OnViewVisible(); - // Change view - SelectedApplication = Applications.SourceCollection.Cast().FirstOrDefault(x => x.Name == data.Application); + ContentControlApplication.Content = _tracerouteHostView; + break; + case ApplicationName.DNSLookup: + if (_dnsLookupHostView == null) + _dnsLookupHostView = new DNSLookupHostView(); + else + _dnsLookupHostView.OnViewVisible(); - // Crate a new tab / perform action - switch (data.Application) - { - case ApplicationName.Dashboard: - break; - case ApplicationName.NetworkInterface: - break; - case ApplicationName.WiFi: - break; - case ApplicationName.IPScanner: - _ipScannerHostView.AddTab(data.Args); - break; - case ApplicationName.PortScanner: - _portScannerHostView.AddTab(data.Args); - break; - case ApplicationName.PingMonitor: - _pingMonitorHostView.AddHost(data.Args); - break; - case ApplicationName.Traceroute: - _tracerouteHostView.AddTab(data.Args); - break; - case ApplicationName.DNSLookup: - _dnsLookupHostView.AddTab(data.Args); - break; - case ApplicationName.RemoteDesktop: - _remoteDesktopHostView.AddTab(data.Args); - break; - case ApplicationName.PowerShell: - _powerShellHostView.AddTab(data.Args); - break; - case ApplicationName.PuTTY: - _puttyHostView.AddTab(data.Args); - break; - case ApplicationName.AWSSessionManager: - break; - case ApplicationName.TigerVNC: - _tigerVNCHostView.AddTab(data.Args); - break; - case ApplicationName.WebConsole: - break; - case ApplicationName.SNMP: - _snmpHostView.AddTab(data.Args); - break; - case ApplicationName.SNTPLookup: - break; - case ApplicationName.DiscoveryProtocol: - break; - case ApplicationName.WakeOnLAN: - break; - case ApplicationName.Whois: - break; - case ApplicationName.SubnetCalculator: - break; - case ApplicationName.BitCalculator: - break; - case ApplicationName.Lookup: - break; - case ApplicationName.Connections: - break; - case ApplicationName.Listeners: - break; - case ApplicationName.ARPTable: - break; - case ApplicationName.None: - break; - default: - throw new ArgumentOutOfRangeException(); - } - } - #endregion + ContentControlApplication.Content = _dnsLookupHostView; + break; + case ApplicationName.RemoteDesktop: + if (_remoteDesktopHostView == null) + _remoteDesktopHostView = new RemoteDesktopHostView(); + else + _remoteDesktopHostView.OnViewVisible(); - #region Settings - private void OpenSettings() - { - // Init settings view - if (_settingsView == null) - { - _settingsView = new SettingsView(SelectedApplication.Name); - ContentControlSettings.Content = _settingsView; - } - else // Change view - { - _settingsView.ChangeSettingsView(SelectedApplication.Name); - _settingsView.Refresh(); - } + ContentControlApplication.Content = _remoteDesktopHostView; + break; + case ApplicationName.PowerShell: + if (_powerShellHostView == null) + _powerShellHostView = new PowerShellHostView(); + else + _powerShellHostView.OnViewVisible(); - // Show the view (this will hide other content) - ShowSettingsView = true; - } + ContentControlApplication.Content = _powerShellHostView; + break; + case ApplicationName.PuTTY: + if (_puttyHostView == null) + _puttyHostView = new PuTTYHostView(); + else + _puttyHostView.OnViewVisible(); - private void EventSystem_RedirectToSettingsEvent(object sender, EventArgs e) - { - OpenSettings(); - } + ContentControlApplication.Content = _puttyHostView; + break; + case ApplicationName.AWSSessionManager: + if (_awsSessionManagerHostView == null) + _awsSessionManagerHostView = new AWSSessionManagerHostView(); + else + _awsSessionManagerHostView.OnViewVisible(fromSettings); - private void CloseSettings() - { - ShowSettingsView = false; + ContentControlApplication.Content = _awsSessionManagerHostView; + break; + case ApplicationName.TigerVNC: + if (_tigerVNCHostView == null) + _tigerVNCHostView = new TigerVNCHostView(); + else + _tigerVNCHostView.OnViewVisible(); - // Change HotKeys - if (SettingsManager.HotKeysChanged) - { - UnregisterHotKeys(); - RegisterHotKeys(); + ContentControlApplication.Content = _tigerVNCHostView; + break; + case ApplicationName.WebConsole: + if (_webConsoleHostView == null) + _webConsoleHostView = new WebConsoleHostView(); + else + _webConsoleHostView.OnViewVisible(); - SettingsManager.HotKeysChanged = false; - } + ContentControlApplication.Content = _webConsoleHostView; + break; + case ApplicationName.SNMP: + if (_snmpHostView == null) + _snmpHostView = new SNMPHostView(); + else + _snmpHostView.OnViewVisible(); - // Refresh the application view - OnApplicationViewVisible(SelectedApplication.Name, true); - } - #endregion + ContentControlApplication.Content = _snmpHostView; + break; + case ApplicationName.SNTPLookup: + if (_sntpLookupHostView == null) + _sntpLookupHostView = new SNTPLookupHostView(); + else + _sntpLookupHostView.OnViewVisible(); - #region Profiles - private void LoadProfiles() - { - _isProfileLoading = true; - ProfileFiles = new CollectionViewSource { Source = ProfileManager.ProfileFiles }.View; - ProfileFiles.SortDescriptions.Add(new SortDescription(nameof(ProfileFileInfo.Name), ListSortDirection.Ascending)); - _isProfileLoading = false; + ContentControlApplication.Content = _sntpLookupHostView; + break; + case ApplicationName.DiscoveryProtocol: + if (_discoveryProtocolView == null) + _discoveryProtocolView = new DiscoveryProtocolView(); + else + _discoveryProtocolView.OnViewVisible(); - ProfileManager.OnLoadedProfileFileChangedEvent += ProfileManager_OnLoadedProfileFileChangedEvent; - ProfileManager.OnSwitchProfileFileViaUIEvent += ProfileManager_OnSwitchProfileFileViaUIEvent; + ContentControlApplication.Content = _discoveryProtocolView; + break; + case ApplicationName.WakeOnLAN: + if (_wakeOnLanView == null) + _wakeOnLanView = new WakeOnLANView(); + else + _wakeOnLanView.OnViewVisible(); - SelectedProfileFile = ProfileFiles.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Profiles_LastSelected); - SelectedProfileFile ??= ProfileFiles.SourceCollection.Cast().FirstOrDefault(); - } - - private async Task LoadProfile(ProfileFileInfo info, bool showWrongPassword = false) - { - if (info.IsEncrypted && !info.IsPasswordValid) - { - IsProfileFileLocked = true; + ContentControlApplication.Content = _wakeOnLanView; + break; + case ApplicationName.Whois: + if (_whoisHostView == null) + _whoisHostView = new WhoisHostView(); + else + _whoisHostView.OnViewVisible(); - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.UnlockProfileFile - }; + ContentControlApplication.Content = _whoisHostView; + break; + case ApplicationName.SubnetCalculator: + if (_subnetCalculatorHostView == null) + _subnetCalculatorHostView = new SubnetCalculatorHostView(); + else + _subnetCalculatorHostView.OnViewVisible(); - var viewModel = new CredentialsPasswordProfileFileViewModel(async instance => - { - await this.HideMetroDialogAsync(customDialog); - ConfigurationManager.Current.IsDialogOpen = false; + ContentControlApplication.Content = _subnetCalculatorHostView; + break; + case ApplicationName.BitCalculator: + if (_bitCalculatorView == null) + _bitCalculatorView = new BitCalculatorView(); + else + _bitCalculatorView.OnViewVisible(); - info.Password = instance.Password; + ContentControlApplication.Content = _bitCalculatorView; + break; + case ApplicationName.Lookup: + if (_lookupHostView == null) + _lookupHostView = new LookupHostView(); + else + _lookupHostView.OnViewVisible(); - SwitchProfile(info); - }, async instance => - { - await this.HideMetroDialogAsync(customDialog); - ConfigurationManager.Current.IsDialogOpen = false; + ContentControlApplication.Content = _lookupHostView; + break; + case ApplicationName.Connections: + if (_connectionsView == null) + _connectionsView = new ConnectionsView(); + else + _connectionsView.OnViewVisible(); - ProfileManager.Unload(); - }, info.Name, showWrongPassword); + ContentControlApplication.Content = _connectionsView; + break; + case ApplicationName.Listeners: + if (_listenersView == null) + _listenersView = new ListenersView(); + else + _listenersView.OnViewVisible(); - customDialog.Content = new CredentialsPasswordProfileFileDialog - { - DataContext = viewModel - }; + ContentControlApplication.Content = _listenersView; + break; + case ApplicationName.ARPTable: + if (_arpTableView == null) + _arpTableView = new ARPTableView(); + else + _arpTableView.OnViewVisible(); - ConfigurationManager.Current.IsDialogOpen = true; - await this.ShowMetroDialogAsync(customDialog); - } - else - { - SwitchProfile(info); - } + ContentControlApplication.Content = _arpTableView; + break; } + } - private async Task SwitchProfile(ProfileFileInfo info) - { - try - { - ProfileManager.Switch(info); + private void OnApplicationViewHide(ApplicationName name) + { + switch (name) + { + case ApplicationName.Dashboard: + _dashboardView?.OnViewHide(); + break; + case ApplicationName.NetworkInterface: + _networkInterfaceView?.OnViewHide(); + break; + case ApplicationName.WiFi: + _wiFiView?.OnViewHide(); + break; + case ApplicationName.IPScanner: + _ipScannerHostView?.OnViewHide(); + break; + case ApplicationName.PortScanner: + _portScannerHostView?.OnViewHide(); + break; + case ApplicationName.PingMonitor: + _pingMonitorHostView?.OnViewHide(); + break; + case ApplicationName.Traceroute: + _tracerouteHostView?.OnViewHide(); + break; + case ApplicationName.DNSLookup: + _dnsLookupHostView?.OnViewHide(); + break; + case ApplicationName.RemoteDesktop: + _remoteDesktopHostView?.OnViewHide(); + break; + case ApplicationName.PowerShell: + _powerShellHostView?.OnViewHide(); + break; + case ApplicationName.PuTTY: + _puttyHostView?.OnViewHide(); + break; + case ApplicationName.AWSSessionManager: + _awsSessionManagerHostView?.OnViewHide(); + break; + case ApplicationName.TigerVNC: + _tigerVNCHostView?.OnViewHide(); + break; + case ApplicationName.WebConsole: + _webConsoleHostView?.OnViewHide(); + break; + case ApplicationName.SNMP: + _snmpHostView?.OnViewHide(); + break; + case ApplicationName.SNTPLookup: + _sntpLookupHostView?.OnViewHide(); + break; + case ApplicationName.DiscoveryProtocol: + _discoveryProtocolView?.OnViewHide(); + break; + case ApplicationName.WakeOnLAN: + _wakeOnLanView?.OnViewHide(); + break; + case ApplicationName.Lookup: + _lookupHostView?.OnViewHide(); + break; + case ApplicationName.SubnetCalculator: + _subnetCalculatorHostView?.OnViewHide(); + break; + case ApplicationName.BitCalculator: + _bitCalculatorView?.OnViewHide(); + break; + case ApplicationName.Connections: + _connectionsView?.OnViewHide(); + break; + case ApplicationName.Listeners: + _listenersView?.OnViewHide(); + break; + case ApplicationName.ARPTable: + _arpTableView?.OnViewHide(); + break; + } + } - IsProfileFileLocked = false; + private void ClearSearchOnApplicationListMinimize() + { + if (ExpandApplicationView) + return; - // Null if profile is loaded before application is loaded - if (SelectedApplication != null) - OnProfilesLoaded(SelectedApplication.Name); - } - catch (System.Security.Cryptography.CryptographicException) - { - // Wrong password, try again... - LoadProfile(info, true); - } - catch - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.Migrate; - settings.NegativeButtonText = Localization.Resources.Strings.Cancel; - settings.DefaultButtonFocus = MessageDialogResult.Affirmative; + if (IsApplicationListOpen && IsTextBoxSearchFocused) + return; - ConfigurationManager.Current.IsDialogOpen = true; + if (IsApplicationListOpen && IsMouseOverApplicationList) + return; - // ToDo: Improve Message - var result = await this.ShowMessageAsync(Localization.Resources.Strings.ProfileCouldNotBeLoaded, Localization.Resources.Strings.ProfileCouldNotBeLoadedMessage, MessageDialogStyle.AffirmativeAndNegative, settings); + Search = string.Empty; - ConfigurationManager.Current.IsDialogOpen = false; + // Scroll into view + ListViewApplication.ScrollIntoView(SelectedApplication); + } - if (result == MessageDialogResult.Affirmative) - { - ExternalProcessStarter.RunProcess("powershell.exe", $"-NoLogo -NoProfile -ExecutionPolicy ByPass -File \"{Path.Combine(ConfigurationManager.Current.ExecutionPath, "Resources", "Migrate-Profiles.ps1")}\" -Path \"{ProfileManager.GetProfilesFolderLocation()}\" -NETworkManagerPath \"{ConfigurationManager.Current.ApplicationFullName}\" -NETworkManagerVersion \"{AssemblyManager.Current.Version}\""); - CloseApplication(); - } - } + private void EventSystem_RedirectDataToApplicationEvent(object sender, EventArgs e) + { + if (e is not EventSystemRedirectArgs data) + return; + + // Change view + SelectedApplication = Applications.SourceCollection.Cast().FirstOrDefault(x => x.Name == data.Application); + + // Crate a new tab / perform action + switch (data.Application) + { + case ApplicationName.Dashboard: + break; + case ApplicationName.NetworkInterface: + break; + case ApplicationName.WiFi: + break; + case ApplicationName.IPScanner: + _ipScannerHostView.AddTab(data.Args); + break; + case ApplicationName.PortScanner: + _portScannerHostView.AddTab(data.Args); + break; + case ApplicationName.PingMonitor: + _pingMonitorHostView.AddHost(data.Args); + break; + case ApplicationName.Traceroute: + _tracerouteHostView.AddTab(data.Args); + break; + case ApplicationName.DNSLookup: + _dnsLookupHostView.AddTab(data.Args); + break; + case ApplicationName.RemoteDesktop: + _remoteDesktopHostView.AddTab(data.Args); + break; + case ApplicationName.PowerShell: + _powerShellHostView.AddTab(data.Args); + break; + case ApplicationName.PuTTY: + _puttyHostView.AddTab(data.Args); + break; + case ApplicationName.AWSSessionManager: + break; + case ApplicationName.TigerVNC: + _tigerVNCHostView.AddTab(data.Args); + break; + case ApplicationName.WebConsole: + break; + case ApplicationName.SNMP: + _snmpHostView.AddTab(data.Args); + break; + case ApplicationName.SNTPLookup: + break; + case ApplicationName.DiscoveryProtocol: + break; + case ApplicationName.WakeOnLAN: + break; + case ApplicationName.Whois: + break; + case ApplicationName.SubnetCalculator: + break; + case ApplicationName.BitCalculator: + break; + case ApplicationName.Lookup: + break; + case ApplicationName.Connections: + break; + case ApplicationName.Listeners: + break; + case ApplicationName.ARPTable: + break; + case ApplicationName.None: + break; + default: + throw new ArgumentOutOfRangeException(); } + } + #endregion - private void OnProfilesLoaded(ApplicationName name) + #region Settings + private void OpenSettings() + { + // Init settings view + if (_settingsView == null) { - switch (name) - { - case ApplicationName.AWSSessionManager: - _awsSessionManagerHostView?.OnProfileLoaded(); - break; - } + _settingsView = new SettingsView(SelectedApplication.Name); + ContentControlSettings.Content = _settingsView; } - - /// - /// Update the view when the loaded profile file changed - /// - /// - /// - private void ProfileManager_OnLoadedProfileFileChangedEvent(object sender, ProfileFileInfoArgs e) + else // Change view { - _isProfileUpdating = true; - - SelectedProfileFile = ProfileFiles.SourceCollection.Cast().FirstOrDefault(x => x.Equals(e.ProfileFileInfo)); - - _isProfileUpdating = false; + _settingsView.ChangeSettingsView(SelectedApplication.Name); + _settingsView.Refresh(); } - /// - /// Switch the profile from code behind via UI to get the password for encrypted files. - /// - /// - /// - private void ProfileManager_OnSwitchProfileFileViaUIEvent(object sender, ProfileFileInfoArgs e) - { - SelectedProfileFile = ProfileFiles.SourceCollection.Cast().FirstOrDefault(x => x.Equals(e.ProfileFileInfo)); - } - #endregion + // Show the view (this will hide other content) + ShowSettingsView = true; + } - #region Update check - private void CheckForUpdates() - { - var updater = new Updater(); + private void EventSystem_RedirectToSettingsEvent(object sender, EventArgs e) + { + OpenSettings(); + } - updater.UpdateAvailable += Updater_UpdateAvailable; - updater.Error += Updater_Error; - updater.CheckOnGitHub(Properties.Resources.NETworkManager_GitHub_User, Properties.Resources.NETworkManager_GitHub_Repo, AssemblyManager.Current.Version, SettingsManager.Current.Update_CheckForPreReleases); - } + private void CloseSettings() + { + ShowSettingsView = false; - private static void Updater_Error(object sender, EventArgs e) + // Change HotKeys + if (SettingsManager.HotKeysChanged) { - // Log - } + UnregisterHotKeys(); + RegisterHotKeys(); - private void Updater_UpdateAvailable(object sender, UpdateAvailableArgs e) - { - UpdateReleaseUrl = e.Release.Prerelease ? e.Release.HtmlUrl : Properties.Resources.NETworkManager_LatestReleaseUrl; - IsUpdateAvailable = true; + SettingsManager.HotKeysChanged = false; } - #endregion - #region Handle WndProc messages (Single instance, handle HotKeys) - private HwndSource _hwndSoure; - - // This is called after MainWindow() and before OnContentRendered() --> to register hotkeys... - protected override void OnSourceInitialized(EventArgs e) - { - base.OnSourceInitialized(e); + // Refresh the application view + OnApplicationViewVisible(SelectedApplication.Name, true); + } + #endregion - _hwndSoure = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); - _hwndSoure?.AddHook(HwndHook); + #region Profiles + private void LoadProfiles() + { + _isProfileLoading = true; + ProfileFiles = new CollectionViewSource { Source = ProfileManager.ProfileFiles }.View; + ProfileFiles.SortDescriptions.Add(new SortDescription(nameof(ProfileFileInfo.Name), ListSortDirection.Ascending)); + _isProfileLoading = false; - RegisterHotKeys(); - } + ProfileManager.OnLoadedProfileFileChangedEvent += ProfileManager_OnLoadedProfileFileChangedEvent; + ProfileManager.OnSwitchProfileFileViaUIEvent += ProfileManager_OnSwitchProfileFileViaUIEvent; - [DebuggerStepThrough] - private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + SelectedProfileFile = ProfileFiles.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Profiles_LastSelected); + SelectedProfileFile ??= ProfileFiles.SourceCollection.Cast().FirstOrDefault(); + } + + private async Task LoadProfile(ProfileFileInfo info, bool showWrongPassword = false) + { + if (info.IsEncrypted && !info.IsPasswordValid) { - // Single instance or Hotkey --> Show window - if (msg == SingleInstance.WM_SHOWME || msg == WmHotkey && wParam.ToInt32() == 1) + IsProfileFileLocked = true; + + var customDialog = new CustomDialog { - ShowWindow(); - handled = true; - } + Title = Localization.Resources.Strings.UnlockProfileFile + }; - return IntPtr.Zero; - } - #endregion + var viewModel = new CredentialsPasswordProfileFileViewModel(async instance => + { + await this.HideMetroDialogAsync(customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - #region Global HotKeys - [DllImport("user32.dll")] - private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk); - [DllImport("user32.dll")] - private static extern bool UnregisterHotKey(IntPtr hWnd, int id); + info.Password = instance.Password; - // WM_HOTKEY - private const int WmHotkey = 0x0312; + SwitchProfile(info); + }, async instance => + { + await this.HideMetroDialogAsync(customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - /* ID | Command - * ---|------------------- - * 1 | ShowWindow() - */ + ProfileManager.Unload(); + }, info.Name, showWrongPassword); - private readonly List _registeredHotKeys = new(); + customDialog.Content = new CredentialsPasswordProfileFileDialog + { + DataContext = viewModel + }; - private void RegisterHotKeys() + ConfigurationManager.Current.IsDialogOpen = true; + await this.ShowMetroDialogAsync(customDialog); + } + else { - if (SettingsManager.Current.HotKey_ShowWindowEnabled) - { - RegisterHotKey(new WindowInteropHelper(this).Handle, 1, SettingsManager.Current.HotKey_ShowWindowModifier, SettingsManager.Current.HotKey_ShowWindowKey); - _registeredHotKeys.Add(1); - } + SwitchProfile(info); } + } - private void UnregisterHotKeys() + private async Task SwitchProfile(ProfileFileInfo info) + { + try { - // Unregister all registred keys - foreach (var i in _registeredHotKeys) - UnregisterHotKey(new WindowInteropHelper(this).Handle, i); + ProfileManager.Switch(info); - // Clear list - _registeredHotKeys.Clear(); - } - #endregion + IsProfileFileLocked = false; - #region NotifyIcon - private void InitNotifyIcon() + // Null if profile is loaded before application is loaded + if (SelectedApplication != null) + OnProfilesLoaded(SelectedApplication.Name); + } + catch (System.Security.Cryptography.CryptographicException) { - _notifyIcon = new NotifyIcon(); + // Wrong password, try again... + LoadProfile(info, true); + } + catch + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.Migrate; + settings.NegativeButtonText = Localization.Resources.Strings.Cancel; + settings.DefaultButtonFocus = MessageDialogResult.Affirmative; + + ConfigurationManager.Current.IsDialogOpen = true; + + // ToDo: Improve Message + var result = await this.ShowMessageAsync(Localization.Resources.Strings.ProfileCouldNotBeLoaded, Localization.Resources.Strings.ProfileCouldNotBeLoadedMessage, MessageDialogStyle.AffirmativeAndNegative, settings); + + ConfigurationManager.Current.IsDialogOpen = false; - // Get the application icon for the tray - using (var iconStream = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/NETworkManager.ico"))?.Stream) + if (result == MessageDialogResult.Affirmative) { - if (iconStream != null) - _notifyIcon.Icon = new Icon(iconStream); + ExternalProcessStarter.RunProcess("powershell.exe", $"-NoLogo -NoProfile -ExecutionPolicy ByPass -File \"{Path.Combine(ConfigurationManager.Current.ExecutionPath, "Resources", "Migrate-Profiles.ps1")}\" -Path \"{ProfileManager.GetProfilesFolderLocation()}\" -NETworkManagerPath \"{ConfigurationManager.Current.ApplicationFullName}\" -NETworkManagerVersion \"{AssemblyManager.Current.Version}\""); + CloseApplication(); } - - _notifyIcon.Text = Title; - _notifyIcon.Click += NotifyIcon_Click; - _notifyIcon.MouseDown += NotifyIcon_MouseDown; - _notifyIcon.Visible = true; } + } - private void NotifyIcon_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) + private void OnProfilesLoaded(ApplicationName name) + { + switch (name) { - if (e.Button != MouseButtons.Right) - return; + case ApplicationName.AWSSessionManager: + _awsSessionManagerHostView?.OnProfileLoaded(); + break; + } + } - var trayMenu = (ContextMenu)FindResource("ContextMenuNotifyIcon"); + /// + /// Update the view when the loaded profile file changed + /// + /// + /// + private void ProfileManager_OnLoadedProfileFileChangedEvent(object sender, ProfileFileInfoArgs e) + { + _isProfileUpdating = true; - trayMenu.IsOpen = true; - } + SelectedProfileFile = ProfileFiles.SourceCollection.Cast().FirstOrDefault(x => x.Equals(e.ProfileFileInfo)); - private void NotifyIcon_Click(object sender, EventArgs e) - { - System.Windows.Forms.MouseEventArgs mouse = (System.Windows.Forms.MouseEventArgs)e; + _isProfileUpdating = false; + } - if (mouse.Button != MouseButtons.Left) - return; + /// + /// Switch the profile from code behind via UI to get the password for encrypted files. + /// + /// + /// + private void ProfileManager_OnSwitchProfileFileViaUIEvent(object sender, ProfileFileInfoArgs e) + { + SelectedProfileFile = ProfileFiles.SourceCollection.Cast().FirstOrDefault(x => x.Equals(e.ProfileFileInfo)); + } + #endregion - if (OpenStatusWindowCommand.CanExecute(null)) - OpenStatusWindowCommand.Execute(null); - } + #region Update check + private void CheckForUpdates() + { + var updater = new Updater(); - private void MetroWindowMain_StateChanged(object sender, EventArgs e) - { - if (WindowState != WindowState.Minimized) - return; + updater.UpdateAvailable += Updater_UpdateAvailable; + updater.Error += Updater_Error; + updater.CheckOnGitHub(Properties.Resources.NETworkManager_GitHub_User, Properties.Resources.NETworkManager_GitHub_Repo, AssemblyManager.Current.Version, SettingsManager.Current.Update_CheckForPreReleases); + } - if (SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar) - HideWindowToTray(); - } + private static void Updater_Error(object sender, EventArgs e) + { + // Log + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = this; - } - #endregion + private void Updater_UpdateAvailable(object sender, UpdateAvailableArgs e) + { + UpdateReleaseUrl = e.Release.Prerelease ? e.Release.HtmlUrl : Properties.Resources.NETworkManager_LatestReleaseUrl; + IsUpdateAvailable = true; + } + #endregion - #region ICommands & Actions - public ICommand OpenStatusWindowCommand => new RelayCommand(p => OpenStatusWindowAction()); + #region Handle WndProc messages (Single instance, handle HotKeys) + private HwndSource _hwndSoure; - private void OpenStatusWindowAction() - { - OpenStatusWindow(true); - } + // This is called after MainWindow() and before OnContentRendered() --> to register hotkeys... + protected override void OnSourceInitialized(EventArgs e) + { + base.OnSourceInitialized(e); + + _hwndSoure = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); + _hwndSoure?.AddHook(HwndHook); - public ICommand RestartApplicationCommand => new RelayCommand(p => RestartApplicationAction()); + RegisterHotKeys(); + } - private void RestartApplicationAction() + [DebuggerStepThrough] + private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + // Single instance or Hotkey --> Show window + if (msg == SingleInstance.WM_SHOWME || msg == WmHotkey && wParam.ToInt32() == 1) { - RestartApplication(); + ShowWindow(); + handled = true; } - public ICommand OpenWebsiteCommand => new RelayCommand(OpenWebsiteAction); + return IntPtr.Zero; + } + #endregion - private static void OpenWebsiteAction(object url) - { - ExternalProcessStarter.OpenUrl((string)url); - } + #region Global HotKeys + [DllImport("user32.dll")] + private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk); + [DllImport("user32.dll")] + private static extern bool UnregisterHotKey(IntPtr hWnd, int id); - public ICommand OpenDocumentationCommand => new RelayCommand(p => OpenDocumentationAction()); + // WM_HOTKEY + private const int WmHotkey = 0x0312; - private void OpenDocumentationAction() - { - DocumentationManager.OpenDocumentation(ShowSettingsView ? _settingsView.GetDocumentationIdentifier() : DocumentationManager.GetIdentifierByAppliactionName(SelectedApplication.Name)); - } + /* ID | Command + * ---|------------------- + * 1 | ShowWindow() + */ - public ICommand OpenApplicationListCommand => new RelayCommand(p => OpenApplicationListAction()); + private readonly List _registeredHotKeys = new(); - private void OpenApplicationListAction() + private void RegisterHotKeys() + { + if (SettingsManager.Current.HotKey_ShowWindowEnabled) { - IsApplicationListOpen = true; - TextBoxSearch.Focus(); + RegisterHotKey(new WindowInteropHelper(this).Handle, 1, SettingsManager.Current.HotKey_ShowWindowModifier, SettingsManager.Current.HotKey_ShowWindowKey); + _registeredHotKeys.Add(1); } + } - public ICommand UnlockProfileCommand => new RelayCommand(p => UnlockProfileAction()); + private void UnregisterHotKeys() + { + // Unregister all registred keys + foreach (var i in _registeredHotKeys) + UnregisterHotKey(new WindowInteropHelper(this).Handle, i); - private void UnlockProfileAction() - { - LoadProfile(SelectedProfileFile); - } + // Clear list + _registeredHotKeys.Clear(); + } + #endregion - public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); + #region NotifyIcon + private void InitNotifyIcon() + { + _notifyIcon = new NotifyIcon(); - private void OpenSettingsAction() + // Get the application icon for the tray + using (var iconStream = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/NETworkManager.ico"))?.Stream) { - OpenSettings(); + if (iconStream != null) + _notifyIcon.Icon = new Icon(iconStream); } - public ICommand OpenSettingsFromTrayCommand => new RelayCommand(p => OpenSettingsFromTrayAction()); + _notifyIcon.Text = Title; + _notifyIcon.Click += NotifyIcon_Click; + _notifyIcon.MouseDown += NotifyIcon_MouseDown; + _notifyIcon.Visible = true; + } - private void OpenSettingsFromTrayAction() - { - // Bring window to front - ShowWindow(); + private void NotifyIcon_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) + { + if (e.Button != MouseButtons.Right) + return; - OpenSettings(); - } + var trayMenu = (ContextMenu)FindResource("ContextMenuNotifyIcon"); - public ICommand CloseSettingsCommand => new RelayCommand(p => CloseSettingsAction()); + trayMenu.IsOpen = true; + } - private void CloseSettingsAction() - { - CloseSettings(); - } + private void NotifyIcon_Click(object sender, EventArgs e) + { + System.Windows.Forms.MouseEventArgs mouse = (System.Windows.Forms.MouseEventArgs)e; - public ICommand ShowWindowCommand => new RelayCommand(p => ShowWindowAction()); + if (mouse.Button != MouseButtons.Left) + return; - private void ShowWindowAction() - { - ShowWindow(); - } + if (OpenStatusWindowCommand.CanExecute(null)) + OpenStatusWindowCommand.Execute(null); + } - public ICommand CloseApplicationCommand => new RelayCommand(p => CloseApplicationAction()); + private void MetroWindowMain_StateChanged(object sender, EventArgs e) + { + if (WindowState != WindowState.Minimized) + return; - private void CloseApplicationAction() - { - CloseApplication(); - } + if (SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar) + HideWindowToTray(); + } - public void CloseApplication() - { - _closeApplication = true; + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = this; + } + #endregion - // Make it thread safe when it's called inside a dialog - System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Close(); - })); - } + #region ICommands & Actions + public ICommand OpenStatusWindowCommand => new RelayCommand(p => OpenStatusWindowAction()); - public void RestartApplication(bool asAdmin = false) - { - ExternalProcessStarter.RunProcess(ConfigurationManager.Current.ApplicationFullName, $"{CommandLineManager.GetParameterWithSplitIdentifier(CommandLineManager.ParameterRestartPid)}{Process.GetCurrentProcess().Id} {CommandLineManager.GetParameterWithSplitIdentifier(CommandLineManager.ParameterApplication)}{SelectedApplication.Name}", asAdmin); + private void OpenStatusWindowAction() + { + OpenStatusWindow(true); + } - CloseApplication(); - } + public ICommand RestartApplicationCommand => new RelayCommand(p => RestartApplicationAction()); - public ICommand ApplicationListMouseEnterCommand => new RelayCommand(p => ApplicationListMouseEnterAction()); + private void RestartApplicationAction() + { + RestartApplication(); + } - private void ApplicationListMouseEnterAction() - { - IsMouseOverApplicationList = true; - } + public ICommand OpenWebsiteCommand => new RelayCommand(OpenWebsiteAction); - public ICommand ApplicationListMouseLeaveCommand => new RelayCommand(p => ApplicationListMouseLeaveAction()); + private static void OpenWebsiteAction(object url) + { + ExternalProcessStarter.OpenUrl((string)url); + } - private void ApplicationListMouseLeaveAction() - { - // Don't minmize the list, if the user has accidently moved the mouse while searching - if (!IsTextBoxSearchFocused) - IsApplicationListOpen = false; + public ICommand OpenDocumentationCommand => new RelayCommand(p => OpenDocumentationAction()); - IsMouseOverApplicationList = false; - } + private void OpenDocumentationAction() + { + DocumentationManager.OpenDocumentation(ShowSettingsView ? _settingsView.GetDocumentationIdentifier() : DocumentationManager.GetIdentifierByAppliactionName(SelectedApplication.Name)); + } - public ICommand TextBoxSearchGotFocusCommand => new RelayCommand(p => TextBoxSearchGotFocusAction()); + public ICommand OpenApplicationListCommand => new RelayCommand(p => OpenApplicationListAction()); - private void TextBoxSearchGotFocusAction() - { - IsTextBoxSearchFocused = true; - } + private void OpenApplicationListAction() + { + IsApplicationListOpen = true; + TextBoxSearch.Focus(); + } - public ICommand TextBoxSearchLostFocusCommand => new RelayCommand(p => TextBoxSearchLostFocusAction()); + public ICommand UnlockProfileCommand => new RelayCommand(p => UnlockProfileAction()); - private void TextBoxSearchLostFocusAction() - { - if (!IsMouseOverApplicationList) - IsApplicationListOpen = false; + private void UnlockProfileAction() + { + LoadProfile(SelectedProfileFile); + } - IsTextBoxSearchFocused = false; - } + public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + private void OpenSettingsAction() + { + OpenSettings(); + } - private void ClearSearchAction() - { - Search = string.Empty; - } - #endregion + public ICommand OpenSettingsFromTrayCommand => new RelayCommand(p => OpenSettingsFromTrayAction()); - #region Methods - private void ShowWindow() - { - if (_isInTray) - ShowWindowFromTray(); + private void OpenSettingsFromTrayAction() + { + // Bring window to front + ShowWindow(); - if (!IsActive) - BringWindowToFront(); - } + OpenSettings(); + } - private void HideWindowToTray() - { - if (_notifyIcon == null) - InitNotifyIcon(); + public ICommand CloseSettingsCommand => new RelayCommand(p => CloseSettingsAction()); - _isInTray = true; + private void CloseSettingsAction() + { + CloseSettings(); + } - _notifyIcon.Visible = true; + public ICommand ShowWindowCommand => new RelayCommand(p => ShowWindowAction()); - Hide(); - } + private void ShowWindowAction() + { + ShowWindow(); + } - private void ShowWindowFromTray() - { - _isInTray = false; + public ICommand CloseApplicationCommand => new RelayCommand(p => CloseApplicationAction()); - Show(); + private void CloseApplicationAction() + { + CloseApplication(); + } - _notifyIcon.Visible = SettingsManager.Current.TrayIcon_AlwaysShowIcon; - } + public void CloseApplication() + { + _closeApplication = true; - private void BringWindowToFront() + // Make it thread safe when it's called inside a dialog + System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - if (WindowState == WindowState.Minimized) - WindowState = WindowState.Normal; + Close(); + })); + } - Activate(); - } + public void RestartApplication(bool asAdmin = false) + { + ExternalProcessStarter.RunProcess(ConfigurationManager.Current.ApplicationFullName, $"{CommandLineManager.GetParameterWithSplitIdentifier(CommandLineManager.ParameterRestartPid)}{Process.GetCurrentProcess().Id} {CommandLineManager.GetParameterWithSplitIdentifier(CommandLineManager.ParameterApplication)}{SelectedApplication.Name}", asAdmin); - private void ConfigureDNS() - { - _log.Info("Configure application DNS..."); + CloseApplication(); + } - DNSClientSettings dnsSettings = new(); + public ICommand ApplicationListMouseEnterCommand => new RelayCommand(p => ApplicationListMouseEnterAction()); - if (SettingsManager.Current.Network_UseCustomDNSServer) - { - if (!string.IsNullOrEmpty(SettingsManager.Current.Network_CustomDNSServer)) - { - _log.Info($"Use custom DNS servers ({SettingsManager.Current.Network_CustomDNSServer})..."); + private void ApplicationListMouseEnterAction() + { + IsMouseOverApplicationList = true; + } - List<(string Server, int Port)> dnsServers = new(); + public ICommand ApplicationListMouseLeaveCommand => new RelayCommand(p => ApplicationListMouseLeaveAction()); - foreach (var dnsServer in SettingsManager.Current.Network_CustomDNSServer.Split(";")) - { - dnsServers.Add((dnsServer, 53)); - } + private void ApplicationListMouseLeaveAction() + { + // Don't minmize the list, if the user has accidently moved the mouse while searching + if (!IsTextBoxSearchFocused) + IsApplicationListOpen = false; - dnsSettings.UseCustomDNSServers = true; - dnsSettings.DNSServers = dnsServers; - } - else + IsMouseOverApplicationList = false; + } + + public ICommand TextBoxSearchGotFocusCommand => new RelayCommand(p => TextBoxSearchGotFocusAction()); + + private void TextBoxSearchGotFocusAction() + { + IsTextBoxSearchFocused = true; + } + + public ICommand TextBoxSearchLostFocusCommand => new RelayCommand(p => TextBoxSearchLostFocusAction()); + + private void TextBoxSearchLostFocusAction() + { + if (!IsMouseOverApplicationList) + IsApplicationListOpen = false; + + IsTextBoxSearchFocused = false; + } + + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + + private void ClearSearchAction() + { + Search = string.Empty; + } + #endregion + + #region Methods + private void ShowWindow() + { + if (_isInTray) + ShowWindowFromTray(); + + if (!IsActive) + BringWindowToFront(); + } + + private void HideWindowToTray() + { + if (_notifyIcon == null) + InitNotifyIcon(); + + _isInTray = true; + + _notifyIcon.Visible = true; + + Hide(); + } + + private void ShowWindowFromTray() + { + _isInTray = false; + + Show(); + + _notifyIcon.Visible = SettingsManager.Current.TrayIcon_AlwaysShowIcon; + } + + private void BringWindowToFront() + { + if (WindowState == WindowState.Minimized) + WindowState = WindowState.Normal; + + Activate(); + } + + private void ConfigureDNS() + { + _log.Info("Configure application DNS..."); + + DNSClientSettings dnsSettings = new(); + + if (SettingsManager.Current.Network_UseCustomDNSServer) + { + if (!string.IsNullOrEmpty(SettingsManager.Current.Network_CustomDNSServer)) + { + _log.Info($"Use custom DNS servers ({SettingsManager.Current.Network_CustomDNSServer})..."); + + List<(string Server, int Port)> dnsServers = new(); + + foreach (var dnsServer in SettingsManager.Current.Network_CustomDNSServer.Split(";")) { - _log.Info($"Custom DNS servers could not be set (Setting \"{nameof(SettingsManager.Current.Network_CustomDNSServer)}\" has value \"{SettingsManager.Current.Network_CustomDNSServer}\")! Fallback to Windows DNS servers..."); - } + dnsServers.Add((dnsServer, 53)); + } + + dnsSettings.UseCustomDNSServers = true; + dnsSettings.DNSServers = dnsServers; } else { - _log.Info("Use Windows DNS servers..."); + _log.Info($"Custom DNS servers could not be set (Setting \"{nameof(SettingsManager.Current.Network_CustomDNSServer)}\" has value \"{SettingsManager.Current.Network_CustomDNSServer}\")! Fallback to Windows DNS servers..."); } - - DNSClient.GetInstance().Configure(dnsSettings); } - - private void UpdateDNS() + else { - _log.Info("Update Windows DNS servers..."); - - DNSClient.GetInstance().UpdateFromWindows(); + _log.Info("Use Windows DNS servers..."); } - private void WriteDefaultPowerShellProfileToRegistry() - { - if (!SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile) - return; + DNSClient.GetInstance().Configure(dnsSettings); + } - Debug.WriteLine("Test"); + private void UpdateDNS() + { + _log.Info("Update Windows DNS servers..."); - HashSet paths = new(); + DNSClient.GetInstance().UpdateFromWindows(); + } - // PowerShell - if (!string.IsNullOrEmpty(SettingsManager.Current.PowerShell_ApplicationFilePath) && File.Exists(SettingsManager.Current.PowerShell_ApplicationFilePath)) - paths.Add(SettingsManager.Current.PowerShell_ApplicationFilePath); + private void WriteDefaultPowerShellProfileToRegistry() + { + if (!SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile) + return; - // AWS Session Manager - if (!string.IsNullOrEmpty(SettingsManager.Current.AWSSessionManager_ApplicationFilePath) && File.Exists(SettingsManager.Current.AWSSessionManager_ApplicationFilePath)) - paths.Add(SettingsManager.Current.AWSSessionManager_ApplicationFilePath); + Debug.WriteLine("Test"); - foreach (var path in paths) - PowerShell.WriteDefaultProfileToRegistry(SettingsManager.Current.Appearance_Theme, path); - } - #endregion + HashSet paths = new(); - #region Status window - private void OpenStatusWindow(bool activate) - { - _statusWindow.ShowWindow(activate); - } + // PowerShell + if (!string.IsNullOrEmpty(SettingsManager.Current.PowerShell_ApplicationFilePath) && File.Exists(SettingsManager.Current.PowerShell_ApplicationFilePath)) + paths.Add(SettingsManager.Current.PowerShell_ApplicationFilePath); - private async void OnNetworkHasChanged() - { - if (_isNetworkChanging) - return; + // AWS Session Manager + if (!string.IsNullOrEmpty(SettingsManager.Current.AWSSessionManager_ApplicationFilePath) && File.Exists(SettingsManager.Current.AWSSessionManager_ApplicationFilePath)) + paths.Add(SettingsManager.Current.AWSSessionManager_ApplicationFilePath); - _isNetworkChanging = true; + foreach (var path in paths) + PowerShell.WriteDefaultProfileToRegistry(SettingsManager.Current.Appearance_Theme, path); + } + #endregion - // Wait 5 seconds, because the event may be triggered several times. - await Task.Delay(5000); + #region Status window + private void OpenStatusWindow(bool activate) + { + _statusWindow.ShowWindow(activate); + } - _log.Info("Network availability or address has changed!"); + private async void OnNetworkHasChanged() + { + if (_isNetworkChanging) + return; - // Update DNS server if network changed - if (!SettingsManager.Current.Network_UseCustomDNSServer) - UpdateDNS(); + _isNetworkChanging = true; - // Show status window on network change - if (SettingsManager.Current.Status_ShowWindowOnNetworkChange) - { - await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - OpenStatusWindow(false); - })); - } + // Wait 5 seconds, because the event may be triggered several times. + await Task.Delay(5000); - _isNetworkChanging = false; - } - #endregion + _log.Info("Network availability or address has changed!"); + + // Update DNS server if network changed + if (!SettingsManager.Current.Network_UseCustomDNSServer) + UpdateDNS(); - #region Events - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + // Show status window on network change + if (SettingsManager.Current.Status_ShowWindowOnNetworkChange) { - switch (e.PropertyName) + await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - // Show restart required note for some settings - case nameof(SettingsInfo.Localization_CultureCode): - IsRestartRequired = true; + OpenStatusWindow(false); + })); + } - break; + _isNetworkChanging = false; + } + #endregion - // Update TrayIcon if changed in the settings - case nameof(SettingsInfo.TrayIcon_AlwaysShowIcon): - if (SettingsManager.Current.TrayIcon_AlwaysShowIcon && _notifyIcon == null) - InitNotifyIcon(); + #region Events + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) + { + // Show restart required note for some settings + case nameof(SettingsInfo.Localization_CultureCode): + IsRestartRequired = true; - if (_notifyIcon != null) - _notifyIcon.Visible = SettingsManager.Current.TrayIcon_AlwaysShowIcon; + break; - break; + // Update TrayIcon if changed in the settings + case nameof(SettingsInfo.TrayIcon_AlwaysShowIcon): + if (SettingsManager.Current.TrayIcon_AlwaysShowIcon && _notifyIcon == null) + InitNotifyIcon(); - // Update DNS server if changed in the settings - case nameof(SettingsInfo.Network_UseCustomDNSServer): - case nameof(SettingsInfo.Network_CustomDNSServer): - ConfigureDNS(); + if (_notifyIcon != null) + _notifyIcon.Visible = SettingsManager.Current.TrayIcon_AlwaysShowIcon; - break; + break; - // Update PowerShell profile if changed in the settings - case nameof(SettingsInfo.Appearance_PowerShellModifyGlobalProfile): - case nameof(SettingsInfo.Appearance_Theme): - case nameof(SettingsInfo.PowerShell_ApplicationFilePath): - case nameof(SettingsInfo.AWSSessionManager_ApplicationFilePath): - if (SettingsManager.Current.FirstRun) - return; + // Update DNS server if changed in the settings + case nameof(SettingsInfo.Network_UseCustomDNSServer): + case nameof(SettingsInfo.Network_CustomDNSServer): + ConfigureDNS(); - WriteDefaultPowerShellProfileToRegistry(); + break; - break; - } - } - #endregion + // Update PowerShell profile if changed in the settings + case nameof(SettingsInfo.Appearance_PowerShellModifyGlobalProfile): + case nameof(SettingsInfo.Appearance_Theme): + case nameof(SettingsInfo.PowerShell_ApplicationFilePath): + case nameof(SettingsInfo.AWSSessionManager_ApplicationFilePath): + if (SettingsManager.Current.FirstRun) + return; - #region Bugfixes - private void ScrollViewer_ManipulationBoundaryFeedback(object sender, ManipulationBoundaryFeedbackEventArgs e) - { - e.Handled = true; - } - #endregion + WriteDefaultPowerShellProfileToRegistry(); - #region Focus embedded window - private void MetroMainWindow_Activated(object sender, EventArgs e) - { - FocusEmbeddedWindow(); + break; } + } + #endregion - private async void FocusEmbeddedWindow() - { - // Delay the focus to prevent blocking the ui - do - { - await Task.Delay(250); - } while (Control.MouseButtons == MouseButtons.Left); - - /* Don't continue if - - Application is not set - - Settings are opened - - Profile file drop down is opened - - Application search textbox is opened - - Dialog over an embedded window is opened - - Window is resizing - */ - if (SelectedApplication == null || ShowSettingsView || IsProfileFileDropDownOpened || IsTextBoxSearchFocused || ConfigurationManager.Current.IsDialogOpen) - return; + #region Bugfixes + private void ScrollViewer_ManipulationBoundaryFeedback(object sender, ManipulationBoundaryFeedbackEventArgs e) + { + e.Handled = true; + } + #endregion - // Switch by name - switch (SelectedApplication.Name) - { - case ApplicationName.PowerShell: - _powerShellHostView?.FocusEmbeddedWindow(); - break; - case ApplicationName.PuTTY: - _puttyHostView?.FocusEmbeddedWindow(); - break; - case ApplicationName.AWSSessionManager: - _awsSessionManagerHostView?.FocusEmbeddedWindow(); - break; - } + #region Focus embedded window + private void MetroMainWindow_Activated(object sender, EventArgs e) + { + FocusEmbeddedWindow(); + } + + private async void FocusEmbeddedWindow() + { + // Delay the focus to prevent blocking the ui + do + { + await Task.Delay(250); + } while (Control.MouseButtons == MouseButtons.Left); + + /* Don't continue if + - Application is not set + - Settings are opened + - Profile file drop down is opened + - Application search textbox is opened + - Dialog over an embedded window is opened + - Window is resizing + */ + if (SelectedApplication == null || ShowSettingsView || IsProfileFileDropDownOpened || IsTextBoxSearchFocused || ConfigurationManager.Current.IsDialogOpen) + return; + + // Switch by name + switch (SelectedApplication.Name) + { + case ApplicationName.PowerShell: + _powerShellHostView?.FocusEmbeddedWindow(); + break; + case ApplicationName.PuTTY: + _puttyHostView?.FocusEmbeddedWindow(); + break; + case ApplicationName.AWSSessionManager: + _awsSessionManagerHostView?.FocusEmbeddedWindow(); + break; } - #endregion } + #endregion } diff --git a/Source/NETworkManager/StatusWindow.xaml.cs b/Source/NETworkManager/StatusWindow.xaml.cs index 7e639e84d3..f2db136f5e 100644 --- a/Source/NETworkManager/StatusWindow.xaml.cs +++ b/Source/NETworkManager/StatusWindow.xaml.cs @@ -6,105 +6,104 @@ using System.Windows.Forms; using System.Windows.Input; -namespace NETworkManager +namespace NETworkManager; + +public partial class StatusWindow : MetroWindow, INotifyPropertyChanged { - public partial class StatusWindow : MetroWindow, INotifyPropertyChanged - { - #region PropertyChangedEventHandler - public event PropertyChangedEventHandler PropertyChanged; + #region PropertyChangedEventHandler + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - #endregion + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + #endregion - #region Variables - private MainWindow _mainWindow; - private NetworkConnectionView _networkConnectionView; - #endregion + #region Variables + private MainWindow _mainWindow; + private NetworkConnectionView _networkConnectionView; + #endregion - #region Constructor - public StatusWindow(MainWindow mainWindow) - { - InitializeComponent(); - DataContext = this; + #region Constructor + public StatusWindow(MainWindow mainWindow) + { + InitializeComponent(); + DataContext = this; - _mainWindow = mainWindow; + _mainWindow = mainWindow; - _networkConnectionView = new NetworkConnectionView(); - ContentControlNetworkConnection.Content = _networkConnectionView; - } - #endregion + _networkConnectionView = new NetworkConnectionView(); + ContentControlNetworkConnection.Content = _networkConnectionView; + } + #endregion - #region ICommands & Actions - public ICommand ReloadCommand => new RelayCommand(p => ReloadAction()); + #region ICommands & Actions + public ICommand ReloadCommand => new RelayCommand(p => ReloadAction()); - private void ReloadAction() - { - Reload(); - } + private void ReloadAction() + { + Reload(); + } - public ICommand ShowMainWindowCommand => new RelayCommand(p => ShowMainWindowAction()); + public ICommand ShowMainWindowCommand => new RelayCommand(p => ShowMainWindowAction()); - private void ShowMainWindowAction() - { - Hide(); + private void ShowMainWindowAction() + { + Hide(); - if (_mainWindow.ShowWindowCommand.CanExecute(null)) - _mainWindow.ShowWindowCommand.Execute(null); - } + if (_mainWindow.ShowWindowCommand.CanExecute(null)) + _mainWindow.ShowWindowCommand.Execute(null); + } - public ICommand CloseCommand => new RelayCommand(p => CloseAction()); + public ICommand CloseCommand => new RelayCommand(p => CloseAction()); - private void CloseAction() - { - Hide(); - } + private void CloseAction() + { + Hide(); + } - #endregion + #endregion - #region Methods - private void Reload() - { - _networkConnectionView.Reload(); - } + #region Methods + private void Reload() + { + _networkConnectionView.Reload(); + } - /// - /// Show the window on the screen. - /// - /// Focus the window (will automatically hide if the focus is lost). - public void ShowWindow(bool activate) - { - // Show on primary screen in left/bottom corner - // ToDo: User setting... - Left = Screen.PrimaryScreen.WorkingArea.Right - Width - 10; - Top = Screen.PrimaryScreen.WorkingArea.Bottom - Height - 10; + /// + /// Show the window on the screen. + /// + /// Focus the window (will automatically hide if the focus is lost). + public void ShowWindow(bool activate) + { + // Show on primary screen in left/bottom corner + // ToDo: User setting... + Left = Screen.PrimaryScreen.WorkingArea.Right - Width - 10; + Top = Screen.PrimaryScreen.WorkingArea.Bottom - Height - 10; - Show(); + Show(); - if (activate) - Activate(); + if (activate) + Activate(); - Topmost = true; - } - #endregion + Topmost = true; + } + #endregion - #region Events - private void MetroWindow_Deactivated(object sender, System.EventArgs e) - { - Hide(); - } + #region Events + private void MetroWindow_Deactivated(object sender, System.EventArgs e) + { + Hide(); + } - private void MetroWindow_Closing(object sender, CancelEventArgs e) - { - e.Cancel = true; + private void MetroWindow_Closing(object sender, CancelEventArgs e) + { + e.Cancel = true; - Hide(); - } + Hide(); + } - #endregion + #endregion - } } diff --git a/Source/NETworkManager/ViewModels/ARPTableAddEntryViewModel.cs b/Source/NETworkManager/ViewModels/ARPTableAddEntryViewModel.cs index 17ac633f71..17fe5e538d 100644 --- a/Source/NETworkManager/ViewModels/ARPTableAddEntryViewModel.cs +++ b/Source/NETworkManager/ViewModels/ARPTableAddEntryViewModel.cs @@ -2,46 +2,45 @@ using System; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ArpTableAddEntryViewModel : ViewModelBase { - public class ArpTableAddEntryViewModel : ViewModelBase - { - public ICommand AddCommand { get; } + public ICommand AddCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _ipAddress; - public string IPAddress + private string _ipAddress; + public string IPAddress + { + get => _ipAddress; + set { - get => _ipAddress; - set - { - if (value == _ipAddress) - return; - - _ipAddress = value; - OnPropertyChanged(); - } - } + if (value == _ipAddress) + return; - private string _macAddress; - public string MACAddress - { - get => _macAddress; - set - { - if (value == _macAddress) - return; - - _macAddress = value; - OnPropertyChanged(); - } + _ipAddress = value; + OnPropertyChanged(); } + } - public ArpTableAddEntryViewModel(Action addCommand, Action cancelHandler) + private string _macAddress; + public string MACAddress + { + get => _macAddress; + set { - AddCommand = new RelayCommand(p => addCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - } + if (value == _macAddress) + return; + + _macAddress = value; + OnPropertyChanged(); + } } + + public ArpTableAddEntryViewModel(Action addCommand, Action cancelHandler) + { + AddCommand = new RelayCommand(p => addCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ARPTableViewModel.cs b/Source/NETworkManager/ViewModels/ARPTableViewModel.cs index cead72a843..cc55a3239a 100644 --- a/Source/NETworkManager/ViewModels/ARPTableViewModel.cs +++ b/Source/NETworkManager/ViewModels/ARPTableViewModel.cs @@ -16,268 +16,302 @@ using NETworkManager.Models.Export; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ARPTableViewModel : ViewModelBase { - public class ARPTableViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading; - private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); - private bool _isTimerPaused; + private readonly bool _isLoading; + private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); + private bool _isTimerPaused; - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - ARPInfoResultsView.Refresh(); + ARPInfoResultsView.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private ObservableCollection _arpInfoResults = new ObservableCollection(); - public ObservableCollection ARPInfoResults + private ObservableCollection _arpInfoResults = new ObservableCollection(); + public ObservableCollection ARPInfoResults + { + get => _arpInfoResults; + set { - get => _arpInfoResults; - set - { - if (value == _arpInfoResults) - return; + if (value == _arpInfoResults) + return; - _arpInfoResults = value; - OnPropertyChanged(); - } + _arpInfoResults = value; + OnPropertyChanged(); } + } - public ICollectionView ARPInfoResultsView { get; } + public ICollectionView ARPInfoResultsView { get; } - private ARPInfo _selectedARPInfo; - public ARPInfo SelectedARPInfo + private ARPInfo _selectedARPInfo; + public ARPInfo SelectedARPInfo + { + get => _selectedARPInfo; + set { - get => _selectedARPInfo; - set - { - if (value == _selectedARPInfo) - return; + if (value == _selectedARPInfo) + return; - _selectedARPInfo = value; - OnPropertyChanged(); - } + _selectedARPInfo = value; + OnPropertyChanged(); } + } - private IList _selectedARPInfos = new ArrayList(); - public IList SelectedARPInfos + private IList _selectedARPInfos = new ArrayList(); + public IList SelectedARPInfos + { + get => _selectedARPInfos; + set { - get => _selectedARPInfos; - set - { - if (Equals(value, _selectedARPInfos)) - return; + if (Equals(value, _selectedARPInfos)) + return; - _selectedARPInfos = value; - OnPropertyChanged(); - } + _selectedARPInfos = value; + OnPropertyChanged(); } + } - private bool _autoRefresh; - public bool AutoRefresh + private bool _autoRefresh; + public bool AutoRefresh + { + get => _autoRefresh; + set { - get => _autoRefresh; - set - { - if (value == _autoRefresh) - return; - - if (!_isLoading) - SettingsManager.Current.ARPTable_AutoRefresh = value; + if (value == _autoRefresh) + return; - _autoRefresh = value; + if (!_isLoading) + SettingsManager.Current.ARPTable_AutoRefresh = value; - // Start timer to refresh automatically - if (!_isLoading) - { - if (value) - StartAutoRefreshTimer(); - else - StopAutoRefreshTimer(); - } + _autoRefresh = value; - OnPropertyChanged(); + // Start timer to refresh automatically + if (!_isLoading) + { + if (value) + StartAutoRefreshTimer(); + else + StopAutoRefreshTimer(); } + + OnPropertyChanged(); } + } - public ICollectionView AutoRefreshTimes { get; } + public ICollectionView AutoRefreshTimes { get; } - private AutoRefreshTimeInfo _selectedAutoRefreshTime; - public AutoRefreshTimeInfo SelectedAutoRefreshTime + private AutoRefreshTimeInfo _selectedAutoRefreshTime; + public AutoRefreshTimeInfo SelectedAutoRefreshTime + { + get => _selectedAutoRefreshTime; + set { - get => _selectedAutoRefreshTime; - set - { - if (value == _selectedAutoRefreshTime) - return; + if (value == _selectedAutoRefreshTime) + return; - if (!_isLoading) - SettingsManager.Current.ARPTable_AutoRefreshTime = value; + if (!_isLoading) + SettingsManager.Current.ARPTable_AutoRefreshTime = value; - _selectedAutoRefreshTime = value; + _selectedAutoRefreshTime = value; - if (AutoRefresh) - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); + if (AutoRefresh) + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isRefreshing; - public bool IsRefreshing + private bool _isRefreshing; + public bool IsRefreshing + { + get => _isRefreshing; + set { - get => _isRefreshing; - set - { - if (value == _isRefreshing) - return; + if (value == _isRefreshing) + return; - _isRefreshing = value; - OnPropertyChanged(); - } + _isRefreshing = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion + + #region Contructor, load settings + public ARPTableViewModel(IDialogCoordinator instance) + { + _isLoading = true; + _dialogCoordinator = instance; - #region Contructor, load settings - public ARPTableViewModel(IDialogCoordinator instance) + // Result view + search + ARPInfoResultsView = CollectionViewSource.GetDefaultView(ARPInfoResults); + ARPInfoResultsView.SortDescriptions.Add(new SortDescription(nameof(ARPInfo.IPAddressInt32), ListSortDirection.Ascending)); + ARPInfoResultsView.Filter = o => { - _isLoading = true; - _dialogCoordinator = instance; + if (!(o is ARPInfo info)) + return false; - // Result view + search - ARPInfoResultsView = CollectionViewSource.GetDefaultView(ARPInfoResults); - ARPInfoResultsView.SortDescriptions.Add(new SortDescription(nameof(ARPInfo.IPAddressInt32), ListSortDirection.Ascending)); - ARPInfoResultsView.Filter = o => - { - if (!(o is ARPInfo info)) - return false; + if (string.IsNullOrEmpty(Search)) + return true; - if (string.IsNullOrEmpty(Search)) - return true; + // Search by IPAddress and MACAddress + return info.IPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.MACAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || (info.IsMulticast ? Localization.Resources.Strings.Yes : Localization.Resources.Strings.No).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1; + }; - // Search by IPAddress and MACAddress - return info.IPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.MACAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || (info.IsMulticast ? Localization.Resources.Strings.Yes : Localization.Resources.Strings.No).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1; - }; + AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); + SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.ARPTable_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.ARPTable_AutoRefreshTime.TimeUnit)); - AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); - SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.ARPTable_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.ARPTable_AutoRefreshTime.TimeUnit)); + _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; - _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; + LoadSettings(); - LoadSettings(); + _isLoading = false; - _isLoading = false; + Run(); + } - Run(); - } + private async Task Run() + { + await Refresh(); - private async Task Run() - { - await Refresh(); + if (AutoRefresh) + StartAutoRefreshTimer(); + } - if (AutoRefresh) - StartAutoRefreshTimer(); - } + private void LoadSettings() + { + AutoRefresh = SettingsManager.Current.ARPTable_AutoRefresh; + } + #endregion - private void LoadSettings() - { - AutoRefresh = SettingsManager.Current.ARPTable_AutoRefresh; - } - #endregion + #region ICommands & Actions + public ICommand RefreshCommand => new RelayCommand(p => RefreshAction(), Refresh_CanExecute); + + private bool Refresh_CanExecute(object paramter) + { + return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + } - #region ICommands & Actions - public ICommand RefreshCommand => new RelayCommand(p => RefreshAction(), Refresh_CanExecute); + private async Task RefreshAction() + { + IsStatusMessageDisplayed = false; - private bool Refresh_CanExecute(object paramter) - { - return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - } + await Refresh(); + } - private async Task RefreshAction() + public ICommand DeleteTableCommand => new RelayCommand(p => DeleteTableAction(), DeleteTable_CanExecute); + + private bool DeleteTable_CanExecute(object paramter) + { + return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + } + + private async Task DeleteTableAction() + { + IsStatusMessageDisplayed = false; + + try { - IsStatusMessageDisplayed = false; + var arpTable = new ARP(); - await Refresh(); - } + arpTable.UserHasCanceled += ArpTable_UserHasCanceled; - public ICommand DeleteTableCommand => new RelayCommand(p => DeleteTableAction(), DeleteTable_CanExecute); + await arpTable.DeleteTableAsync(); - private bool DeleteTable_CanExecute(object paramter) + await Refresh(); + } + catch (Exception ex) { - return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; } + } - private async Task DeleteTableAction() - { - IsStatusMessageDisplayed = false; + public ICommand DeleteEntryCommand => new RelayCommand(p => DeleteEntryAction(), DeleteEntry_CanExecute); - try - { - var arpTable = new ARP(); + private bool DeleteEntry_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - arpTable.UserHasCanceled += ArpTable_UserHasCanceled; + private async Task DeleteEntryAction() + { + IsStatusMessageDisplayed = false; - await arpTable.DeleteTableAsync(); + try + { + var arpTable = new ARP(); - await Refresh(); - } - catch (Exception ex) - { - StatusMessage = ex.Message; - IsStatusMessageDisplayed = true; - } + arpTable.UserHasCanceled += ArpTable_UserHasCanceled; + + await arpTable.DeleteEntryAsync(SelectedARPInfo.IPAddress.ToString()); + + await Refresh(); } + catch (Exception ex) + { + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; + } + } + + public ICommand AddEntryCommand => new RelayCommand(p => AddEntryAction(), AddEntry_CanExecute); + + private bool AddEntry_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - public ICommand DeleteEntryCommand => new RelayCommand(p => DeleteEntryAction(), DeleteEntry_CanExecute); + private async Task AddEntryAction() + { + IsStatusMessageDisplayed = false; - private bool DeleteEntry_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.AddEntry + }; - private async Task DeleteEntryAction() + var arpTableAddEntryViewModel = new ArpTableAddEntryViewModel(async instance => { - IsStatusMessageDisplayed = false; + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); try { @@ -285,7 +319,7 @@ private async Task DeleteEntryAction() arpTable.UserHasCanceled += ArpTable_UserHasCanceled; - await arpTable.DeleteEntryAsync(SelectedARPInfo.IPAddress.ToString()); + await arpTable.AddEntryAsync(instance.IPAddress, MACAddressHelper.Format(instance.MACAddress, "-")); await Refresh(); } @@ -294,190 +328,155 @@ private async Task DeleteEntryAction() StatusMessage = ex.Message; IsStatusMessageDisplayed = true; } - } - - public ICommand AddEntryCommand => new RelayCommand(p => AddEntryAction(), AddEntry_CanExecute); - - private bool AddEntry_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - - private async Task AddEntryAction() + }, instance => { - IsStatusMessageDisplayed = false; + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddEntry - }; - - var arpTableAddEntryViewModel = new ArpTableAddEntryViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - try - { - var arpTable = new ARP(); + customDialog.Content = new ARPTableAddEntryDialog + { + DataContext = arpTableAddEntryViewModel + }; - arpTable.UserHasCanceled += ArpTable_UserHasCanceled; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - await arpTable.AddEntryAsync(instance.IPAddress, MACAddressHelper.Format(instance.MACAddress, "-")); + public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); - await Refresh(); - } - catch (Exception ex) - { - StatusMessage = ex.Message; - IsStatusMessageDisplayed = true; - } - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); + private void CopySelectedIPAddressAction() + { + ClipboardHelper.SetClipboard(SelectedARPInfo.IPAddress.ToString()); + } - customDialog.Content = new ARPTableAddEntryDialog - { - DataContext = arpTableAddEntryViewModel - }; + public ICommand CopySelectedMACAddressCommand => new RelayCommand(p => CopySelectedMACAddressAction()); - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + private void CopySelectedMACAddressAction() + { + ClipboardHelper.SetClipboard(MACAddressHelper.GetDefaultFormat(SelectedARPInfo.MACAddress.ToString())); + } - public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); + public ICommand CopySelectedMulticastCommand => new RelayCommand(p => CopySelectedMulticastAction()); - private void CopySelectedIPAddressAction() - { - ClipboardHelper.SetClipboard(SelectedARPInfo.IPAddress.ToString()); - } + private void CopySelectedMulticastAction() + { + ClipboardHelper.SetClipboard(SelectedARPInfo.IsMulticast ? Localization.Resources.Strings.Yes : Localization.Resources.Strings.No); + } - public ICommand CopySelectedMACAddressCommand => new RelayCommand(p => CopySelectedMACAddressAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private void CopySelectedMACAddressAction() + private async Task ExportAction() + { + var customDialog = new CustomDialog { - ClipboardHelper.SetClipboard(MACAddressHelper.GetDefaultFormat(SelectedARPInfo.MACAddress.ToString())); - } - - public ICommand CopySelectedMulticastCommand => new RelayCommand(p => CopySelectedMulticastAction()); + Title = Localization.Resources.Strings.Export + }; - private void CopySelectedMulticastAction() + var exportViewModel = new ExportViewModel(async instance => { - ClipboardHelper.SetClipboard(SelectedARPInfo.IsMulticast ? Localization.Resources.Strings.Yes : Localization.Resources.Strings.No); - } + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - - private async Task ExportAction() - { - var customDialog = new CustomDialog + try { - Title = Localization.Resources.Strings.Export - }; - - var exportViewModel = new ExportViewModel(async instance => + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? ARPInfoResults : new ObservableCollection(SelectedARPInfos.Cast().ToArray())); + } + catch (Exception ex) { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? ARPInfoResults : new ObservableCollection(SelectedARPInfos.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - SettingsManager.Current.ARPTable_ExportFileType = instance.FileType; - SettingsManager.Current.ARPTable_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.ARPTable_ExportFileType, SettingsManager.Current.ARPTable_ExportFilePath); + SettingsManager.Current.ARPTable_ExportFileType = instance.FileType; + SettingsManager.Current.ARPTable_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.ARPTable_ExportFileType, SettingsManager.Current.ARPTable_ExportFilePath); - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - #region Methods - private async Task Refresh() - { - IsRefreshing = true; + #region Methods + private async Task Refresh() + { + IsRefreshing = true; - ARPInfoResults.Clear(); + ARPInfoResults.Clear(); - (await ARP.GetTableAsync()).ForEach(x => ARPInfoResults.Add(x)); + (await ARP.GetTableAsync()).ForEach(x => ARPInfoResults.Add(x)); - IsRefreshing = false; - } + IsRefreshing = false; + } - private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) - { - _autoRefreshTimer.Interval = timeSpan; - } + private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) + { + _autoRefreshTimer.Interval = timeSpan; + } - private void StartAutoRefreshTimer() - { - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); + private void StartAutoRefreshTimer() + { + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); - _autoRefreshTimer.Start(); - } + _autoRefreshTimer.Start(); + } - private void StopAutoRefreshTimer() - { - _autoRefreshTimer.Stop(); - } + private void StopAutoRefreshTimer() + { + _autoRefreshTimer.Stop(); + } - private void PauseAutoRefreshTimer() - { - if (!_autoRefreshTimer.IsEnabled) - return; + private void PauseAutoRefreshTimer() + { + if (!_autoRefreshTimer.IsEnabled) + return; - _autoRefreshTimer.Stop(); + _autoRefreshTimer.Stop(); - _isTimerPaused = true; - } + _isTimerPaused = true; + } - private void ResumeAutoRefreshTimer() - { - if (!_isTimerPaused) - return; + private void ResumeAutoRefreshTimer() + { + if (!_isTimerPaused) + return; - _autoRefreshTimer.Start(); + _autoRefreshTimer.Start(); - _isTimerPaused = false; - } + _isTimerPaused = false; + } - public void OnViewHide() - { - PauseAutoRefreshTimer(); - } + public void OnViewHide() + { + PauseAutoRefreshTimer(); + } - public void OnViewVisible() - { - ResumeAutoRefreshTimer(); - } - #endregion + public void OnViewVisible() + { + ResumeAutoRefreshTimer(); + } + #endregion - #region Events - private void ArpTable_UserHasCanceled(object sender, EventArgs e) - { - StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; - IsStatusMessageDisplayed = true; - } + #region Events + private void ArpTable_UserHasCanceled(object sender, EventArgs e) + { + StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; + IsStatusMessageDisplayed = true; + } - private async void AutoRefreshTimer_Tick(object sender, EventArgs e) - { - // Stop timer... - _autoRefreshTimer.Stop(); + private async void AutoRefreshTimer_Tick(object sender, EventArgs e) + { + // Stop timer... + _autoRefreshTimer.Stop(); - // Refresh - await Refresh(); + // Refresh + await Refresh(); - // Restart timer... - _autoRefreshTimer.Start(); - } - #endregion + // Restart timer... + _autoRefreshTimer.Start(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/AWSProfileViewModel.cs b/Source/NETworkManager/ViewModels/AWSProfileViewModel.cs index 423f9c1dcb..f652864456 100644 --- a/Source/NETworkManager/ViewModels/AWSProfileViewModel.cs +++ b/Source/NETworkManager/ViewModels/AWSProfileViewModel.cs @@ -3,121 +3,120 @@ using System.Windows.Input; using NETworkManager.Models.AWS; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class AWSProfileViewModel : ViewModelBase { - public class AWSProfileViewModel : ViewModelBase - { - private readonly bool _isLoading; + private readonly bool _isLoading; - public ICommand SaveCommand { get; } + public ICommand SaveCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private bool _isEnabled; - public bool IsEnabled + private bool _isEnabled; + public bool IsEnabled + { + get => _isEnabled; + set { - get => _isEnabled; - set - { - if (_isEnabled == value) - return; + if (_isEnabled == value) + return; - _isEnabled = value; + _isEnabled = value; - if (!_isLoading) - Validate(); + if (!_isLoading) + Validate(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private string _profile; - public string Profile + private string _profile; + public string Profile + { + get => _profile; + set { - get => _profile; - set - { - if (_profile == value) - return; + if (_profile == value) + return; - _profile = value; + _profile = value; - if (!_isLoading) - Validate(); + if (!_isLoading) + Validate(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private string _region; - public string Region + private string _region; + public string Region + { + get => _region; + set { - get => _region; - set - { - if (_region == value) - return; + if (_region == value) + return; - _region = value; + _region = value; - if (!_isLoading) - Validate(); + if (!_isLoading) + Validate(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private readonly AWSProfileInfo _info; + private readonly AWSProfileInfo _info; - private bool _infoChanged; - public bool InfoChanged + private bool _infoChanged; + public bool InfoChanged + { + get => _infoChanged; + set { - get => _infoChanged; - set - { - if (value == _infoChanged) - return; - - _infoChanged = value; - OnPropertyChanged(); - } + if (value == _infoChanged) + return; + + _infoChanged = value; + OnPropertyChanged(); } + } - private bool _isEdited; - public bool IsEdited + private bool _isEdited; + public bool IsEdited + { + get => _isEdited; + set { - get => _isEdited; - set - { - if (value == _isEdited) - return; - - _isEdited = value; - OnPropertyChanged(); - } + if (value == _isEdited) + return; + + _isEdited = value; + OnPropertyChanged(); } + } - public AWSProfileViewModel(Action saveCommand, Action cancelHandler, bool isEdited = false, AWSProfileInfo info = null) - { - _isLoading = true; + public AWSProfileViewModel(Action saveCommand, Action cancelHandler, bool isEdited = false, AWSProfileInfo info = null) + { + _isLoading = true; - SaveCommand = new RelayCommand(p => saveCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + SaveCommand = new RelayCommand(p => saveCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - IsEdited = isEdited; + IsEdited = isEdited; - _info = info ?? new AWSProfileInfo(); - - IsEnabled = _info.IsEnabled; - Profile = _info.Profile; - Region = _info.Region; + _info = info ?? new AWSProfileInfo(); + + IsEnabled = _info.IsEnabled; + Profile = _info.Profile; + Region = _info.Region; - _isLoading = false; - } + _isLoading = false; + } - public void Validate() - { - InfoChanged = _info.IsEnabled != IsEnabled || _info.Profile != Profile || _info.Region != Region; - } + public void Validate() + { + InfoChanged = _info.IsEnabled != IsEnabled || _info.Profile != Profile || _info.Region != Region; } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/AWSSessionManagerConnectViewModel.cs b/Source/NETworkManager/ViewModels/AWSSessionManagerConnectViewModel.cs index 17228a7064..20b5f08958 100644 --- a/Source/NETworkManager/ViewModels/AWSSessionManagerConnectViewModel.cs +++ b/Source/NETworkManager/ViewModels/AWSSessionManagerConnectViewModel.cs @@ -5,77 +5,76 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class AWSSessionManagerConnectViewModel : ViewModelBase { - public class AWSSessionManagerConnectViewModel : ViewModelBase - { - public ICommand ConnectCommand { get; } - public ICommand CancelCommand { get; } + public ICommand ConnectCommand { get; } + public ICommand CancelCommand { get; } - private string _instanceID; - public string InstanceID + private string _instanceID; + public string InstanceID + { + get => _instanceID; + set { - get => _instanceID; - set - { - if (value == _instanceID) - return; + if (value == _instanceID) + return; - _instanceID = value; - OnPropertyChanged(); - } + _instanceID = value; + OnPropertyChanged(); } + } - public ICollectionView InstanceIDHistoryView { get; } + public ICollectionView InstanceIDHistoryView { get; } - private string _profile; - public string Profile + private string _profile; + public string Profile + { + get => _profile; + set { - get => _profile; - set - { - if (value == _profile) - return; + if (value == _profile) + return; - _profile = value; - OnPropertyChanged(); - } + _profile = value; + OnPropertyChanged(); } + } - public ICollectionView ProfileHistoryView { get; } + public ICollectionView ProfileHistoryView { get; } - private string _region; - public string Region + private string _region; + public string Region + { + get => _region; + set { - get => _region; - set - { - if (value == _region) - return; + if (value == _region) + return; - _region = value; - OnPropertyChanged(); - } + _region = value; + OnPropertyChanged(); } + } - public ICollectionView RegionHistoryView { get; } + public ICollectionView RegionHistoryView { get; } - public AWSSessionManagerConnectViewModel(Action connectCommand, Action cancelHandler) - { - ConnectCommand = new RelayCommand(p => connectCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + public AWSSessionManagerConnectViewModel(Action connectCommand, Action cancelHandler) + { + ConnectCommand = new RelayCommand(p => connectCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - InstanceIDHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_InstanceIDHistory); - ProfileHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_ProfileHistory); - RegionHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_RegionHistory); + InstanceIDHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_InstanceIDHistory); + ProfileHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_ProfileHistory); + RegionHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_RegionHistory); - LoadSettings(); - } + LoadSettings(); + } - private void LoadSettings() - { - Profile = SettingsManager.Current.AWSSessionManager_DefaultProfile; - Region = SettingsManager.Current.AWSSessionManager_DefaultRegion; - } + private void LoadSettings() + { + Profile = SettingsManager.Current.AWSSessionManager_DefaultProfile; + Region = SettingsManager.Current.AWSSessionManager_DefaultRegion; } } diff --git a/Source/NETworkManager/ViewModels/AWSSessionManagerHostViewModel.cs b/Source/NETworkManager/ViewModels/AWSSessionManagerHostViewModel.cs index fa743bea90..d0f4ae738f 100644 --- a/Source/NETworkManager/ViewModels/AWSSessionManagerHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/AWSSessionManagerHostViewModel.cs @@ -30,966 +30,965 @@ using log4net; using Amazon.EC2.Model; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class AWSSessionManagerHostViewModel : ViewModelBase, IProfileManager { - public class AWSSessionManagerHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private static readonly ILog _log = LogManager.GetLogger(typeof(AWSSessionManagerHostViewModel)); - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new(); + #region Variables + private static readonly ILog _log = LogManager.GetLogger(typeof(AWSSessionManagerHostViewModel)); + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private bool _isAWSCLIInstalled; - public bool IsAWSCLIInstalled + private bool _isAWSCLIInstalled; + public bool IsAWSCLIInstalled + { + get => _isAWSCLIInstalled; + set { - get => _isAWSCLIInstalled; - set - { - if (value == _isAWSCLIInstalled) - return; + if (value == _isAWSCLIInstalled) + return; - _isAWSCLIInstalled = value; - OnPropertyChanged(); - } + _isAWSCLIInstalled = value; + OnPropertyChanged(); } + } - private bool _isAWSSessionManagerPluginInstalled; - public bool IsAWSSessionManagerPluginInstalled + private bool _isAWSSessionManagerPluginInstalled; + public bool IsAWSSessionManagerPluginInstalled + { + get => _isAWSSessionManagerPluginInstalled; + set { - get => _isAWSSessionManagerPluginInstalled; - set - { - if (value == _isAWSSessionManagerPluginInstalled) - return; + if (value == _isAWSSessionManagerPluginInstalled) + return; - _isAWSSessionManagerPluginInstalled = value; - OnPropertyChanged(); - } + _isAWSSessionManagerPluginInstalled = value; + OnPropertyChanged(); } + } - private bool _isPowerShellConfigured; - public bool IsPowerShellConfigured + private bool _isPowerShellConfigured; + public bool IsPowerShellConfigured + { + get => _isPowerShellConfigured; + set { - get => _isPowerShellConfigured; - set - { - if (value == _isPowerShellConfigured) - return; + if (value == _isPowerShellConfigured) + return; - _isPowerShellConfigured = value; - OnPropertyChanged(); - } + _isPowerShellConfigured = value; + OnPropertyChanged(); } + } - private bool _isSyncEnabled; - public bool IsSyncEnabled + private bool _isSyncEnabled; + public bool IsSyncEnabled + { + get => _isSyncEnabled; + set { - get => _isSyncEnabled; - set - { - if (value == _isSyncEnabled) - return; + if (value == _isSyncEnabled) + return; - _isSyncEnabled = value; - OnPropertyChanged(); - } + _isSyncEnabled = value; + OnPropertyChanged(); } + } - private bool _isSyncing; - public bool IsSyncing + private bool _isSyncing; + public bool IsSyncing + { + get => _isSyncing; + set { - get => _isSyncing; - set - { - if (value == _isSyncing) - return; + if (value == _isSyncing) + return; - _isSyncing = value; - OnPropertyChanged(); - } + _isSyncing = value; + OnPropertyChanged(); } + } - private bool _disableFocusEmbeddedWindow; + private bool _disableFocusEmbeddedWindow; - private DragablzTabItem _selectedTabItem; - public DragablzTabItem SelectedTabItem + private DragablzTabItem _selectedTabItem; + public DragablzTabItem SelectedTabItem + { + get => _selectedTabItem; + set { - get => _selectedTabItem; - set - { - if (value == _selectedTabItem) - return; + if (value == _selectedTabItem) + return; - _selectedTabItem = value; + _selectedTabItem = value; - // Focus embedded window on switching tab - if (!_disableFocusEmbeddedWindow) - FocusEmbeddedWindow(); + // Focus embedded window on switching tab + if (!_disableFocusEmbeddedWindow) + FocusEmbeddedWindow(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _headerContextMenuIsOpen; - public bool HeaderContextMenuIsOpen + private bool _headerContextMenuIsOpen; + public bool HeaderContextMenuIsOpen + { + get => _headerContextMenuIsOpen; + set { - get => _headerContextMenuIsOpen; - set - { - if (value == _headerContextMenuIsOpen) - return; + if (value == _headerContextMenuIsOpen) + return; - _headerContextMenuIsOpen = value; - OnPropertyChanged(); - } + _headerContextMenuIsOpen = value; + OnPropertyChanged(); } - #region Profiles + } + #region Profiles - public ICollectionView Profiles { get; } + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _textBoxSearchIsFocused; - public bool TextBoxSearchIsFocused + private bool _textBoxSearchIsFocused; + public bool TextBoxSearchIsFocused + { + get => _textBoxSearchIsFocused; + set { - get => _textBoxSearchIsFocused; - set - { - if (value == _textBoxSearchIsFocused) - return; + if (value == _textBoxSearchIsFocused) + return; - _textBoxSearchIsFocused = value; - OnPropertyChanged(); - } + _textBoxSearchIsFocused = value; + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.AWSSessionManager_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.AWSSessionManager_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.AWSSessionManager_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.AWSSessionManager_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _profileContextMenuIsOpen; - public bool ProfileContextMenuIsOpen + private bool _profileContextMenuIsOpen; + public bool ProfileContextMenuIsOpen + { + get => _profileContextMenuIsOpen; + set { - get => _profileContextMenuIsOpen; - set - { - if (value == _profileContextMenuIsOpen) - return; + if (value == _profileContextMenuIsOpen) + return; - _profileContextMenuIsOpen = value; - OnPropertyChanged(); - } + _profileContextMenuIsOpen = value; + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public AWSSessionManagerHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public AWSSessionManagerHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - CheckInstallationStatus(); - CheckSettings(); + CheckInstallationStatus(); + CheckSettings(); - InterTabClient = new DragablzInterTabClient(ApplicationName.AWSSessionManager); + InterTabClient = new DragablzInterTabClient(ApplicationName.AWSSessionManager); - TabItems = new ObservableCollection(); + TabItems = new ObservableCollection(); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (o is not ProfileInfo info) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (o is not ProfileInfo info) + return false; - if (string.IsNullOrEmpty(Search)) - return info.AWSSessionManager_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.AWSSessionManager_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) + // Search by: Tag=xxx (exact match, ignore case) - //if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - // return !string.IsNullOrEmpty(info.Tags) && info.AWSSessionManager_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - // + //if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + // return !string.IsNullOrEmpty(info.Tags) && info.AWSSessionManager_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + // - // Search by: Name, AWSSessionManager_Host - return info.AWSSessionManager_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.AWSSessionManager_InstanceID.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, AWSSessionManager_Host + return info.AWSSessionManager_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.AWSSessionManager_InstanceID.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.AWSSessionManager_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.AWSSessionManager_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += Current_PropertyChanged; - SettingsManager.Current.AWSSessionManager_AWSProfiles.CollectionChanged += AWSSessionManager_AWSProfiles_CollectionChanged; + SettingsManager.Current.PropertyChanged += Current_PropertyChanged; + SettingsManager.Current.AWSSessionManager_AWSProfiles.CollectionChanged += AWSSessionManager_AWSProfiles_CollectionChanged; - SyncAllInstanceIDsFromAWS(); + SyncAllInstanceIDsFromAWS(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - IsSyncEnabled = SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS; + private void LoadSettings() + { + IsSyncEnabled = SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS; - ExpandProfileView = SettingsManager.Current.AWSSessionManager_ExpandProfileView; + ExpandProfileView = SettingsManager.Current.AWSSessionManager_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.AWSSessionManager_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.AWSSessionManager_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.AWSSessionManager_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.AWSSessionManager_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ICommand CheckInstallationStatusCommand => new RelayCommand(p => CheckInstallationStatusAction()); + #region ICommand & Actions + public ICommand CheckInstallationStatusCommand => new RelayCommand(p => CheckInstallationStatusAction()); - private void CheckInstallationStatusAction() - { - CheckInstallationStatus(); - } + private void CheckInstallationStatusAction() + { + CheckInstallationStatus(); + } - public ItemActionCallback CloseItemCommand => CloseItemAction; + public ItemActionCallback CloseItemCommand => CloseItemAction; - private void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as AWSSessionManagerControl)?.CloseTab(); - } + private void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as AWSSessionManagerControl)?.CloseTab(); + } - private bool AWSSessionManager_Connected_CanExecute(object view) - { - if (view is AWSSessionManagerControl control) - return control.IsConnected; + private bool AWSSessionManager_Connected_CanExecute(object view) + { + if (view is AWSSessionManagerControl control) + return control.IsConnected; - return false; - } + return false; + } - public ICommand AWSSessionManager_ReconnectCommand => new RelayCommand(AWSSessionManager_ReconnectAction); + public ICommand AWSSessionManager_ReconnectCommand => new RelayCommand(AWSSessionManager_ReconnectAction); - private void AWSSessionManager_ReconnectAction(object view) + private void AWSSessionManager_ReconnectAction(object view) + { + if (view is AWSSessionManagerControl control) { - if (view is AWSSessionManagerControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } + } - public ICommand AWSSessionManager_ResizeWindowCommand => new RelayCommand(AWSSessionManager_ResizeWindowAction, AWSSessionManager_Connected_CanExecute); + public ICommand AWSSessionManager_ResizeWindowCommand => new RelayCommand(AWSSessionManager_ResizeWindowAction, AWSSessionManager_Connected_CanExecute); - private void AWSSessionManager_ResizeWindowAction(object view) - { - if (view is AWSSessionManagerControl control) - control.ResizeEmbeddedWindow(); - } + private void AWSSessionManager_ResizeWindowAction(object view) + { + if (view is AWSSessionManagerControl control) + control.ResizeEmbeddedWindow(); + } - public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); + public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); - private bool Connect_CanExecute(object obj) => IsPowerShellConfigured; + private bool Connect_CanExecute(object obj) => IsPowerShellConfigured; - private void ConnectAction() - { - Connect(); - } + private void ConnectAction() + { + Connect(); + } - public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); + public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); - private bool ConnectProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool ConnectProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ConnectProfileAction() - { - ConnectProfile(); - } + private void ConnectProfileAction() + { + ConnectProfile(); + } - public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); + public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); - private void ConnectProfileExternalAction() - { - ConnectProfileExternal(); - } + private void ConnectProfileExternalAction() + { + ConnectProfileExternal(); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.AWSSessionManager); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.AWSSessionManager); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - private bool SyncInstanceIDsFromAWS_CanExecute(object obj) => !IsSyncing && IsSyncEnabled; + private bool SyncInstanceIDsFromAWS_CanExecute(object obj) => !IsSyncing && IsSyncEnabled; - public ICommand SyncAllInstanceIDsFromAWSCommand => new RelayCommand(p => SyncAllInstanceIDsFromAWSAction(), SyncInstanceIDsFromAWS_CanExecute); + public ICommand SyncAllInstanceIDsFromAWSCommand => new RelayCommand(p => SyncAllInstanceIDsFromAWSAction(), SyncInstanceIDsFromAWS_CanExecute); - private void SyncAllInstanceIDsFromAWSAction() - { - SyncAllInstanceIDsFromAWS(); - } + private void SyncAllInstanceIDsFromAWSAction() + { + SyncAllInstanceIDsFromAWS(); + } - public ICommand SyncGroupInstanceIDsFromAWSCommand => new RelayCommand(SyncGroupInstanceIDsFromAWSAction, SyncInstanceIDsFromAWS_CanExecute); + public ICommand SyncGroupInstanceIDsFromAWSCommand => new RelayCommand(SyncGroupInstanceIDsFromAWSAction, SyncInstanceIDsFromAWS_CanExecute); - private void SyncGroupInstanceIDsFromAWSAction(object group) - { - SyncGroupInstanceIDsFromAWS((string)group); - } + private void SyncGroupInstanceIDsFromAWSAction(object group) + { + SyncGroupInstanceIDsFromAWS((string)group); + } - public ICommand TextBoxSearchGotFocusCommand - { - get { return new RelayCommand(p => TextBoxSearchGotFocusAction()); } - } + public ICommand TextBoxSearchGotFocusCommand + { + get { return new RelayCommand(p => TextBoxSearchGotFocusAction()); } + } - private void TextBoxSearchGotFocusAction() - { - TextBoxSearchIsFocused = true; - } + private void TextBoxSearchGotFocusAction() + { + TextBoxSearchIsFocused = true; + } - public ICommand TextBoxSearchLostFocusCommand - { - get { return new RelayCommand(p => TextBoxSearchLostFocusAction()); } - } + public ICommand TextBoxSearchLostFocusCommand + { + get { return new RelayCommand(p => TextBoxSearchLostFocusAction()); } + } - private void TextBoxSearchLostFocusAction() - { - TextBoxSearchIsFocused = false; - } + private void TextBoxSearchLostFocusAction() + { + TextBoxSearchIsFocused = false; + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ICommand OpenDocumentationCommand - { - get { return new RelayCommand(p => OpenDocumentationAction()); } - } + public ICommand OpenDocumentationCommand + { + get { return new RelayCommand(p => OpenDocumentationAction()); } + } - private void OpenDocumentationAction() - { - DocumentationManager.OpenDocumentation(DocumentationIdentifier.ApplicationAWSSessionManager); - } + private void OpenDocumentationAction() + { + DocumentationManager.OpenDocumentation(DocumentationIdentifier.ApplicationAWSSessionManager); + } - public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); + public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); - private static void OpenSettingsAction() - { - EventSystem.RedirectToSettings(); - } - #endregion + private static void OpenSettingsAction() + { + EventSystem.RedirectToSettings(); + } + #endregion - #region Methods - private void CheckInstallationStatus() - { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")) + #region Methods + private void CheckInstallationStatus() + { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall")) + { + foreach (string subkeyName in key.GetSubKeyNames()) { - foreach (string subkeyName in key.GetSubKeyNames()) - { - using RegistryKey subKey = key.OpenSubKey(subkeyName); + using RegistryKey subKey = key.OpenSubKey(subkeyName); - var displayName = subKey.GetValue("DisplayName"); + var displayName = subKey.GetValue("DisplayName"); - if (displayName == null) - continue; + if (displayName == null) + continue; - if (displayName.Equals("AWS Command Line Interface v2")) - IsAWSCLIInstalled = true; + if (displayName.Equals("AWS Command Line Interface v2")) + IsAWSCLIInstalled = true; - if (displayName.Equals( "Session Manager Plugin")) - IsAWSSessionManagerPluginInstalled = true; - } + if (displayName.Equals( "Session Manager Plugin")) + IsAWSSessionManagerPluginInstalled = true; } } + } - private void CheckSettings() + private void CheckSettings() + { + IsPowerShellConfigured = !string.IsNullOrEmpty(SettingsManager.Current.AWSSessionManager_ApplicationFilePath) && File.Exists(SettingsManager.Current.AWSSessionManager_ApplicationFilePath); + } + + private bool IsConfigured => IsAWSCLIInstalled && IsAWSSessionManagerPluginInstalled && IsPowerShellConfigured; + + private async Task SyncAllInstanceIDsFromAWS() + { + if (!IsSyncEnabled) { - IsPowerShellConfigured = !string.IsNullOrEmpty(SettingsManager.Current.AWSSessionManager_ApplicationFilePath) && File.Exists(SettingsManager.Current.AWSSessionManager_ApplicationFilePath); + _log.Info("Sync all EC2 instances from AWS is disabled in the settings."); + return; } - private bool IsConfigured => IsAWSCLIInstalled && IsAWSSessionManagerPluginInstalled && IsPowerShellConfigured; + _log.Info("Sync all EC2 instance(s) from AWS..."); - private async Task SyncAllInstanceIDsFromAWS() + if (!IsConfigured) { - if (!IsSyncEnabled) - { - _log.Info("Sync all EC2 instances from AWS is disabled in the settings."); - return; - } + _log.Warn($"Preconditions not met! AWS CLI installed {IsAWSCLIInstalled}. AWS Session Manager plugin installed {IsAWSSessionManagerPluginInstalled}. PowerShell configured {IsPowerShellConfigured}."); + return; + } - _log.Info("Sync all EC2 instance(s) from AWS..."); + if (IsSyncing) + { + _log.Info("Skip... Sync is already running!"); + return; + } - if (!IsConfigured) + // Check if profile file is unlocked + if (Application.Current.MainWindow != null) + { + if (((MainWindow)Application.Current.MainWindow).IsProfileFileLocked) { - _log.Warn($"Preconditions not met! AWS CLI installed {IsAWSCLIInstalled}. AWS Session Manager plugin installed {IsAWSSessionManagerPluginInstalled}. PowerShell configured {IsPowerShellConfigured}."); + _log.Warn("The profile file is locked! The profile file must first be unlocked to synchronize the instance IDs and add them as a profile."); return; } + } + else + { + _log.Warn("Cannot find MainWindow because it is null!"); + return; + } - if (IsSyncing) - { - _log.Info("Skip... Sync is already running!"); - return; - } + IsSyncing = true; - // Check if profile file is unlocked - if (Application.Current.MainWindow != null) - { - if (((MainWindow)Application.Current.MainWindow).IsProfileFileLocked) - { - _log.Warn("The profile file is locked! The profile file must first be unlocked to synchronize the instance IDs and add them as a profile."); - return; - } - } - else + foreach (var profile in SettingsManager.Current.AWSSessionManager_AWSProfiles) + { + if (!profile.IsEnabled) { - _log.Warn("Cannot find MainWindow because it is null!"); - return; + _log.Info($"Skip AWS profile \"[{profile.Profile}\\{profile.Region}]\" because it is disabled!"); + continue; } - IsSyncing = true; + await SyncInstanceIDsFromAWS(profile.Profile, profile.Region); + } - foreach (var profile in SettingsManager.Current.AWSSessionManager_AWSProfiles) - { - if (!profile.IsEnabled) - { - _log.Info($"Skip AWS profile \"[{profile.Profile}\\{profile.Region}]\" because it is disabled!"); - continue; - } + await Task.Delay(2000); - await SyncInstanceIDsFromAWS(profile.Profile, profile.Region); - } + _log.Info("All Instance IDs synced from AWS!"); - await Task.Delay(2000); + IsSyncing = false; + } - _log.Info("All Instance IDs synced from AWS!"); + private async Task SyncGroupInstanceIDsFromAWS(string group) + { + _log.Info($"Sync group \"{group}\"..."); - IsSyncing = false; - } + IsSyncing = true; + + // Extract "profile\region" from "~ [profile\region]" + Regex regex = new(@"\[(.*?)\]"); + var result = regex.Match(group); - private async Task SyncGroupInstanceIDsFromAWS(string group) + if (result.Success) { - _log.Info($"Sync group \"{group}\"..."); + // Split "profile\region" into profile and region + var groupData = result.Groups[1].Value.Split(@"\"); + await SyncInstanceIDsFromAWS(groupData[0], groupData[1]); + } + else + { + _log.Error($"Could not extract AWS profile and AWS region from \"{group}\"!"); + } - IsSyncing = true; + await Task.Delay(2000); - // Extract "profile\region" from "~ [profile\region]" - Regex regex = new(@"\[(.*?)\]"); - var result = regex.Match(group); + _log.Info($"Group synced!"); - if (result.Success) - { - // Split "profile\region" into profile and region - var groupData = result.Groups[1].Value.Split(@"\"); - await SyncInstanceIDsFromAWS(groupData[0], groupData[1]); - } - else - { - _log.Error($"Could not extract AWS profile and AWS region from \"{group}\"!"); - } + IsSyncing = false; + } - await Task.Delay(2000); + private async Task SyncInstanceIDsFromAWS(string profile, string region) + { + _log.Info($"Sync EC2 Instance(s) for AWS profile \"[{profile}\\{region}]\"..."); - _log.Info($"Group synced!"); + CredentialProfileStoreChain credentialProfileStoreChain = new(); + credentialProfileStoreChain.TryGetAWSCredentials(profile, out AWSCredentials credentials); - IsSyncing = false; + if (credentials == null) + { + _log.Error($"Could not detect AWS credentials for AWS profile \"{profile}\"! You can configure them in the file \"%USERPROFILE%\\.aws\\config\" or via aws cli with the command \"aws configure --profile \" "); + return; } - private async Task SyncInstanceIDsFromAWS(string profile, string region) - { - _log.Info($"Sync EC2 Instance(s) for AWS profile \"[{profile}\\{region}]\"..."); + using AmazonEC2Client client = new(credentials, RegionEndpoint.GetBySystemName(region)); - CredentialProfileStoreChain credentialProfileStoreChain = new(); - credentialProfileStoreChain.TryGetAWSCredentials(profile, out AWSCredentials credentials); + DescribeInstancesResponse response = null; - if (credentials == null) - { - _log.Error($"Could not detect AWS credentials for AWS profile \"{profile}\"! You can configure them in the file \"%USERPROFILE%\\.aws\\config\" or via aws cli with the command \"aws configure --profile \" "); - return; - } + try + { + response = await client.DescribeInstancesAsync(); + } + catch (AmazonEC2Exception ex) + { + _log.Error($"Could not get EC2 Instance(s) from AWS! Error message: \"{ex.Message}\""); + return; + } - using AmazonEC2Client client = new(credentials, RegionEndpoint.GetBySystemName(region)); + var groupName = $"~ [{profile}\\{region}]"; - DescribeInstancesResponse response = null; + // Create a new group info for profiles + var groupInfo = new GroupInfo() + { + Name = groupName, + IsDynamic = true, + }; - try - { - response = await client.DescribeInstancesAsync(); - } - catch (AmazonEC2Exception ex) + foreach (var reservation in response.Reservations) + { + foreach (var instance in reservation.Instances) { - _log.Error($"Could not get EC2 Instance(s) from AWS! Error message: \"{ex.Message}\""); - return; - } + if (SettingsManager.Current.AWSSessionManager_SyncOnlyRunningInstancesFromAWS && instance.State.Name.Value != "running") + continue; - var groupName = $"~ [{profile}\\{region}]"; + var tagName = instance.Tags.FirstOrDefault(x => x.Key == "Name"); - // Create a new group info for profiles - var groupInfo = new GroupInfo() - { - Name = groupName, - IsDynamic = true, - }; + var name = (tagName == null || tagName.Value == null) ? instance.InstanceId : $"{tagName.Value} ({instance.InstanceId})"; - foreach (var reservation in response.Reservations) - { - foreach (var instance in reservation.Instances) + groupInfo.Profiles.Add(new ProfileInfo() { - if (SettingsManager.Current.AWSSessionManager_SyncOnlyRunningInstancesFromAWS && instance.State.Name.Value != "running") - continue; - - var tagName = instance.Tags.FirstOrDefault(x => x.Key == "Name"); - - var name = (tagName == null || tagName.Value == null) ? instance.InstanceId : $"{tagName.Value} ({instance.InstanceId})"; - - groupInfo.Profiles.Add(new ProfileInfo() - { - Name = name, - Host = instance.InstanceId, - Group = $"~ [{profile}\\{region}]", - IsDynamic = true, - - AWSSessionManager_Enabled = true, - AWSSessionManager_InstanceID = instance.InstanceId, - AWSSessionManager_OverrideProfile = true, - AWSSessionManager_Profile = profile, - AWSSessionManager_OverrideRegion = true, - AWSSessionManager_Region = region - }); - } + Name = name, + Host = instance.InstanceId, + Group = $"~ [{profile}\\{region}]", + IsDynamic = true, + + AWSSessionManager_Enabled = true, + AWSSessionManager_InstanceID = instance.InstanceId, + AWSSessionManager_OverrideProfile = true, + AWSSessionManager_Profile = profile, + AWSSessionManager_OverrideRegion = true, + AWSSessionManager_Region = region + }); } + } - // Remove, replace or add group - var profilesChangedCurrentState = ProfileManager.ProfilesChanged; - ProfileManager.ProfilesChanged = false; + // Remove, replace or add group + var profilesChangedCurrentState = ProfileManager.ProfilesChanged; + ProfileManager.ProfilesChanged = false; - if (groupInfo.Profiles.Count == 0) - { - if (ProfileManager.GroupExists(groupName)) - ProfileManager.RemoveGroup(ProfileManager.GetGroup(groupName)); - - _log.Info("No EC2 Instance(s) found!"); - } - else - { + if (groupInfo.Profiles.Count == 0) + { + if (ProfileManager.GroupExists(groupName)) + ProfileManager.RemoveGroup(ProfileManager.GetGroup(groupName)); - if (ProfileManager.GroupExists(groupName)) - ProfileManager.ReplaceGroup(ProfileManager.GetGroup(groupName), groupInfo); - else - ProfileManager.AddGroup(groupInfo); + _log.Info("No EC2 Instance(s) found!"); + } + else + { - _log.Info($"Found {groupInfo.Profiles.Count} EC2 Instance(s) and added them to the group \"{groupName}\"!"); - } + if (ProfileManager.GroupExists(groupName)) + ProfileManager.ReplaceGroup(ProfileManager.GetGroup(groupName), groupInfo); + else + ProfileManager.AddGroup(groupInfo); - ProfileManager.ProfilesChanged = profilesChangedCurrentState; + _log.Info($"Found {groupInfo.Profiles.Count} EC2 Instance(s) and added them to the group \"{groupName}\"!"); } - private void RemoveDynamicGroups() + ProfileManager.ProfilesChanged = profilesChangedCurrentState; + } + + private void RemoveDynamicGroups() + { + foreach (var profile in SettingsManager.Current.AWSSessionManager_AWSProfiles) { - foreach (var profile in SettingsManager.Current.AWSSessionManager_AWSProfiles) - { - if (!profile.IsEnabled) - continue; + if (!profile.IsEnabled) + continue; - RemoveDynamicGroup(profile.Profile, profile.Region); - } + RemoveDynamicGroup(profile.Profile, profile.Region); } + } - private void RemoveDynamicGroup(string profile, string region) - { - string groupName = $"~ [{profile}\\{region}]"; + private void RemoveDynamicGroup(string profile, string region) + { + string groupName = $"~ [{profile}\\{region}]"; - //Debug.WriteLine("Remove dynamic group: " + groupName); + //Debug.WriteLine("Remove dynamic group: " + groupName); - var profilesChangedCurrentState = ProfileManager.ProfilesChanged; - ProfileManager.ProfilesChanged = false; + var profilesChangedCurrentState = ProfileManager.ProfilesChanged; + ProfileManager.ProfilesChanged = false; - if (ProfileManager.GroupExists(groupName)) - ProfileManager.RemoveGroup(ProfileManager.GetGroup(groupName)); + if (ProfileManager.GroupExists(groupName)) + ProfileManager.RemoveGroup(ProfileManager.GetGroup(groupName)); - ProfileManager.ProfilesChanged = profilesChangedCurrentState; - } + ProfileManager.ProfilesChanged = profilesChangedCurrentState; + } - private async Task Connect() + private async Task Connect() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Connect - }; + Title = Localization.Resources.Strings.Connect + }; - var connectViewModel = new AWSSessionManagerConnectViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - - // Create profile info - var info = new AWSSessionManagerSessionInfo - { - InstanceID = instance.InstanceID, - Profile = instance.Profile, - Region = instance.Region - }; - - // Add to history - // Note: The history can only be updated after the values have been read. - // Otherwise, in some cases, incorrect values are taken over. - AddInstanceIDToHistory(instance.InstanceID); - AddProfileToHistory(instance.Profile); - AddRegionToHistory(instance.Region); - - // Connect - Connect(info); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - }); + var connectViewModel = new AWSSessionManagerConnectViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - customDialog.Content = new AWSSessionManagerConnectDialog + // Create profile info + var info = new AWSSessionManagerSessionInfo { - DataContext = connectViewModel + InstanceID = instance.InstanceID, + Profile = instance.Profile, + Region = instance.Region }; - ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + // Add to history + // Note: The history can only be updated after the values have been read. + // Otherwise, in some cases, incorrect values are taken over. + AddInstanceIDToHistory(instance.InstanceID); + AddProfileToHistory(instance.Profile); + AddRegionToHistory(instance.Region); - private void ConnectProfile() + // Connect + Connect(info); + }, async instance => { - Connect(NETworkManager.Profiles.Application.AWSSessionManager.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); - } + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; + }); - private void ConnectProfileExternal() + customDialog.Content = new AWSSessionManagerConnectDialog { - Process.Start(new ProcessStartInfo() - { - FileName = SettingsManager.Current.AWSSessionManager_ApplicationFilePath, - Arguments = AWSSessionManager.BuildCommandLine(NETworkManager.Profiles.Application.AWSSessionManager.CreateSessionInfo(SelectedProfile)) - }); - } + DataContext = connectViewModel + }; + + ConfigurationManager.Current.IsDialogOpen = true; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + private void ConnectProfile() + { + Connect(NETworkManager.Profiles.Application.AWSSessionManager.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); + } - private void Connect(AWSSessionManagerSessionInfo sessionInfo, string header = null) + private void ConnectProfileExternal() + { + Process.Start(new ProcessStartInfo() { - sessionInfo.ApplicationFilePath = SettingsManager.Current.AWSSessionManager_ApplicationFilePath; + FileName = SettingsManager.Current.AWSSessionManager_ApplicationFilePath, + Arguments = AWSSessionManager.BuildCommandLine(NETworkManager.Profiles.Application.AWSSessionManager.CreateSessionInfo(SelectedProfile)) + }); + } - TabItems.Add(new DragablzTabItem(header ?? sessionInfo.InstanceID, new AWSSessionManagerControl(sessionInfo))); + private void Connect(AWSSessionManagerSessionInfo sessionInfo, string header = null) + { + sessionInfo.ApplicationFilePath = SettingsManager.Current.AWSSessionManager_ApplicationFilePath; - // Select the added tab - _disableFocusEmbeddedWindow = true; - SelectedTabItem = TabItems.Last(); - _disableFocusEmbeddedWindow = false; - } + TabItems.Add(new DragablzTabItem(header ?? sessionInfo.InstanceID, new AWSSessionManagerControl(sessionInfo))); - // Modify history list - private static void AddInstanceIDToHistory(string instanceID) - { - if (string.IsNullOrEmpty(instanceID)) - return; + // Select the added tab + _disableFocusEmbeddedWindow = true; + SelectedTabItem = TabItems.Last(); + _disableFocusEmbeddedWindow = false; + } - SettingsManager.Current.AWSSessionManager_InstanceIDHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.AWSSessionManager_InstanceIDHistory.ToList(), instanceID, SettingsManager.Current.General_HistoryListEntries)); - } + // Modify history list + private static void AddInstanceIDToHistory(string instanceID) + { + if (string.IsNullOrEmpty(instanceID)) + return; - private static void AddProfileToHistory(string profile) - { - if (string.IsNullOrEmpty(profile)) - return; + SettingsManager.Current.AWSSessionManager_InstanceIDHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.AWSSessionManager_InstanceIDHistory.ToList(), instanceID, SettingsManager.Current.General_HistoryListEntries)); + } - SettingsManager.Current.AWSSessionManager_ProfileHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.AWSSessionManager_ProfileHistory.ToList(), profile, SettingsManager.Current.General_HistoryListEntries)); - } + private static void AddProfileToHistory(string profile) + { + if (string.IsNullOrEmpty(profile)) + return; - private static void AddRegionToHistory(string region) - { - if (string.IsNullOrEmpty(region)) - return; + SettingsManager.Current.AWSSessionManager_ProfileHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.AWSSessionManager_ProfileHistory.ToList(), profile, SettingsManager.Current.General_HistoryListEntries)); + } - SettingsManager.Current.AWSSessionManager_RegionHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.AWSSessionManager_RegionHistory.ToList(), region, SettingsManager.Current.General_HistoryListEntries)); - } + private static void AddRegionToHistory(string region) + { + if (string.IsNullOrEmpty(region)) + return; + + SettingsManager.Current.AWSSessionManager_RegionHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.AWSSessionManager_RegionHistory.ToList(), region, SettingsManager.Current.General_HistoryListEntries)); + } - private void StartDelayedSearch() + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } - if (dueToChangedSize) + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; + + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void FocusEmbeddedWindow() - { - /* Don't continue if - - Search TextBox is focused - - Header ContextMenu is opened - - Profile ContextMenu is opened - */ - if (TextBoxSearchIsFocused || HeaderContextMenuIsOpen || ProfileContextMenuIsOpen) - return; - - (SelectedTabItem?.View as AWSSessionManagerControl)?.FocusEmbeddedWindow(); - } - - public void OnViewVisible(bool fromSettings) - { - _isViewActive = true; + _canProfileWidthChange = true; + } - RefreshProfiles(); + public void FocusEmbeddedWindow() + { + /* Don't continue if + - Search TextBox is focused + - Header ContextMenu is opened + - Profile ContextMenu is opened + */ + if (TextBoxSearchIsFocused || HeaderContextMenuIsOpen || ProfileContextMenuIsOpen) + return; + + (SelectedTabItem?.View as AWSSessionManagerControl)?.FocusEmbeddedWindow(); + } - // Do not synchronize If the view becomes visible again - // after the settings have been opened - if (!fromSettings) - SyncAllInstanceIDsFromAWS(); - } + public void OnViewVisible(bool fromSettings) + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); - public void OnProfileLoaded() - { + // Do not synchronize If the view becomes visible again + // after the settings have been opened + if (!fromSettings) SyncAllInstanceIDsFromAWS(); - } + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void OnProfileLoaded() + { + SyncAllInstanceIDsFromAWS(); + } - public void OnProfileDialogOpen() - { - ConfigurationManager.Current.IsDialogOpen = true; - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogClose() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - ConfigurationManager.Current.IsDialogOpen = false; - } - #endregion + Profiles.Refresh(); + })); + } - #region Event - private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - if (e.PropertyName == nameof(SettingsInfo.AWSSessionManager_EnableSyncInstanceIDsFromAWS)) - { - IsSyncEnabled = SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS; + public void OnProfileDialogOpen() + { + ConfigurationManager.Current.IsDialogOpen = true; + } - if (IsSyncEnabled) - SyncAllInstanceIDsFromAWS(); - else - RemoveDynamicGroups(); - } + public void OnProfileDialogClose() + { + ConfigurationManager.Current.IsDialogOpen = false; + } + #endregion - if (e.PropertyName == nameof(SettingsInfo.AWSSessionManager_SyncOnlyRunningInstancesFromAWS)) - SyncAllInstanceIDsFromAWS(); + #region Event + private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(SettingsInfo.AWSSessionManager_EnableSyncInstanceIDsFromAWS)) + { + IsSyncEnabled = SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS; - if (e.PropertyName == nameof(SettingsInfo.AWSSessionManager_ApplicationFilePath)) - CheckSettings(); + if (IsSyncEnabled) + SyncAllInstanceIDsFromAWS(); + else + RemoveDynamicGroups(); } - private void AWSSessionManager_AWSProfiles_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) + if (e.PropertyName == nameof(SettingsInfo.AWSSessionManager_SyncOnlyRunningInstancesFromAWS)) + SyncAllInstanceIDsFromAWS(); + + if (e.PropertyName == nameof(SettingsInfo.AWSSessionManager_ApplicationFilePath)) + CheckSettings(); + } + + private void AWSSessionManager_AWSProfiles_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) + { + // Remove groups + if (e.OldItems != null) { - // Remove groups - if (e.OldItems != null) + foreach (AWSProfileInfo profile in e.OldItems) { - foreach (AWSProfileInfo profile in e.OldItems) - { - RemoveDynamicGroup(profile.Profile, profile.Region); - } + RemoveDynamicGroup(profile.Profile, profile.Region); } + } - // Sync new groups - if (e.NewItems != null) + // Sync new groups + if (e.NewItems != null) + { + foreach (AWSProfileInfo profile in e.NewItems) { - foreach (AWSProfileInfo profile in e.NewItems) - { - if (profile.IsEnabled) - SyncInstanceIDsFromAWS(profile.Profile, profile.Region); - } + if (profile.IsEnabled) + SyncInstanceIDsFromAWS(profile.Profile, profile.Region); } } + } - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/AWSSessionManagerSettingsViewModel.cs b/Source/NETworkManager/ViewModels/AWSSessionManagerSettingsViewModel.cs index 7a62db1ca4..3bd6b5e51c 100644 --- a/Source/NETworkManager/ViewModels/AWSSessionManagerSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/AWSSessionManagerSettingsViewModel.cs @@ -11,302 +11,301 @@ using System.ComponentModel; using System.Windows.Data; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class AWSSessionManagerSettingsViewModel : ViewModelBase { - public class AWSSessionManagerSettingsViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading; + private readonly bool _isLoading; - private bool _enableSyncInstanceIDsFromAWS; - public bool EnableSyncInstanceIDsFromAWS + private bool _enableSyncInstanceIDsFromAWS; + public bool EnableSyncInstanceIDsFromAWS + { + get => _enableSyncInstanceIDsFromAWS; + set { - get => _enableSyncInstanceIDsFromAWS; - set - { - if (value == _enableSyncInstanceIDsFromAWS) - return; - - if (!_isLoading) - SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS = value; - - _enableSyncInstanceIDsFromAWS = value; - OnPropertyChanged(); - } + if (value == _enableSyncInstanceIDsFromAWS) + return; + + if (!_isLoading) + SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS = value; + + _enableSyncInstanceIDsFromAWS = value; + OnPropertyChanged(); } + } - public ICollectionView AWSProfiles { get; } + public ICollectionView AWSProfiles { get; } - private AWSProfileInfo _selectedAWSProfile = new AWSProfileInfo(); - public AWSProfileInfo SelectedAWSProfile + private AWSProfileInfo _selectedAWSProfile = new AWSProfileInfo(); + public AWSProfileInfo SelectedAWSProfile + { + get => _selectedAWSProfile; + set { - get => _selectedAWSProfile; - set - { - if (value == _selectedAWSProfile) - return; - - _selectedAWSProfile = value; - OnPropertyChanged(); - } + if (value == _selectedAWSProfile) + return; + + _selectedAWSProfile = value; + OnPropertyChanged(); } + } - private bool _syncOnlyRunningInstancesFromAWS; - public bool SyncOnlyRunningInstancesFromAWS + private bool _syncOnlyRunningInstancesFromAWS; + public bool SyncOnlyRunningInstancesFromAWS + { + get => _syncOnlyRunningInstancesFromAWS; + set { - get => _syncOnlyRunningInstancesFromAWS; - set - { - if (value == _syncOnlyRunningInstancesFromAWS) - return; - - if(!_isLoading) - SettingsManager.Current.AWSSessionManager_SyncOnlyRunningInstancesFromAWS = value; - - _syncOnlyRunningInstancesFromAWS = value; - OnPropertyChanged(); - } + if (value == _syncOnlyRunningInstancesFromAWS) + return; + + if(!_isLoading) + SettingsManager.Current.AWSSessionManager_SyncOnlyRunningInstancesFromAWS = value; + + _syncOnlyRunningInstancesFromAWS = value; + OnPropertyChanged(); } + } - private string _defaultProfile; - public string DefaultProfile + private string _defaultProfile; + public string DefaultProfile + { + get => _defaultProfile; + set { - get => _defaultProfile; - set - { - if (value == _defaultProfile) - return; - - if (!_isLoading) - SettingsManager.Current.AWSSessionManager_DefaultProfile = value; - - _defaultProfile = value; - OnPropertyChanged(); - } + if (value == _defaultProfile) + return; + + if (!_isLoading) + SettingsManager.Current.AWSSessionManager_DefaultProfile = value; + + _defaultProfile = value; + OnPropertyChanged(); } + } - private string _defaultRegion; - public string DefaultRegion + private string _defaultRegion; + public string DefaultRegion + { + get => _defaultRegion; + set { - get => _defaultRegion; - set - { - if (value == _defaultRegion) - return; - - if (!_isLoading) - SettingsManager.Current.AWSSessionManager_DefaultRegion = value; - - _defaultRegion = value; - OnPropertyChanged(); - } + if (value == _defaultRegion) + return; + + if (!_isLoading) + SettingsManager.Current.AWSSessionManager_DefaultRegion = value; + + _defaultRegion = value; + OnPropertyChanged(); } + } - private string _applicationFilePath; - public string ApplicationFilePath + private string _applicationFilePath; + public string ApplicationFilePath + { + get => _applicationFilePath; + set { - get => _applicationFilePath; - set - { - if (value == _applicationFilePath) - return; + if (value == _applicationFilePath) + return; - if (!_isLoading) - SettingsManager.Current.AWSSessionManager_ApplicationFilePath = value; + if (!_isLoading) + SettingsManager.Current.AWSSessionManager_ApplicationFilePath = value; - IsConfigured = !string.IsNullOrEmpty(value); + IsConfigured = !string.IsNullOrEmpty(value); - _applicationFilePath = value; - OnPropertyChanged(); - } + _applicationFilePath = value; + OnPropertyChanged(); } + } - private bool _isConfigured; - public bool IsConfigured + private bool _isConfigured; + public bool IsConfigured + { + get => _isConfigured; + set { - get => _isConfigured; - set - { - if (value == _isConfigured) - return; - - _isConfigured = value; - OnPropertyChanged(); - } + if (value == _isConfigured) + return; + + _isConfigured = value; + OnPropertyChanged(); } - #endregion + } + #endregion + + #region Contructor, load settings + public AWSSessionManagerSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; + + _dialogCoordinator = instance; + + AWSProfiles = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_AWSProfiles); + AWSProfiles.SortDescriptions.Add(new SortDescription(nameof(AWSProfileInfo.Profile), ListSortDirection.Ascending)); + AWSProfiles.SortDescriptions.Add(new SortDescription(nameof(AWSProfileInfo.Region), ListSortDirection.Ascending)); + + LoadSettings(); + + _isLoading = false; + } + + private void LoadSettings() + { + EnableSyncInstanceIDsFromAWS = SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS; + SyncOnlyRunningInstancesFromAWS = SettingsManager.Current.AWSSessionManager_SyncOnlyRunningInstancesFromAWS; + DefaultProfile = SettingsManager.Current.AWSSessionManager_DefaultProfile; + DefaultRegion = SettingsManager.Current.AWSSessionManager_DefaultRegion; + ApplicationFilePath = SettingsManager.Current.AWSSessionManager_ApplicationFilePath; + IsConfigured = File.Exists(ApplicationFilePath); + } + #endregion + + #region ICommands & Actions + public ICommand AddAWSProfileCommand => new RelayCommand(p => AddAWSProfileAction()); + + private void AddAWSProfileAction() + { + AddAWSProfile(); + } - #region Contructor, load settings - public AWSSessionManagerSettingsViewModel(IDialogCoordinator instance) + public ICommand EditAWSProfileCommand => new RelayCommand(p => EditAWSProfileAction()); + + private void EditAWSProfileAction() + { + EditAWSProfile(); + } + + public ICommand DeleteAWSProfileCommand => new RelayCommand(p => DeleteAWSProfileAction()); + + private void DeleteAWSProfileAction() + { + DeleteAWSProfile(); + } + + public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); + + private void BrowseFileAction() + { + var openFileDialog = new System.Windows.Forms.OpenFileDialog { - _isLoading = true; + Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter + }; - _dialogCoordinator = instance; + if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + ApplicationFilePath = openFileDialog.FileName; + } - AWSProfiles = CollectionViewSource.GetDefaultView(SettingsManager.Current.AWSSessionManager_AWSProfiles); - AWSProfiles.SortDescriptions.Add(new SortDescription(nameof(AWSProfileInfo.Profile), ListSortDirection.Ascending)); - AWSProfiles.SortDescriptions.Add(new SortDescription(nameof(AWSProfileInfo.Region), ListSortDirection.Ascending)); + public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); - LoadSettings(); + private void ConfigureAction() + { + Configure(); + } + #endregion - _isLoading = false; - } + #region Methods + public async Task AddAWSProfile() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.AddAWSProfile + }; - private void LoadSettings() + var viewModel = new AWSProfileViewModel(instance => { - EnableSyncInstanceIDsFromAWS = SettingsManager.Current.AWSSessionManager_EnableSyncInstanceIDsFromAWS; - SyncOnlyRunningInstancesFromAWS = SettingsManager.Current.AWSSessionManager_SyncOnlyRunningInstancesFromAWS; - DefaultProfile = SettingsManager.Current.AWSSessionManager_DefaultProfile; - DefaultRegion = SettingsManager.Current.AWSSessionManager_DefaultRegion; - ApplicationFilePath = SettingsManager.Current.AWSSessionManager_ApplicationFilePath; - IsConfigured = File.Exists(ApplicationFilePath); - } - #endregion + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - #region ICommands & Actions - public ICommand AddAWSProfileCommand => new RelayCommand(p => AddAWSProfileAction()); + SettingsManager.Current.AWSSessionManager_AWSProfiles.Add(new AWSProfileInfo(instance.IsEnabled, instance.Profile, instance.Region)); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - private void AddAWSProfileAction() + customDialog.Content = new AWSProfileDialog { - AddAWSProfile(); - } + DataContext = viewModel + }; - public ICommand EditAWSProfileCommand => new RelayCommand(p => EditAWSProfileAction()); + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + public async Task EditAWSProfile() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.EditAWSProfile + }; - private void EditAWSProfileAction() + var viewModel = new AWSProfileViewModel(instance => { - EditAWSProfile(); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - public ICommand DeleteAWSProfileCommand => new RelayCommand(p => DeleteAWSProfileAction()); + SettingsManager.Current.AWSSessionManager_AWSProfiles.Remove(SelectedAWSProfile); + SettingsManager.Current.AWSSessionManager_AWSProfiles.Add(new AWSProfileInfo(instance.IsEnabled, instance.Profile, instance.Region)); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, true, SelectedAWSProfile); - private void DeleteAWSProfileAction() + customDialog.Content = new AWSProfileDialog { - DeleteAWSProfile(); - } + DataContext = viewModel + }; - public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + public async Task DeleteAWSProfile() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.DeleteAWSProfile + }; - private void BrowseFileAction() + var viewModel = new ConfirmDeleteViewModel(instance => { - var openFileDialog = new System.Windows.Forms.OpenFileDialog - { - Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter - }; + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - ApplicationFilePath = openFileDialog.FileName; - } + SettingsManager.Current.AWSSessionManager_AWSProfiles.Remove(SelectedAWSProfile); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, Localization.Resources.Strings.DeleteAWSProfileMessage); - public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); + customDialog.Content = new ConfirmDeleteDialog + { + DataContext = viewModel + }; - private void ConfigureAction() + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + private async Task Configure() + { + try { - Configure(); + Process.Start(SettingsManager.Current.AWSSessionManager_ApplicationFilePath); } - #endregion - - #region Methods - public async Task AddAWSProfile() - { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddAWSProfile - }; - - var viewModel = new AWSProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.AWSSessionManager_AWSProfiles.Add(new AWSProfileInfo(instance.IsEnabled, instance.Profile, instance.Region)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); - - customDialog.Content = new AWSProfileDialog - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - - public async Task EditAWSProfile() - { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.EditAWSProfile - }; - - var viewModel = new AWSProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.AWSSessionManager_AWSProfiles.Remove(SelectedAWSProfile); - SettingsManager.Current.AWSSessionManager_AWSProfiles.Add(new AWSProfileInfo(instance.IsEnabled, instance.Profile, instance.Region)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, true, SelectedAWSProfile); - - customDialog.Content = new AWSProfileDialog - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - - public async Task DeleteAWSProfile() - { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.DeleteAWSProfile - }; - - var viewModel = new ConfirmDeleteViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.AWSSessionManager_AWSProfiles.Remove(SelectedAWSProfile); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, Localization.Resources.Strings.DeleteAWSProfileMessage); - - customDialog.Content = new ConfirmDeleteDialog - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - - private async Task Configure() + catch (Exception ex) { - try - { - Process.Start(SettingsManager.Current.AWSSessionManager_ApplicationFilePath); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); - } - } + var settings = AppearanceManager.MetroDialog; - public void SetFilePathFromDragDrop(string filePath) - { - ApplicationFilePath = filePath; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - OnPropertyChanged(nameof(ApplicationFilePath)); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); } - #endregion } + + public void SetFilePathFromDragDrop(string filePath) + { + ApplicationFilePath = filePath; + + OnPropertyChanged(nameof(ApplicationFilePath)); + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/AboutViewModel.cs b/Source/NETworkManager/ViewModels/AboutViewModel.cs index 3e0578ace6..b51075b05b 100644 --- a/Source/NETworkManager/ViewModels/AboutViewModel.cs +++ b/Source/NETworkManager/ViewModels/AboutViewModel.cs @@ -10,237 +10,236 @@ using NETworkManager.Documentation; using NETworkManager.Properties; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class AboutViewModel : ViewModelBase { - public class AboutViewModel : ViewModelBase - { - #region Variables - public string Version => $"{Strings.Version} {AssemblyManager.Current.Version}"; - public string DevelopedByText => string.Format(Strings.DevelopedAndMaintainedByX + " ", Resources.NETworkManager_GitHub_User); + #region Variables + public string Version => $"{Strings.Version} {AssemblyManager.Current.Version}"; + public string DevelopedByText => string.Format(Strings.DevelopedAndMaintainedByX + " ", Resources.NETworkManager_GitHub_User); - private bool _isUpdateCheckRunning; - public bool IsUpdateCheckRunning + private bool _isUpdateCheckRunning; + public bool IsUpdateCheckRunning + { + get => _isUpdateCheckRunning; + set { - get => _isUpdateCheckRunning; - set - { - if (value == _isUpdateCheckRunning) - return; - - _isUpdateCheckRunning = value; - OnPropertyChanged(); - } + if (value == _isUpdateCheckRunning) + return; + + _isUpdateCheckRunning = value; + OnPropertyChanged(); } + } - private bool _isUpdateAvailable; - public bool IsUpdateAvailable + private bool _isUpdateAvailable; + public bool IsUpdateAvailable + { + get => _isUpdateAvailable; + set { - get => _isUpdateAvailable; - set - { - if (value == _isUpdateAvailable) - return; - - _isUpdateAvailable = value; - OnPropertyChanged(); - } + if (value == _isUpdateAvailable) + return; + + _isUpdateAvailable = value; + OnPropertyChanged(); } + } - private string _updateText; - public string UpdateText + private string _updateText; + public string UpdateText + { + get => _updateText; + set { - get => _updateText; - set - { - if (value == _updateText) - return; - - _updateText = value; - OnPropertyChanged(); - } + if (value == _updateText) + return; + + _updateText = value; + OnPropertyChanged(); } + } - private string _updateReleaseUrl; - public string UpdateReleaseUrl + private string _updateReleaseUrl; + public string UpdateReleaseUrl + { + get => _updateReleaseUrl; + set { - get => _updateReleaseUrl; - set - { - if (value == _updateReleaseUrl) - return; - - _updateReleaseUrl = value; - OnPropertyChanged(); - } + if (value == _updateReleaseUrl) + return; + + _updateReleaseUrl = value; + OnPropertyChanged(); } + } - private bool _showUpdaterMessage; - public bool ShowUpdaterMessage + private bool _showUpdaterMessage; + public bool ShowUpdaterMessage + { + get => _showUpdaterMessage; + set { - get => _showUpdaterMessage; - set - { - if (value == _showUpdaterMessage) - return; - - _showUpdaterMessage = value; - OnPropertyChanged(); - } + if (value == _showUpdaterMessage) + return; + + _showUpdaterMessage = value; + OnPropertyChanged(); } + } - private string _updaterMessage; - public string UpdaterMessage + private string _updaterMessage; + public string UpdaterMessage + { + get => _updaterMessage; + set { - get => _updaterMessage; - set - { - if (value == _updaterMessage) - return; - - _updaterMessage = value; - OnPropertyChanged(); - } + if (value == _updaterMessage) + return; + + _updaterMessage = value; + OnPropertyChanged(); } + } - public ICollectionView LibrariesView { get; } + public ICollectionView LibrariesView { get; } - private LibraryInfo _selectedLibraryInfo; - public LibraryInfo SelectedLibraryInfo + private LibraryInfo _selectedLibraryInfo; + public LibraryInfo SelectedLibraryInfo + { + get => _selectedLibraryInfo; + set { - get => _selectedLibraryInfo; - set - { - if (value == _selectedLibraryInfo) - return; - - _selectedLibraryInfo = value; - OnPropertyChanged(); - } + if (value == _selectedLibraryInfo) + return; + + _selectedLibraryInfo = value; + OnPropertyChanged(); } + } - public ICollectionView ExternalServicesView { get; } + public ICollectionView ExternalServicesView { get; } - private ExternalServicesInfo _selectedExternalServicesInfo; - public ExternalServicesInfo SelectedExternalServicesInfo + private ExternalServicesInfo _selectedExternalServicesInfo; + public ExternalServicesInfo SelectedExternalServicesInfo + { + get => _selectedExternalServicesInfo; + set { - get => _selectedExternalServicesInfo; - set - { - if (value == _selectedExternalServicesInfo) - return; - - _selectedExternalServicesInfo = value; - OnPropertyChanged(); - } + if (value == _selectedExternalServicesInfo) + return; + + _selectedExternalServicesInfo = value; + OnPropertyChanged(); } + } - public ICollectionView ResourcesView { get; } + public ICollectionView ResourcesView { get; } - private ResourceInfo _selectedResourceInfo; - public ResourceInfo SelectedResourceInfo + private ResourceInfo _selectedResourceInfo; + public ResourceInfo SelectedResourceInfo + { + get => _selectedResourceInfo; + set { - get => _selectedResourceInfo; - set - { - if (value == _selectedResourceInfo) - return; - - _selectedResourceInfo = value; - OnPropertyChanged(); - } + if (value == _selectedResourceInfo) + return; + + _selectedResourceInfo = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor - public AboutViewModel() - { - LibrariesView = CollectionViewSource.GetDefaultView(LibraryManager.List); - LibrariesView.SortDescriptions.Add(new SortDescription(nameof(LibraryInfo.Name), ListSortDirection.Ascending)); + #region Constructor + public AboutViewModel() + { + LibrariesView = CollectionViewSource.GetDefaultView(LibraryManager.List); + LibrariesView.SortDescriptions.Add(new SortDescription(nameof(LibraryInfo.Name), ListSortDirection.Ascending)); - ExternalServicesView = CollectionViewSource.GetDefaultView(ExternalServicesManager.List); - ExternalServicesView.SortDescriptions.Add(new SortDescription(nameof(ExternalServicesInfo.Name), ListSortDirection.Ascending)); + ExternalServicesView = CollectionViewSource.GetDefaultView(ExternalServicesManager.List); + ExternalServicesView.SortDescriptions.Add(new SortDescription(nameof(ExternalServicesInfo.Name), ListSortDirection.Ascending)); - ResourcesView = CollectionViewSource.GetDefaultView(ResourceManager.List); - ResourcesView.SortDescriptions.Add(new SortDescription(nameof(ResourceInfo.Name), ListSortDirection.Ascending)); - } - #endregion + ResourcesView = CollectionViewSource.GetDefaultView(ResourceManager.List); + ResourcesView.SortDescriptions.Add(new SortDescription(nameof(ResourceInfo.Name), ListSortDirection.Ascending)); + } + #endregion - #region Commands & Actions - public ICommand CheckForUpdatesCommand => new RelayCommand(p => CheckForUpdatesAction()); + #region Commands & Actions + public ICommand CheckForUpdatesCommand => new RelayCommand(p => CheckForUpdatesAction()); - private void CheckForUpdatesAction() - { - CheckForUpdates(); - } + private void CheckForUpdatesAction() + { + CheckForUpdates(); + } - public ICommand OpenWebsiteCommand => new RelayCommand(OpenWebsiteAction); + public ICommand OpenWebsiteCommand => new RelayCommand(OpenWebsiteAction); - private static void OpenWebsiteAction(object url) - { - ExternalProcessStarter.OpenUrl((string)url); - } + private static void OpenWebsiteAction(object url) + { + ExternalProcessStarter.OpenUrl((string)url); + } - public ICommand OpenDocumentationCommand - { - get { return new RelayCommand(p => OpenDocumentationAction()); } - } + public ICommand OpenDocumentationCommand + { + get { return new RelayCommand(p => OpenDocumentationAction()); } + } - private void OpenDocumentationAction() - { - DocumentationManager.OpenDocumentation(DocumentationIdentifier.Default); - } + private void OpenDocumentationAction() + { + DocumentationManager.OpenDocumentation(DocumentationIdentifier.Default); + } - public ICommand OpenLicenseFolderCommand => new RelayCommand(p => OpenLicenseFolderAction()); + public ICommand OpenLicenseFolderCommand => new RelayCommand(p => OpenLicenseFolderAction()); - private void OpenLicenseFolderAction() - { - Process.Start("explorer.exe", LibraryManager.GetLicenseLocation()); - } - #endregion + private void OpenLicenseFolderAction() + { + Process.Start("explorer.exe", LibraryManager.GetLicenseLocation()); + } + #endregion - #region Methods - private void CheckForUpdates() - { - IsUpdateAvailable = false; - ShowUpdaterMessage = false; + #region Methods + private void CheckForUpdates() + { + IsUpdateAvailable = false; + ShowUpdaterMessage = false; - IsUpdateCheckRunning = true; + IsUpdateCheckRunning = true; - var updater = new Updater(); + var updater = new Updater(); - updater.UpdateAvailable += Updater_UpdateAvailable; - updater.NoUpdateAvailable += Updater_NoUpdateAvailable; - updater.Error += Updater_Error; + updater.UpdateAvailable += Updater_UpdateAvailable; + updater.NoUpdateAvailable += Updater_NoUpdateAvailable; + updater.Error += Updater_Error; - updater.CheckOnGitHub(Resources.NETworkManager_GitHub_User, Resources.NETworkManager_GitHub_Repo, AssemblyManager.Current.Version, SettingsManager.Current.Update_CheckForPreReleases); - } - #endregion + updater.CheckOnGitHub(Resources.NETworkManager_GitHub_User, Resources.NETworkManager_GitHub_Repo, AssemblyManager.Current.Version, SettingsManager.Current.Update_CheckForPreReleases); + } + #endregion - #region Events - private void Updater_UpdateAvailable(object sender, UpdateAvailableArgs e) - { - UpdateText = string.Format(Strings.VersionxxIsAvailable, e.Release.TagName); - UpdateReleaseUrl = e.Release.Prerelease ? e.Release.HtmlUrl : Resources.NETworkManager_LatestReleaseUrl; + #region Events + private void Updater_UpdateAvailable(object sender, UpdateAvailableArgs e) + { + UpdateText = string.Format(Strings.VersionxxIsAvailable, e.Release.TagName); + UpdateReleaseUrl = e.Release.Prerelease ? e.Release.HtmlUrl : Resources.NETworkManager_LatestReleaseUrl; - IsUpdateCheckRunning = false; - IsUpdateAvailable = true; - } + IsUpdateCheckRunning = false; + IsUpdateAvailable = true; + } - private void Updater_NoUpdateAvailable(object sender, EventArgs e) - { - UpdaterMessage = Strings.NoUpdateAvailable; + private void Updater_NoUpdateAvailable(object sender, EventArgs e) + { + UpdaterMessage = Strings.NoUpdateAvailable; - IsUpdateCheckRunning = false; - ShowUpdaterMessage = true; - } + IsUpdateCheckRunning = false; + ShowUpdaterMessage = true; + } - private void Updater_Error(object sender, EventArgs e) - { - UpdaterMessage = Strings.ErrorCheckingApiGithubComVerifyYourNetworkConnection; + private void Updater_Error(object sender, EventArgs e) + { + UpdaterMessage = Strings.ErrorCheckingApiGithubComVerifyYourNetworkConnection; - IsUpdateCheckRunning = false; - ShowUpdaterMessage = true; - } - #endregion + IsUpdateCheckRunning = false; + ShowUpdaterMessage = true; } + #endregion } diff --git a/Source/NETworkManager/ViewModels/BitCalculatorSettingsViewModel.cs b/Source/NETworkManager/ViewModels/BitCalculatorSettingsViewModel.cs index ae33555c71..9c1e692507 100644 --- a/Source/NETworkManager/ViewModels/BitCalculatorSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/BitCalculatorSettingsViewModel.cs @@ -3,50 +3,49 @@ using System.Collections.Generic; using System.Linq; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class BitCalculatorSettingsViewModel : ViewModelBase { - public class BitCalculatorSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - public List Notations { get; set; } + public List Notations { get; set; } - private BitCaluclatorNotation _notation; - public BitCaluclatorNotation Notation + private BitCaluclatorNotation _notation; + public BitCaluclatorNotation Notation + { + get => _notation; + set { - get => _notation; - set - { - if (value == _notation) - return; + if (value == _notation) + return; - if (!_isLoading) - SettingsManager.Current.BitCalculator_Notation = value; + if (!_isLoading) + SettingsManager.Current.BitCalculator_Notation = value; - _notation = value; - OnPropertyChanged(); - } + _notation = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public BitCalculatorSettingsViewModel() - { - _isLoading = true; + #region Constructor, load settings + public BitCalculatorSettingsViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - Notations = System.Enum.GetValues(typeof(BitCaluclatorNotation)).Cast().OrderBy(x => x.ToString()).ToList(); - Notation = Notations.First(x => x == SettingsManager.Current.BitCalculator_Notation); - } - #endregion + private void LoadSettings() + { + Notations = System.Enum.GetValues(typeof(BitCaluclatorNotation)).Cast().OrderBy(x => x.ToString()).ToList(); + Notation = Notations.First(x => x == SettingsManager.Current.BitCalculator_Notation); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs b/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs index 583f182cd8..d507993785 100644 --- a/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs +++ b/Source/NETworkManager/ViewModels/BitCalculatorViewModel.cs @@ -12,191 +12,190 @@ using System.Windows; using log4net; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class BitCalculatorViewModel : ViewModelBase { - public class BitCalculatorViewModel : ViewModelBase - { - #region Variables - private static readonly ILog _log = LogManager.GetLogger(typeof(BitCalculatorViewModel)); - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private static readonly ILog _log = LogManager.GetLogger(typeof(BitCalculatorViewModel)); + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private string _input; - public string Input + private string _input; + public string Input + { + get => _input; + set { - get => _input; - set - { - if (value == _input) - return; - - _input = value; - OnPropertyChanged(); - } + if (value == _input) + return; + + _input = value; + OnPropertyChanged(); } + } - public ICollectionView InputHistoryView { get; } + public ICollectionView InputHistoryView { get; } - private List _units = new(); - public List Units + private List _units = new(); + public List Units + { + get => _units; + set { - get => _units; - set - { - if (value == _units) - return; - - _units = value; - OnPropertyChanged(); - } + if (value == _units) + return; + + _units = value; + OnPropertyChanged(); } + } - private BitCaluclatorUnit _unit; - public BitCaluclatorUnit Unit + private BitCaluclatorUnit _unit; + public BitCaluclatorUnit Unit + { + get => _unit; + set { - get => _unit; - set - { - if (value == _unit) - return; - - if (!_isLoading) - SettingsManager.Current.BitCalculator_Unit = value; - - _unit = value; - OnPropertyChanged(); - } + if (value == _unit) + return; + + if (!_isLoading) + SettingsManager.Current.BitCalculator_Unit = value; + + _unit = value; + OnPropertyChanged(); } + } - private bool _isCalculationRunning; - public bool IsCalculationRunning + private bool _isCalculationRunning; + public bool IsCalculationRunning + { + get => _isCalculationRunning; + set { - get => _isCalculationRunning; - set - { - if (value == _isCalculationRunning) - return; - - _isCalculationRunning = value; - OnPropertyChanged(); - } + if (value == _isCalculationRunning) + return; + + _isCalculationRunning = value; + OnPropertyChanged(); } + } - private bool _isResultVisible; - public bool IsResultVisible + private bool _isResultVisible; + public bool IsResultVisible + { + get => _isResultVisible; + set { - get => _isResultVisible; - set - { - if (value == _isResultVisible) - return; + if (value == _isResultVisible) + return; - _isResultVisible = value; - OnPropertyChanged(); - } + _isResultVisible = value; + OnPropertyChanged(); } + } - private BitCaluclatorInfo _result = new(); - public BitCaluclatorInfo Result + private BitCaluclatorInfo _result = new(); + public BitCaluclatorInfo Result + { + get => _result; + set { - get => _result; - set - { - if (value == _result) - return; - - _result = value; - OnPropertyChanged(); - } + if (value == _result) + return; + + _result = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public BitCalculatorViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public BitCalculatorViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - InputHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.BitCalculator_InputHistory); + InputHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.BitCalculator_InputHistory); - Units = Enum.GetValues(typeof(BitCaluclatorUnit)).Cast().ToList(); - Unit = Units.First(x => x == SettingsManager.Current.BitCalculator_Unit); + Units = Enum.GetValues(typeof(BitCaluclatorUnit)).Cast().ToList(); + Unit = Units.First(x => x == SettingsManager.Current.BitCalculator_Unit); - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { + private void LoadSettings() + { - } - #endregion + } + #endregion - #region ICommands & Actions - public ICommand CalculateCommand => new RelayCommand(p => CalcualateAction(), Calculate_CanExecute); + #region ICommands & Actions + public ICommand CalculateCommand => new RelayCommand(p => CalcualateAction(), Calculate_CanExecute); - private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + + private void CalcualateAction() + { + Calculate(); + } + #endregion + + #region Methods + private async void Calculate() + { + IsResultVisible = false; + IsCalculationRunning = true; - private void CalcualateAction() + if (double.TryParse(Input.Replace('.', ','), out double input)) { - Calculate(); + Result = await BitCaluclator.CalculateAsync(input, Unit, SettingsManager.Current.BitCalculator_Notation); } - #endregion - - #region Methods - private async void Calculate() + else { - IsResultVisible = false; - IsCalculationRunning = true; - - if (double.TryParse(Input.Replace('.', ','), out double input)) - { - Result = await BitCaluclator.CalculateAsync(input, Unit, SettingsManager.Current.BitCalculator_Notation); - } - else - { - _log.Error($"Could not parse input \"{Input}\" into double!"); - } + _log.Error($"Could not parse input \"{Input}\" into double!"); + } - IsResultVisible = true; + IsResultVisible = true; - AddInputToHistory(Input); + AddInputToHistory(Input); - IsCalculationRunning = false; - } + IsCalculationRunning = false; + } - private void AddInputToHistory(string input) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.BitCalculator_InputHistory.ToList(), input, SettingsManager.Current.General_HistoryListEntries); + private void AddInputToHistory(string input) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.BitCalculator_InputHistory.ToList(), input, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.BitCalculator_InputHistory.Clear(); - OnPropertyChanged(nameof(Input)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.BitCalculator_InputHistory.Clear(); + OnPropertyChanged(nameof(Input)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.BitCalculator_InputHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.BitCalculator_InputHistory.Add(x)); + } - public void OnViewVisible() - { - _isViewActive = true; - } + public void OnViewVisible() + { + _isViewActive = true; + } - public void OnViewHide() - { - _isViewActive = false; - } + public void OnViewHide() + { + _isViewActive = false; + } - #endregion + #endregion - #region Event + #region Event - #endregion - } + #endregion } diff --git a/Source/NETworkManager/ViewModels/CommandLineViewModel.cs b/Source/NETworkManager/ViewModels/CommandLineViewModel.cs index ac5b08b185..0408fb9fbd 100644 --- a/Source/NETworkManager/ViewModels/CommandLineViewModel.cs +++ b/Source/NETworkManager/ViewModels/CommandLineViewModel.cs @@ -5,123 +5,122 @@ using System.Linq; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class CommandLineViewModel : ViewModelBase { - public class CommandLineViewModel : ViewModelBase + #region Variables + private bool _displayWrongParameter; + public bool DisplayWrongParameter { - #region Variables - private bool _displayWrongParameter; - public bool DisplayWrongParameter + get => _displayWrongParameter; + set { - get => _displayWrongParameter; - set - { - if (value == _displayWrongParameter) - return; - - _displayWrongParameter = value; - OnPropertyChanged(); - } + if (value == _displayWrongParameter) + return; + + _displayWrongParameter = value; + OnPropertyChanged(); } + } - private string _wrongParameter; - public string WrongParameter + private string _wrongParameter; + public string WrongParameter + { + get => _wrongParameter; + set { - get => _wrongParameter; - set - { - if (value == _wrongParameter) - return; - - _wrongParameter = value; - OnPropertyChanged(); - } + if (value == _wrongParameter) + return; + + _wrongParameter = value; + OnPropertyChanged(); } + } - private string _parameterHelp; - public string ParameterHelp + private string _parameterHelp; + public string ParameterHelp + { + get => _parameterHelp; + set { - get => _parameterHelp; - set - { - if (value == _parameterHelp) - return; - - _parameterHelp = value; - OnPropertyChanged(); - } + if (value == _parameterHelp) + return; + + _parameterHelp = value; + OnPropertyChanged(); } + } - private string _parameterResetSettings; - public string ParameterResetSettings + private string _parameterResetSettings; + public string ParameterResetSettings + { + get => _parameterResetSettings; + set { - get => _parameterResetSettings; - set - { - if (value == _parameterResetSettings) - return; - - _parameterResetSettings = value; - OnPropertyChanged(); - } + if (value == _parameterResetSettings) + return; + + _parameterResetSettings = value; + OnPropertyChanged(); } + } - private string _parameterApplication; - public string ParameterApplication + private string _parameterApplication; + public string ParameterApplication + { + get => _parameterApplication; + set { - get => _parameterApplication; - set - { - if (value == _parameterApplication) - return; - - _parameterApplication = value; - OnPropertyChanged(); - } + if (value == _parameterApplication) + return; + + _parameterApplication = value; + OnPropertyChanged(); } + } - private string _parameterApplicationValues; - public string ParameterApplicationValues + private string _parameterApplicationValues; + public string ParameterApplicationValues + { + get => _parameterApplicationValues; + set { - get => _parameterApplicationValues; - set - { - if (value == _parameterApplicationValues) - return; - - _parameterApplicationValues = value; - OnPropertyChanged(); - } + if (value == _parameterApplicationValues) + return; + + _parameterApplicationValues = value; + OnPropertyChanged(); } + } - #endregion + #endregion - #region Constructor, load settings - public CommandLineViewModel() + #region Constructor, load settings + public CommandLineViewModel() + { + if (!string.IsNullOrEmpty(CommandLineManager.Current.WrongParameter)) { - if (!string.IsNullOrEmpty(CommandLineManager.Current.WrongParameter)) - { - WrongParameter = CommandLineManager.Current.WrongParameter; - DisplayWrongParameter = true; - } - - ParameterHelp = CommandLineManager.ParameterHelp; - ParameterResetSettings = CommandLineManager.ParameterResetSettings; - ParameterApplication = CommandLineManager.GetParameterWithSplitIdentifier(CommandLineManager.ParameterApplication); - ParameterApplicationValues = string.Join(", ", System.Enum.GetValues(typeof(ApplicationName)).Cast().ToList()); + WrongParameter = CommandLineManager.Current.WrongParameter; + DisplayWrongParameter = true; } - #endregion - #region ICommand & Actions - public ICommand OpenDocumentationCommand - { - get { return new RelayCommand(p => OpenDocumentationAction()); } - } + ParameterHelp = CommandLineManager.ParameterHelp; + ParameterResetSettings = CommandLineManager.ParameterResetSettings; + ParameterApplication = CommandLineManager.GetParameterWithSplitIdentifier(CommandLineManager.ParameterApplication); + ParameterApplicationValues = string.Join(", ", System.Enum.GetValues(typeof(ApplicationName)).Cast().ToList()); + } + #endregion - private void OpenDocumentationAction() - { - DocumentationManager.OpenDocumentation(DocumentationIdentifier.CommandLineArguments); - } - #endregion + #region ICommand & Actions + public ICommand OpenDocumentationCommand + { + get { return new RelayCommand(p => OpenDocumentationAction()); } + } + + private void OpenDocumentationAction() + { + DocumentationManager.OpenDocumentation(DocumentationIdentifier.CommandLineArguments); } + #endregion } diff --git a/Source/NETworkManager/ViewModels/ConfirmDeleteViewModel.cs b/Source/NETworkManager/ViewModels/ConfirmDeleteViewModel.cs index 4879edd6eb..aa42e5da7f 100644 --- a/Source/NETworkManager/ViewModels/ConfirmDeleteViewModel.cs +++ b/Source/NETworkManager/ViewModels/ConfirmDeleteViewModel.cs @@ -2,34 +2,33 @@ using System; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ConfirmDeleteViewModel : ViewModelBase { - public class ConfirmDeleteViewModel : ViewModelBase - { - public ICommand DeleteCommand { get; } + public ICommand DeleteCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _message; - public string Message + private string _message; + public string Message + { + get => _message; + set { - get => _message; - set - { - if (value == _message) - return; + if (value == _message) + return; - _message = value; - OnPropertyChanged(); - } + _message = value; + OnPropertyChanged(); } - - public ConfirmDeleteViewModel(Action deleteCommand, Action cancelHandler, string message) - { - DeleteCommand = new RelayCommand(p => deleteCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + } + + public ConfirmDeleteViewModel(Action deleteCommand, Action cancelHandler, string message) + { + DeleteCommand = new RelayCommand(p => deleteCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - Message = message; - } + Message = message; } } diff --git a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs index b3582dc0c0..eb6434a93f 100644 --- a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs +++ b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs @@ -18,382 +18,381 @@ using NETworkManager.Localization; using NETworkManager.Localization.Translators; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ConnectionsViewModel : ViewModelBase { - public class ConnectionsViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading; - private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); - private bool _isTimerPaused; + private readonly bool _isLoading; + private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); + private bool _isTimerPaused; - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - ConnectionResultsView.Refresh(); + ConnectionResultsView.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private ObservableCollection _connectionResults = new ObservableCollection(); - public ObservableCollection ConnectionResults + private ObservableCollection _connectionResults = new ObservableCollection(); + public ObservableCollection ConnectionResults + { + get => _connectionResults; + set { - get => _connectionResults; - set - { - if (value == _connectionResults) - return; + if (value == _connectionResults) + return; - _connectionResults = value; - OnPropertyChanged(); - } + _connectionResults = value; + OnPropertyChanged(); } + } - public ICollectionView ConnectionResultsView { get; } + public ICollectionView ConnectionResultsView { get; } - private ConnectionInfo _selectedConnectionInfo; - public ConnectionInfo SelectedConnectionInfo + private ConnectionInfo _selectedConnectionInfo; + public ConnectionInfo SelectedConnectionInfo + { + get => _selectedConnectionInfo; + set { - get => _selectedConnectionInfo; - set - { - if (value == _selectedConnectionInfo) - return; + if (value == _selectedConnectionInfo) + return; - _selectedConnectionInfo = value; - OnPropertyChanged(); - } + _selectedConnectionInfo = value; + OnPropertyChanged(); } + } - private IList _selectedConnectionInfos = new ArrayList(); - public IList SelectedConnectionInfos + private IList _selectedConnectionInfos = new ArrayList(); + public IList SelectedConnectionInfos + { + get => _selectedConnectionInfos; + set { - get => _selectedConnectionInfos; - set - { - if (Equals(value, _selectedConnectionInfos)) - return; + if (Equals(value, _selectedConnectionInfos)) + return; - _selectedConnectionInfos = value; - OnPropertyChanged(); - } + _selectedConnectionInfos = value; + OnPropertyChanged(); } + } - private bool _autoRefresh; - public bool AutoRefresh + private bool _autoRefresh; + public bool AutoRefresh + { + get => _autoRefresh; + set { - get => _autoRefresh; - set - { - if (value == _autoRefresh) - return; - - if (!_isLoading) - SettingsManager.Current.Connections_AutoRefresh = value; + if (value == _autoRefresh) + return; - _autoRefresh = value; + if (!_isLoading) + SettingsManager.Current.Connections_AutoRefresh = value; - // Start timer to refresh automatically - if (!_isLoading) - { - if (value) - StartAutoRefreshTimer(); - else - StopAutoRefreshTimer(); - } + _autoRefresh = value; - OnPropertyChanged(); + // Start timer to refresh automatically + if (!_isLoading) + { + if (value) + StartAutoRefreshTimer(); + else + StopAutoRefreshTimer(); } + + OnPropertyChanged(); } + } - public ICollectionView AutoRefreshTimes { get; } + public ICollectionView AutoRefreshTimes { get; } - private AutoRefreshTimeInfo _selectedAutoRefreshTime; - public AutoRefreshTimeInfo SelectedAutoRefreshTime + private AutoRefreshTimeInfo _selectedAutoRefreshTime; + public AutoRefreshTimeInfo SelectedAutoRefreshTime + { + get => _selectedAutoRefreshTime; + set { - get => _selectedAutoRefreshTime; - set - { - if (value == _selectedAutoRefreshTime) - return; + if (value == _selectedAutoRefreshTime) + return; - if (!_isLoading) - SettingsManager.Current.Connections_AutoRefreshTime = value; + if (!_isLoading) + SettingsManager.Current.Connections_AutoRefreshTime = value; - _selectedAutoRefreshTime = value; + _selectedAutoRefreshTime = value; - if (AutoRefresh) - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); + if (AutoRefresh) + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isRefreshing; - public bool IsRefreshing + private bool _isRefreshing; + public bool IsRefreshing + { + get => _isRefreshing; + set { - get => _isRefreshing; - set - { - if (value == _isRefreshing) - return; + if (value == _isRefreshing) + return; - _isRefreshing = value; - OnPropertyChanged(); - } + _isRefreshing = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public ConnectionsViewModel(IDialogCoordinator instance) + #region Contructor, load settings + public ConnectionsViewModel(IDialogCoordinator instance) + { + _isLoading = true; + + _dialogCoordinator = instance; + + // Result view + search + ConnectionResultsView = CollectionViewSource.GetDefaultView(ConnectionResults); + ConnectionResultsView.SortDescriptions.Add(new SortDescription(nameof(ConnectionInfo.LocalIPAddressInt32), ListSortDirection.Ascending)); + ConnectionResultsView.Filter = o => { - _isLoading = true; + if (string.IsNullOrEmpty(Search)) + return true; + + // Search by local/remote IP Address, local/remote Port, Protocol and State + return o is ConnectionInfo info && (info.LocalIPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.LocalPort.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.RemoteIPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.RemotePort.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.Protocol.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || TcpStateTranslator.GetInstance().Translate(info.TcpState).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1); + }; - _dialogCoordinator = instance; + AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); + SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.Connections_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.Connections_AutoRefreshTime.TimeUnit)); - // Result view + search - ConnectionResultsView = CollectionViewSource.GetDefaultView(ConnectionResults); - ConnectionResultsView.SortDescriptions.Add(new SortDescription(nameof(ConnectionInfo.LocalIPAddressInt32), ListSortDirection.Ascending)); - ConnectionResultsView.Filter = o => - { - if (string.IsNullOrEmpty(Search)) - return true; - - // Search by local/remote IP Address, local/remote Port, Protocol and State - return o is ConnectionInfo info && (info.LocalIPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.LocalPort.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.RemoteIPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.RemotePort.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.Protocol.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || TcpStateTranslator.GetInstance().Translate(info.TcpState).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1); - }; + _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; - AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); - SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.Connections_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.Connections_AutoRefreshTime.TimeUnit)); + LoadSettings(); - _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; + _isLoading = false; - LoadSettings(); + Run(); + } - _isLoading = false; + private async Task Run() + { + await Refresh(); - Run(); - } + if (AutoRefresh) + StartAutoRefreshTimer(); + } - private async Task Run() - { - await Refresh(); + private void LoadSettings() + { + AutoRefresh = SettingsManager.Current.Connections_AutoRefresh; + } + #endregion - if (AutoRefresh) - StartAutoRefreshTimer(); - } + #region ICommands & Actions + public ICommand RefreshCommand => new RelayCommand(p => RefreshAction(), Refresh_CanExecute); - private void LoadSettings() - { - AutoRefresh = SettingsManager.Current.Connections_AutoRefresh; - } - #endregion + private bool Refresh_CanExecute(object paramter) + { + return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + } - #region ICommands & Actions - public ICommand RefreshCommand => new RelayCommand(p => RefreshAction(), Refresh_CanExecute); + private async Task RefreshAction() + { + IsStatusMessageDisplayed = false; - private bool Refresh_CanExecute(object paramter) - { - return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - } + await Refresh(); + } - private async Task RefreshAction() - { - IsStatusMessageDisplayed = false; + public ICommand CopySelectedLocalIpAddressCommand => new RelayCommand(p => CopySelectedLocalIpAddressAction()); - await Refresh(); - } + private void CopySelectedLocalIpAddressAction() + { + ClipboardHelper.SetClipboard(SelectedConnectionInfo.LocalIPAddress.ToString()); + } - public ICommand CopySelectedLocalIpAddressCommand => new RelayCommand(p => CopySelectedLocalIpAddressAction()); + public ICommand CopySelectedLocalPortCommand => new RelayCommand(p => CopySelectedLocalPortAction()); - private void CopySelectedLocalIpAddressAction() - { - ClipboardHelper.SetClipboard(SelectedConnectionInfo.LocalIPAddress.ToString()); - } + private void CopySelectedLocalPortAction() + { + ClipboardHelper.SetClipboard(SelectedConnectionInfo.LocalPort.ToString()); + } - public ICommand CopySelectedLocalPortCommand => new RelayCommand(p => CopySelectedLocalPortAction()); + public ICommand CopySelectedRemoteIpAddressCommand => new RelayCommand(p => CopySelectedRemoteIpAddressAction()); - private void CopySelectedLocalPortAction() - { - ClipboardHelper.SetClipboard(SelectedConnectionInfo.LocalPort.ToString()); - } + private void CopySelectedRemoteIpAddressAction() + { + ClipboardHelper.SetClipboard(SelectedConnectionInfo.RemoteIPAddress.ToString()); + } - public ICommand CopySelectedRemoteIpAddressCommand => new RelayCommand(p => CopySelectedRemoteIpAddressAction()); + public ICommand CopySelectedRemotePortCommand => new RelayCommand(p => CopySelectedRemotePortAction()); - private void CopySelectedRemoteIpAddressAction() - { - ClipboardHelper.SetClipboard(SelectedConnectionInfo.RemoteIPAddress.ToString()); - } + private void CopySelectedRemotePortAction() + { + ClipboardHelper.SetClipboard(SelectedConnectionInfo.RemotePort.ToString()); + } - public ICommand CopySelectedRemotePortCommand => new RelayCommand(p => CopySelectedRemotePortAction()); + public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); - private void CopySelectedRemotePortAction() - { - ClipboardHelper.SetClipboard(SelectedConnectionInfo.RemotePort.ToString()); - } + private void CopySelectedProtocolAction() + { + ClipboardHelper.SetClipboard(SelectedConnectionInfo.Protocol.ToString()); + } - public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); + public ICommand CopySelectedStateCommand => new RelayCommand(p => CopySelectedStateAction()); - private void CopySelectedProtocolAction() - { - ClipboardHelper.SetClipboard(SelectedConnectionInfo.Protocol.ToString()); - } + private void CopySelectedStateAction() + { + ClipboardHelper.SetClipboard(TcpStateTranslator.GetInstance().Translate(SelectedConnectionInfo.TcpState)); + } - public ICommand CopySelectedStateCommand => new RelayCommand(p => CopySelectedStateAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private void CopySelectedStateAction() + private async Task ExportAction() + { + var customDialog = new CustomDialog { - ClipboardHelper.SetClipboard(TcpStateTranslator.GetInstance().Translate(SelectedConnectionInfo.TcpState)); - } + Title = Localization.Resources.Strings.Export + }; - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - - private async Task ExportAction() + var exportViewModel = new ExportViewModel(async instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - var exportViewModel = new ExportViewModel(async instance => + try { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? ConnectionResults : new ObservableCollection(SelectedConnectionInfos.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? ConnectionResults : new ObservableCollection(SelectedConnectionInfos.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - SettingsManager.Current.Connections_ExportFileType = instance.FileType; - SettingsManager.Current.Connections_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Connections_ExportFileType, SettingsManager.Current.Connections_ExportFilePath); + SettingsManager.Current.Connections_ExportFileType = instance.FileType; + SettingsManager.Current.Connections_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Connections_ExportFileType, SettingsManager.Current.Connections_ExportFilePath); - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - #region Methods - private async Task Refresh() - { - IsRefreshing = true; + #region Methods + private async Task Refresh() + { + IsRefreshing = true; - ConnectionResults.Clear(); + ConnectionResults.Clear(); - (await Connection.GetActiveTcpConnectionsAsync()).ForEach(x => ConnectionResults.Add(x)); + (await Connection.GetActiveTcpConnectionsAsync()).ForEach(x => ConnectionResults.Add(x)); - IsRefreshing = false; - } + IsRefreshing = false; + } - private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) - { - _autoRefreshTimer.Interval = timeSpan; - } + private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) + { + _autoRefreshTimer.Interval = timeSpan; + } - private void StartAutoRefreshTimer() - { - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); + private void StartAutoRefreshTimer() + { + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); - _autoRefreshTimer.Start(); - } + _autoRefreshTimer.Start(); + } - private void StopAutoRefreshTimer() - { - _autoRefreshTimer.Stop(); - } + private void StopAutoRefreshTimer() + { + _autoRefreshTimer.Stop(); + } - private void PauseAutoRefreshTimer() - { - if (!_autoRefreshTimer.IsEnabled) - return; + private void PauseAutoRefreshTimer() + { + if (!_autoRefreshTimer.IsEnabled) + return; - _autoRefreshTimer.Stop(); - _isTimerPaused = true; - } + _autoRefreshTimer.Stop(); + _isTimerPaused = true; + } - private void ResumeAutoRefreshTimer() - { - if (!_isTimerPaused) - return; + private void ResumeAutoRefreshTimer() + { + if (!_isTimerPaused) + return; - _autoRefreshTimer.Start(); - _isTimerPaused = false; - } + _autoRefreshTimer.Start(); + _isTimerPaused = false; + } - public void OnViewVisible() - { - ResumeAutoRefreshTimer(); - } + public void OnViewVisible() + { + ResumeAutoRefreshTimer(); + } - public void OnViewHide() - { - PauseAutoRefreshTimer(); - } + public void OnViewHide() + { + PauseAutoRefreshTimer(); + } - #endregion + #endregion - #region Events - private async void AutoRefreshTimer_Tick(object sender, EventArgs e) - { - // Stop timer... - _autoRefreshTimer.Stop(); + #region Events + private async void AutoRefreshTimer_Tick(object sender, EventArgs e) + { + // Stop timer... + _autoRefreshTimer.Stop(); - // Refresh - await Refresh(); + // Refresh + await Refresh(); - // Restart timer... - _autoRefreshTimer.Start(); - } - #endregion + // Restart timer... + _autoRefreshTimer.Start(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/CredentialsChangePasswordViewModel.cs b/Source/NETworkManager/ViewModels/CredentialsChangePasswordViewModel.cs index 2d6c04961a..7c0f978f13 100644 --- a/Source/NETworkManager/ViewModels/CredentialsChangePasswordViewModel.cs +++ b/Source/NETworkManager/ViewModels/CredentialsChangePasswordViewModel.cs @@ -3,153 +3,152 @@ using System.Security; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class CredentialsChangePasswordViewModel : ViewModelBase { - public class CredentialsChangePasswordViewModel : ViewModelBase + /// + /// Command which is called when the OK button is clicked. + /// + public ICommand OKCommand { get; } + + /// + /// Command which is called when the cancel button is clicked. + /// + public ICommand CancelCommand { get; } + + /// + /// Private variable for . + /// + private SecureString _password = new SecureString(); + + /// + /// Password as secure string. + /// + public SecureString Password { - /// - /// Command which is called when the OK button is clicked. - /// - public ICommand OKCommand { get; } - - /// - /// Command which is called when the cancel button is clicked. - /// - public ICommand CancelCommand { get; } - - /// - /// Private variable for . - /// - private SecureString _password = new SecureString(); - - /// - /// Password as secure string. - /// - public SecureString Password + get => _password; + set { - get => _password; - set - { - if (value == _password) - return; + if (value == _password) + return; - _password = value; + _password = value; - ValidatePassword(); + ValidatePassword(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private SecureString _newPassword = new SecureString(); + /// + /// Private variable for . + /// + private SecureString _newPassword = new SecureString(); - /// - /// New password as secure string. - /// - public SecureString NewPassword + /// + /// New password as secure string. + /// + public SecureString NewPassword + { + get => _newPassword; + set { - get => _newPassword; - set - { - if (value == _newPassword) - return; + if (value == _newPassword) + return; - _newPassword = value; + _newPassword = value; - ValidatePassword(); + ValidatePassword(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private SecureString _newPasswordRepeat = new SecureString(); + /// + /// Private variable for . + /// + private SecureString _newPasswordRepeat = new SecureString(); - /// - /// Repeated new password as secure string. - /// - public SecureString NewPasswordRepeat + /// + /// Repeated new password as secure string. + /// + public SecureString NewPasswordRepeat + { + get => _newPasswordRepeat; + set { - get => _newPasswordRepeat; - set - { - if (value == _newPasswordRepeat) - return; + if (value == _newPasswordRepeat) + return; - _newPasswordRepeat = value; + _newPasswordRepeat = value; - ValidatePassword(); + ValidatePassword(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private bool _isPasswordEmpty = true; + /// + /// Private variable for . + /// + private bool _isPasswordEmpty = true; - /// - /// Indicate if one of the password fields are empty. - /// - public bool IsPasswordEmpty + /// + /// Indicate if one of the password fields are empty. + /// + public bool IsPasswordEmpty + { + get => _isPasswordEmpty; + set { - get => _isPasswordEmpty; - set - { - if (value == _isPasswordEmpty) - return; - - _isPasswordEmpty = value; - OnPropertyChanged(); - } + if (value == _isPasswordEmpty) + return; + + _isPasswordEmpty = value; + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private bool _isRepeatedPasswordEqual; + /// + /// Private variable for . + /// + private bool _isRepeatedPasswordEqual; - /// - /// Indicate if the is equal to the . - /// - public bool IsRepeatedPasswordEqual + /// + /// Indicate if the is equal to the . + /// + public bool IsRepeatedPasswordEqual + { + get => _isRepeatedPasswordEqual; + set { - get => _isRepeatedPasswordEqual; - set - { - if (value == _isRepeatedPasswordEqual) - return; - - _isRepeatedPasswordEqual = value; - OnPropertyChanged(); - } + if (value == _isRepeatedPasswordEqual) + return; + + _isRepeatedPasswordEqual = value; + OnPropertyChanged(); } + } - /// - /// Check if the passwords are valid and equal. - /// - private void ValidatePassword() - { - IsPasswordEmpty = Password == null || Password.Length == 0 || NewPassword == null || NewPassword.Length == 0 || NewPasswordRepeat == null || NewPasswordRepeat.Length == 0; + /// + /// Check if the passwords are valid and equal. + /// + private void ValidatePassword() + { + IsPasswordEmpty = Password == null || Password.Length == 0 || NewPassword == null || NewPassword.Length == 0 || NewPasswordRepeat == null || NewPasswordRepeat.Length == 0; - IsRepeatedPasswordEqual = !IsPasswordEmpty && SecureStringHelper.ConvertToString(NewPassword).Equals(SecureStringHelper.ConvertToString(NewPasswordRepeat)); - } + IsRepeatedPasswordEqual = !IsPasswordEmpty && SecureStringHelper.ConvertToString(NewPassword).Equals(SecureStringHelper.ConvertToString(NewPasswordRepeat)); + } - /// - /// Initalizes a new class with and . - /// - /// which is executed on OK click. - /// which is executed on cancel click. - public CredentialsChangePasswordViewModel(Action okCommand, Action cancelHandler) - { - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - } + /// + /// Initalizes a new class with and . + /// + /// which is executed on OK click. + /// which is executed on cancel click. + public CredentialsChangePasswordViewModel(Action okCommand, Action cancelHandler) + { + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/CredentialsPasswordProfileFileViewModel.cs b/Source/NETworkManager/ViewModels/CredentialsPasswordProfileFileViewModel.cs index 94d7afe28a..4ebe284898 100644 --- a/Source/NETworkManager/ViewModels/CredentialsPasswordProfileFileViewModel.cs +++ b/Source/NETworkManager/ViewModels/CredentialsPasswordProfileFileViewModel.cs @@ -3,125 +3,124 @@ using System.Security; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class CredentialsPasswordProfileFileViewModel : ViewModelBase { - public class CredentialsPasswordProfileFileViewModel : ViewModelBase + /// + /// Command which is called when the OK button is clicked. + /// + public ICommand OKCommand { get; } + + /// + /// Command which is called when the cancel button is clicked. + /// + public ICommand CancelCommand { get; } + + /// + /// Private variable for . + /// + private string _profileName; + + /// + /// Name of the profile file. + /// + public string ProfileName { - /// - /// Command which is called when the OK button is clicked. - /// - public ICommand OKCommand { get; } - - /// - /// Command which is called when the cancel button is clicked. - /// - public ICommand CancelCommand { get; } - - /// - /// Private variable for . - /// - private string _profileName; - - /// - /// Name of the profile file. - /// - public string ProfileName + get => _profileName; + set { - get => _profileName; - set - { - if (value == _profileName) - return; - - _profileName = value; - OnPropertyChanged(); - } + if (value == _profileName) + return; + + _profileName = value; + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private bool _showWrongPassword; + /// + /// Private variable for . + /// + private bool _showWrongPassword; - /// - /// Show note that the password is wrong. - /// - public bool ShowWrongPassword + /// + /// Show note that the password is wrong. + /// + public bool ShowWrongPassword + { + get => _showWrongPassword; + set { - get => _showWrongPassword; - set - { - if (value == _showWrongPassword) - return; - - _showWrongPassword = value; - OnPropertyChanged(); - } + if (value == _showWrongPassword) + return; + + _showWrongPassword = value; + OnPropertyChanged(); } - - /// - /// Private variable for . - /// - private SecureString _password = new(); - - /// - /// Password as secure string. - /// - public SecureString Password + } + + /// + /// Private variable for . + /// + private SecureString _password = new(); + + /// + /// Password as secure string. + /// + public SecureString Password + { + get => _password; + set { - get => _password; - set - { - if (value == _password) - return; + if (value == _password) + return; - _password = value; + _password = value; - ValidatePassword(); + ValidatePassword(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private bool _isPasswordEmpty; + /// + /// Private variable for . + /// + private bool _isPasswordEmpty; - /// - /// Indicate if one of the password fields are empty. - /// - public bool IsPasswordEmpty + /// + /// Indicate if one of the password fields are empty. + /// + public bool IsPasswordEmpty + { + get => _isPasswordEmpty; + set { - get => _isPasswordEmpty; - set - { - if (value == _isPasswordEmpty) - return; - - _isPasswordEmpty = value; - OnPropertyChanged(); - } - } + if (value == _isPasswordEmpty) + return; + _isPasswordEmpty = value; + OnPropertyChanged(); + } + } - /// - /// Initalizes a new class with and . - /// - /// which is executed on OK click. - /// which is executed on cancel click. - public CredentialsPasswordProfileFileViewModel(Action okCommand, Action cancelHandler, string profileName, bool showWrongPassword = false) - { - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - ProfileName = profileName; - ShowWrongPassword = showWrongPassword; - } + /// + /// Initalizes a new class with and . + /// + /// which is executed on OK click. + /// which is executed on cancel click. + public CredentialsPasswordProfileFileViewModel(Action okCommand, Action cancelHandler, string profileName, bool showWrongPassword = false) + { + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - /// - /// Check if the passwords are valid. - /// - private void ValidatePassword() => IsPasswordEmpty = Password == null || Password.Length == 0; + ProfileName = profileName; + ShowWrongPassword = showWrongPassword; } + + /// + /// Check if the passwords are valid. + /// + private void ValidatePassword() => IsPasswordEmpty = Password == null || Password.Length == 0; } diff --git a/Source/NETworkManager/ViewModels/CredentialsPasswordViewModel.cs b/Source/NETworkManager/ViewModels/CredentialsPasswordViewModel.cs index a104ddb260..b5b0bce730 100644 --- a/Source/NETworkManager/ViewModels/CredentialsPasswordViewModel.cs +++ b/Source/NETworkManager/ViewModels/CredentialsPasswordViewModel.cs @@ -3,80 +3,79 @@ using System.Security; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class CredentialsPasswordViewModel : ViewModelBase { - public class CredentialsPasswordViewModel : ViewModelBase - { - /// - /// Command which is called when the OK button is clicked. - /// - public ICommand OKCommand { get; } + /// + /// Command which is called when the OK button is clicked. + /// + public ICommand OKCommand { get; } - /// - /// Command which is called when the cancel button is clicked. - /// - public ICommand CancelCommand { get; } + /// + /// Command which is called when the cancel button is clicked. + /// + public ICommand CancelCommand { get; } - /// - /// Private variable for . - /// - private SecureString _password = new SecureString(); + /// + /// Private variable for . + /// + private SecureString _password = new SecureString(); - /// - /// Password as secure string. - /// - public SecureString Password + /// + /// Password as secure string. + /// + public SecureString Password + { + get => _password; + set { - get => _password; - set - { - if (value == _password) - return; + if (value == _password) + return; - _password = value; + _password = value; - ValidatePassword(); + ValidatePassword(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private bool _isPasswordEmpty; + /// + /// Private variable for . + /// + private bool _isPasswordEmpty; - /// - /// Indicate if one of the password fields are empty. - /// - public bool IsPasswordEmpty + /// + /// Indicate if one of the password fields are empty. + /// + public bool IsPasswordEmpty + { + get => _isPasswordEmpty; + set { - get => _isPasswordEmpty; - set - { - if (value == _isPasswordEmpty) - return; + if (value == _isPasswordEmpty) + return; - _isPasswordEmpty = value; - OnPropertyChanged(); - } + _isPasswordEmpty = value; + OnPropertyChanged(); } + } - /// - /// Initalizes a new class with and . - /// - /// which is executed on OK click. - /// which is executed on cancel click. - public CredentialsPasswordViewModel(Action okCommand, Action cancelHandler) - { - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - } - - /// - /// Check if the passwords are valid. - /// - private void ValidatePassword() => IsPasswordEmpty = Password == null || Password.Length == 0; + /// + /// Initalizes a new class with and . + /// + /// which is executed on OK click. + /// which is executed on cancel click. + public CredentialsPasswordViewModel(Action okCommand, Action cancelHandler) + { + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); } + + /// + /// Check if the passwords are valid. + /// + private void ValidatePassword() => IsPasswordEmpty = Password == null || Password.Length == 0; } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/CredentialsSetPasswordViewModel.cs b/Source/NETworkManager/ViewModels/CredentialsSetPasswordViewModel.cs index f3a71650a0..89b736f127 100644 --- a/Source/NETworkManager/ViewModels/CredentialsSetPasswordViewModel.cs +++ b/Source/NETworkManager/ViewModels/CredentialsSetPasswordViewModel.cs @@ -3,129 +3,128 @@ using System.Security; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class CredentialsSetPasswordViewModel : ViewModelBase { - public class CredentialsSetPasswordViewModel : ViewModelBase + /// + /// Command which is called when the OK button is clicked. + /// + public ICommand OKCommand { get; } + + /// + /// Command which is called when the cancel button is clicked. + /// + public ICommand CancelCommand { get; } + + /// + /// Private variable for . + /// + private SecureString _password = new SecureString(); + + /// + /// Password as secure string. + /// + public SecureString Password { - /// - /// Command which is called when the OK button is clicked. - /// - public ICommand OKCommand { get; } - - /// - /// Command which is called when the cancel button is clicked. - /// - public ICommand CancelCommand { get; } - - /// - /// Private variable for . - /// - private SecureString _password = new SecureString(); - - /// - /// Password as secure string. - /// - public SecureString Password + get => _password; + set { - get => _password; - set - { - if (value == _password) - return; + if (value == _password) + return; - _password = value; + _password = value; - ValidatePassword(); + ValidatePassword(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private SecureString _passwordRepeat = new SecureString(); + /// + /// Private variable for . + /// + private SecureString _passwordRepeat = new SecureString(); - /// - /// Repeated password as secure string. - /// - public SecureString PasswordRepeat + /// + /// Repeated password as secure string. + /// + public SecureString PasswordRepeat + { + get => _passwordRepeat; + set { - get => _passwordRepeat; - set - { - if (value == _passwordRepeat) - return; + if (value == _passwordRepeat) + return; - _passwordRepeat = value; + _passwordRepeat = value; - ValidatePassword(); + ValidatePassword(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private bool _isPasswordEmpty = true; + /// + /// Private variable for . + /// + private bool _isPasswordEmpty = true; - /// - /// Indicate if one of the password fields are empty. - /// - public bool IsPasswordEmpty + /// + /// Indicate if one of the password fields are empty. + /// + public bool IsPasswordEmpty + { + get => _isPasswordEmpty; + set { - get => _isPasswordEmpty; - set - { - if (value == _isPasswordEmpty) - return; - - _isPasswordEmpty = value; - OnPropertyChanged(); - } + if (value == _isPasswordEmpty) + return; + + _isPasswordEmpty = value; + OnPropertyChanged(); } + } - /// - /// Private variable for . - /// - private bool _isRepeatedPasswordEqual; + /// + /// Private variable for . + /// + private bool _isRepeatedPasswordEqual; - /// - /// Indicate if the is equal to the . - /// - public bool IsRepeatedPasswordEqual + /// + /// Indicate if the is equal to the . + /// + public bool IsRepeatedPasswordEqual + { + get => _isRepeatedPasswordEqual; + set { - get => _isRepeatedPasswordEqual; - set - { - if (value == _isRepeatedPasswordEqual) - return; - - _isRepeatedPasswordEqual = value; - OnPropertyChanged(); - } + if (value == _isRepeatedPasswordEqual) + return; + + _isRepeatedPasswordEqual = value; + OnPropertyChanged(); } + } - /// - /// Check if the passwords are valid and equal. - /// - private void ValidatePassword() - { - IsPasswordEmpty = Password == null || Password.Length == 0 || PasswordRepeat == null || PasswordRepeat.Length == 0; + /// + /// Check if the passwords are valid and equal. + /// + private void ValidatePassword() + { + IsPasswordEmpty = Password == null || Password.Length == 0 || PasswordRepeat == null || PasswordRepeat.Length == 0; - IsRepeatedPasswordEqual = !IsPasswordEmpty && SecureStringHelper.ConvertToString(Password).Equals(SecureStringHelper.ConvertToString(PasswordRepeat)); - } + IsRepeatedPasswordEqual = !IsPasswordEmpty && SecureStringHelper.ConvertToString(Password).Equals(SecureStringHelper.ConvertToString(PasswordRepeat)); + } - /// - /// Initalizes a new class with and . - /// - /// which is executed on OK click. - /// which is executed on cancel click. - public CredentialsSetPasswordViewModel(Action okCommand, Action cancelHandler) - { - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - } + /// + /// Initalizes a new class with and . + /// + /// which is executed on OK click. + /// which is executed on cancel click. + public CredentialsSetPasswordViewModel(Action okCommand, Action cancelHandler) + { + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/CustomCommandViewModel.cs b/Source/NETworkManager/ViewModels/CustomCommandViewModel.cs index cccee20cc1..0506a4909a 100644 --- a/Source/NETworkManager/ViewModels/CustomCommandViewModel.cs +++ b/Source/NETworkManager/ViewModels/CustomCommandViewModel.cs @@ -2,134 +2,133 @@ using System; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class CustomCommandViewModel : ViewModelBase { - public class CustomCommandViewModel : ViewModelBase - { - private readonly bool _isLoading; + private readonly bool _isLoading; - public ICommand SaveCommand { get; } + public ICommand SaveCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private Guid _id; - public Guid ID + private Guid _id; + public Guid ID + { + get => _id; + set { - get => _id; - set - { - if (_id == value) - return; - - _id = value; - OnPropertyChanged(); - } + if (_id == value) + return; + + _id = value; + OnPropertyChanged(); } + } - private string _name; - public string Name + private string _name; + public string Name + { + get => _name; + set { - get => _name; - set - { - if (_name == value) - return; + if (_name == value) + return; - _name = value; + _name = value; - if (!_isLoading) - CheckInfoChanged(); + if (!_isLoading) + CheckInfoChanged(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private string _filePath; - public string FilePath + private string _filePath; + public string FilePath + { + get => _filePath; + set { - get => _filePath; - set - { - if (_filePath == value) - return; + if (_filePath == value) + return; - _filePath = value; + _filePath = value; - if (!_isLoading) - CheckInfoChanged(); + if (!_isLoading) + CheckInfoChanged(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private string _arguments; - public string Arguments + private string _arguments; + public string Arguments + { + get => _arguments; + set { - get => _arguments; - set - { - if (_arguments == value) - return; + if (_arguments == value) + return; - _arguments = value; + _arguments = value; - if (!_isLoading) - CheckInfoChanged(); + if (!_isLoading) + CheckInfoChanged(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private readonly CustomCommandInfo _info; - - private bool _infoChanged; - public bool InfoChanged + private readonly CustomCommandInfo _info; + + private bool _infoChanged; + public bool InfoChanged + { + get => _infoChanged; + set { - get => _infoChanged; - set - { - if (value == _infoChanged) - return; - - _infoChanged = value; - OnPropertyChanged(); - } - } + if (value == _infoChanged) + return; - private bool _isEdited; - public bool IsEdited - { - get => _isEdited; - set - { - if (value == _isEdited) - return; - - _isEdited = value; - OnPropertyChanged(); - } + _infoChanged = value; + OnPropertyChanged(); } + } - public CustomCommandViewModel(Action saveCommand, Action cancelHandler, bool isEdited = false, CustomCommandInfo info = null) + private bool _isEdited; + public bool IsEdited + { + get => _isEdited; + set { - _isLoading = true; + if (value == _isEdited) + return; - SaveCommand = new RelayCommand(p => saveCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + _isEdited = value; + OnPropertyChanged(); + } + } - _isEdited = isEdited; + public CustomCommandViewModel(Action saveCommand, Action cancelHandler, bool isEdited = false, CustomCommandInfo info = null) + { + _isLoading = true; - // Create new --> GUID - _info = info ?? new CustomCommandInfo(); + SaveCommand = new RelayCommand(p => saveCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - ID = _info.ID; - Name = _info.Name; - FilePath = _info.FilePath; - Arguments = _info.Arguments; + _isEdited = isEdited; - _isLoading = false; - } + // Create new --> GUID + _info = info ?? new CustomCommandInfo(); - public void CheckInfoChanged() => InfoChanged = _info.Name != null || _info.FilePath != FilePath || _info.Arguments != Arguments; + ID = _info.ID; + Name = _info.Name; + FilePath = _info.FilePath; + Arguments = _info.Arguments; + + _isLoading = false; } + + public void CheckInfoChanged() => InfoChanged = _info.Name != null || _info.FilePath != FilePath || _info.Arguments != Arguments; } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs b/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs index 42180d4237..fe9d68727b 100644 --- a/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs @@ -16,364 +16,363 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class DNSLookupHostViewModel : ViewModelBase, IProfileManager { - public class DNSLookupHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private int _tabId; + private int _tabId; - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.DNSLookup_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.DNSLookup_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.DNSLookup_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.DNSLookup_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public DNSLookupHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public DNSLookupHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - InterTabClient = new DragablzInterTabClient(ApplicationName.DNSLookup); + InterTabClient = new DragablzInterTabClient(ApplicationName.DNSLookup); - TabItems = new ObservableCollection - { - new DragablzTabItem(Localization.Resources.Strings.NewTab, new DNSLookupView (_tabId), _tabId) - }; - - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + TabItems = new ObservableCollection + { + new DragablzTabItem(Localization.Resources.Strings.NewTab, new DNSLookupView (_tabId), _tabId) + }; + + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.DNSLookup_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.DNSLookup_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.DNSLookup_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.DNSLookup_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, DNSLookup_Host - return info.DNSLookup_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.DNSLookup_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, DNSLookup_Host + return info.DNSLookup_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.DNSLookup_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.DNSLookup_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.DNSLookup_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.DNSLookup_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.DNSLookup_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.DNSLookup_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.DNSLookup_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.DNSLookup_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.DNSLookup_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); + #region ICommand & Actions + public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); - private void AddTabAction() - { - AddTab(); - } + private void AddTabAction() + { + AddTab(); + } - public ICommand LookupProfileCommand => new RelayCommand(p => LookupProfileAction(), LookupProfile_CanExecute); + public ICommand LookupProfileCommand => new RelayCommand(p => LookupProfileAction(), LookupProfile_CanExecute); - private bool LookupProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool LookupProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void LookupProfileAction() - { - AddTab(SelectedProfile.DNSLookup_Host); - } + private void LookupProfileAction() + { + AddTab(SelectedProfile.DNSLookup_Host); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.DNSLookup); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.DNSLookup); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ItemActionCallback CloseItemCommand => CloseItemAction; + public ItemActionCallback CloseItemCommand => CloseItemAction; - private static void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as DNSLookupView)?.CloseTab(); - } - #endregion + private static void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as DNSLookupView)?.CloseTab(); + } + #endregion - #region Methods - private void StartDelayedSearch() + #region Methods + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void AddTab(string host = null) - { - _tabId++; + _canProfileWidthChange = true; + } - TabItems.Add(new DragablzTabItem(host ?? Localization.Resources.Strings.NewTab, new DNSLookupView(_tabId, host), _tabId)); + public void AddTab(string host = null) + { + _tabId++; - SelectedTabIndex = TabItems.Count - 1; - } + TabItems.Add(new DragablzTabItem(host ?? Localization.Resources.Strings.NewTab, new DNSLookupView(_tabId, host), _tabId)); - public void OnViewVisible() - { - _isViewActive = true; + SelectedTabIndex = TabItems.Count - 1; + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Profiles.Refresh(); + })); + } - } + public void OnProfileDialogOpen() + { - public void OnProfileDialogClose() - { + } - } - #endregion + public void OnProfileDialogClose() + { - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/DNSLookupSettingsViewModel.cs b/Source/NETworkManager/ViewModels/DNSLookupSettingsViewModel.cs index 1e162be5bb..dda4b2b39a 100644 --- a/Source/NETworkManager/ViewModels/DNSLookupSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/DNSLookupSettingsViewModel.cs @@ -11,346 +11,345 @@ using DnsClient; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class DNSLookupSettingsViewModel : ViewModelBase { - public class DNSLookupSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - private (string Server, int Port, TransportProtocol TransportProtocol) _profileDialog_NewItemsOptions = ("1.1.1.1", 53, TransportProtocol.UDP); + private (string Server, int Port, TransportProtocol TransportProtocol) _profileDialog_NewItemsOptions = ("1.1.1.1", 53, TransportProtocol.UDP); - public ICollectionView DNSServers { get; } + public ICollectionView DNSServers { get; } - private DNSServerConnectionInfoProfile _selectedDNSServer = new(); - public DNSServerConnectionInfoProfile SelectedDNSServer + private DNSServerConnectionInfoProfile _selectedDNSServer = new(); + public DNSServerConnectionInfoProfile SelectedDNSServer + { + get => _selectedDNSServer; + set { - get => _selectedDNSServer; - set - { - if (value == _selectedDNSServer) - return; - - _selectedDNSServer = value; - OnPropertyChanged(); - } + if (value == _selectedDNSServer) + return; + + _selectedDNSServer = value; + OnPropertyChanged(); } + } - private List ServerInfoProfileNames => SettingsManager.Current.DNSLookup_DNSServers_v2.Where(x => !x.UseWindowsDNSServer).Select(x => x.Name).ToList(); + private List ServerInfoProfileNames => SettingsManager.Current.DNSLookup_DNSServers_v2.Where(x => !x.UseWindowsDNSServer).Select(x => x.Name).ToList(); - private bool _addDNSSuffix; - public bool AddDNSSuffix + private bool _addDNSSuffix; + public bool AddDNSSuffix + { + get => _addDNSSuffix; + set { - get => _addDNSSuffix; - set - { - if (value == _addDNSSuffix) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_AddDNSSuffix = value; - - _addDNSSuffix = value; - OnPropertyChanged(); - } + if (value == _addDNSSuffix) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_AddDNSSuffix = value; + + _addDNSSuffix = value; + OnPropertyChanged(); } + } - private bool _useCustomDNSSuffix; - public bool UseCustomDNSSuffix + private bool _useCustomDNSSuffix; + public bool UseCustomDNSSuffix + { + get => _useCustomDNSSuffix; + set { - get => _useCustomDNSSuffix; - set - { - if (value == _useCustomDNSSuffix) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_UseCustomDNSSuffix = value; - - _useCustomDNSSuffix = value; - OnPropertyChanged(); - } + if (value == _useCustomDNSSuffix) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_UseCustomDNSSuffix = value; + + _useCustomDNSSuffix = value; + OnPropertyChanged(); } + } - private string _customDNSSuffix; - public string CustomDNSSuffix + private string _customDNSSuffix; + public string CustomDNSSuffix + { + get => _customDNSSuffix; + set { - get => _customDNSSuffix; - set - { - if (value == _customDNSSuffix) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_CustomDNSSuffix = value; - - _customDNSSuffix = value; - OnPropertyChanged(); - } + if (value == _customDNSSuffix) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_CustomDNSSuffix = value; + + _customDNSSuffix = value; + OnPropertyChanged(); } + } - private bool _recursion; - public bool Recursion + private bool _recursion; + public bool Recursion + { + get => _recursion; + set { - get => _recursion; - set - { - if (value == _recursion) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_Recursion = value; - - _recursion = value; - OnPropertyChanged(); - } + if (value == _recursion) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_Recursion = value; + + _recursion = value; + OnPropertyChanged(); } + } - private bool _useCache; - public bool UseCache + private bool _useCache; + public bool UseCache + { + get => _useCache; + set { - get => _useCache; - set - { - if (value == _useCache) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_UseCache = value; - - _useCache = value; - OnPropertyChanged(); - } + if (value == _useCache) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_UseCache = value; + + _useCache = value; + OnPropertyChanged(); } + } - public List QueryClasses { get; set; } + public List QueryClasses { get; set; } - private QueryClass _queryClass; - public QueryClass QueryClass + private QueryClass _queryClass; + public QueryClass QueryClass + { + get => _queryClass; + set { - get => _queryClass; - set - { - if (value == _queryClass) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_QueryClass = value; - - _queryClass = value; - OnPropertyChanged(); - } + if (value == _queryClass) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_QueryClass = value; + + _queryClass = value; + OnPropertyChanged(); } + } - private bool _showOnlyMostCommonQueryTypes; - public bool ShowOnlyMostCommonQueryTypes + private bool _showOnlyMostCommonQueryTypes; + public bool ShowOnlyMostCommonQueryTypes + { + get => _showOnlyMostCommonQueryTypes; + set { - get => _showOnlyMostCommonQueryTypes; - set - { - if (value == _showOnlyMostCommonQueryTypes) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_ShowOnlyMostCommonQueryTypes = value; - - _showOnlyMostCommonQueryTypes = value; - OnPropertyChanged(); - } + if (value == _showOnlyMostCommonQueryTypes) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_ShowOnlyMostCommonQueryTypes = value; + + _showOnlyMostCommonQueryTypes = value; + OnPropertyChanged(); } + } - private bool _useTCPOnly; - public bool UseTCPOnly + private bool _useTCPOnly; + public bool UseTCPOnly + { + get => _useTCPOnly; + set { - get => _useTCPOnly; - set - { - if (value == _useTCPOnly) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_UseTCPOnly = value; - - _useTCPOnly = value; - OnPropertyChanged(); - } + if (value == _useTCPOnly) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_UseTCPOnly = value; + + _useTCPOnly = value; + OnPropertyChanged(); } + } - private int _retries; - public int Retries + private int _retries; + public int Retries + { + get => _retries; + set { - get => _retries; - set - { - if (value == _retries) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_Retries = value; - - _retries = value; - OnPropertyChanged(); - } + if (value == _retries) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_Retries = value; + + _retries = value; + OnPropertyChanged(); } + } - private int _timeout; - public int Timeout + private int _timeout; + public int Timeout + { + get => _timeout; + set { - get => _timeout; - set - { - if (value == _timeout) - return; - - if (!_isLoading) - SettingsManager.Current.DNSLookup_Timeout = value; - - _timeout = value; - OnPropertyChanged(); - } + if (value == _timeout) + return; + + if (!_isLoading) + SettingsManager.Current.DNSLookup_Timeout = value; + + _timeout = value; + OnPropertyChanged(); } - #endregion + } + #endregion + + #region Constructor, load settings + public DNSLookupSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; + + _dialogCoordinator = instance; - #region Constructor, load settings - public DNSLookupSettingsViewModel(IDialogCoordinator instance) + DNSServers = CollectionViewSource.GetDefaultView(SettingsManager.Current.DNSLookup_DNSServers_v2); + DNSServers.SortDescriptions.Add(new SortDescription(nameof(DNSServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); + DNSServers.Filter = o => { - _isLoading = true; + if (o is not DNSServerConnectionInfoProfile info) + return false; - _dialogCoordinator = instance; + return !info.UseWindowsDNSServer; + }; - DNSServers = CollectionViewSource.GetDefaultView(SettingsManager.Current.DNSLookup_DNSServers_v2); - DNSServers.SortDescriptions.Add(new SortDescription(nameof(DNSServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); - DNSServers.Filter = o => - { - if (o is not DNSServerConnectionInfoProfile info) - return false; + LoadSettings(); - return !info.UseWindowsDNSServer; - }; + _isLoading = false; + } - LoadSettings(); + private void LoadSettings() + { + AddDNSSuffix = SettingsManager.Current.DNSLookup_AddDNSSuffix; + UseCustomDNSSuffix = SettingsManager.Current.DNSLookup_UseCustomDNSSuffix; + CustomDNSSuffix = SettingsManager.Current.DNSLookup_CustomDNSSuffix; + Recursion = SettingsManager.Current.DNSLookup_Recursion; + UseCache = SettingsManager.Current.DNSLookup_UseCache; + QueryClasses = System.Enum.GetValues(typeof(QueryClass)).Cast().OrderBy(x => x.ToString()).ToList(); + QueryClass = QueryClasses.First(x => x == SettingsManager.Current.DNSLookup_QueryClass); + ShowOnlyMostCommonQueryTypes = SettingsManager.Current.DNSLookup_ShowOnlyMostCommonQueryTypes; + UseTCPOnly = SettingsManager.Current.DNSLookup_UseTCPOnly; + Retries = SettingsManager.Current.DNSLookup_Retries; + Timeout = SettingsManager.Current.DNSLookup_Timeout; + } + #endregion - _isLoading = false; - } + #region ICommand & Actions + public ICommand AddDNSServerCommand => new RelayCommand(p => AddDNSServerAction()); + + private void AddDNSServerAction() + { + AddDNSServer(); + } + + public ICommand EditDNSServerCommand => new RelayCommand(p => EditDNSServerAction()); + + private void EditDNSServerAction() + { + EditDNSServer(); + } + + public ICommand DeleteDNSServerCommand => new RelayCommand(p => DeleteDNSServerAction()); + + private void DeleteDNSServerAction() + { + DeleteDNSServer(); + } + #endregion + + #region Methods - private void LoadSettings() + public async Task AddDNSServer() + { + var customDialog = new CustomDialog { - AddDNSSuffix = SettingsManager.Current.DNSLookup_AddDNSSuffix; - UseCustomDNSSuffix = SettingsManager.Current.DNSLookup_UseCustomDNSSuffix; - CustomDNSSuffix = SettingsManager.Current.DNSLookup_CustomDNSSuffix; - Recursion = SettingsManager.Current.DNSLookup_Recursion; - UseCache = SettingsManager.Current.DNSLookup_UseCache; - QueryClasses = System.Enum.GetValues(typeof(QueryClass)).Cast().OrderBy(x => x.ToString()).ToList(); - QueryClass = QueryClasses.First(x => x == SettingsManager.Current.DNSLookup_QueryClass); - ShowOnlyMostCommonQueryTypes = SettingsManager.Current.DNSLookup_ShowOnlyMostCommonQueryTypes; - UseTCPOnly = SettingsManager.Current.DNSLookup_UseTCPOnly; - Retries = SettingsManager.Current.DNSLookup_Retries; - Timeout = SettingsManager.Current.DNSLookup_Timeout; - } - #endregion + Title = Localization.Resources.Strings.AddDNSServer + }; - #region ICommand & Actions - public ICommand AddDNSServerCommand => new RelayCommand(p => AddDNSServerAction()); + var viewModel = new ServerConnectionInfoProfileViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - private void AddDNSServerAction() + SettingsManager.Current.DNSLookup_DNSServers_v2.Add(new DNSServerConnectionInfoProfile(instance.Name, instance.Servers)); + }, instance => { - AddDNSServer(); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, (ServerInfoProfileNames, false, true)); - public ICommand EditDNSServerCommand => new RelayCommand(p => EditDNSServerAction()); + customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) + { + DataContext = viewModel + }; - private void EditDNSServerAction() + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + public async Task EditDNSServer() + { + var customDialog = new CustomDialog { - EditDNSServer(); - } + Title = Localization.Resources.Strings.EditDNSServer + }; - public ICommand DeleteDNSServerCommand => new RelayCommand(p => DeleteDNSServerAction()); + var viewModel = new ServerConnectionInfoProfileViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - private void DeleteDNSServerAction() + SettingsManager.Current.DNSLookup_DNSServers_v2.Remove(SelectedDNSServer); + SettingsManager.Current.DNSLookup_DNSServers_v2.Add(new DNSServerConnectionInfoProfile(instance.Name, instance.Servers)); + }, instance => { - DeleteDNSServer(); - } - #endregion + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, (ServerInfoProfileNames, true, true), SelectedDNSServer); - #region Methods + customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) + { + DataContext = viewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - public async Task AddDNSServer() + public async Task DeleteDNSServer() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddDNSServer - }; - - var viewModel = new ServerConnectionInfoProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.DNSLookup_DNSServers_v2.Add(new DNSServerConnectionInfoProfile(instance.Name, instance.Servers)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, (ServerInfoProfileNames, false, true)); - - customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + Title = Localization.Resources.Strings.DeleteDNSServer + }; - public async Task EditDNSServer() + var viewModel = new ConfirmDeleteViewModel(instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.EditDNSServer - }; - - var viewModel = new ServerConnectionInfoProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.DNSLookup_DNSServers_v2.Remove(SelectedDNSServer); - SettingsManager.Current.DNSLookup_DNSServers_v2.Add(new DNSServerConnectionInfoProfile(instance.Name, instance.Servers)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, (ServerInfoProfileNames, true, true), SelectedDNSServer); - - customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - public async Task DeleteDNSServer() + SettingsManager.Current.DNSLookup_DNSServers_v2.Remove(SelectedDNSServer); + }, instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.DeleteDNSServer - }; - - var viewModel = new ConfirmDeleteViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.DNSLookup_DNSServers_v2.Remove(SelectedDNSServer); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, Localization.Resources.Strings.DeleteDNSServerMessage); - - customDialog.Content = new ConfirmDeleteDialog - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, Localization.Resources.Strings.DeleteDNSServerMessage); + + customDialog.Content = new ConfirmDeleteDialog + { + DataContext = viewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs index 3922ccd3c1..62be602061 100644 --- a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs @@ -19,455 +19,452 @@ using NETworkManager.Views; using DnsClient; using System.Threading.Tasks; -using Amazon.EC2.Model; -using ControlzEx.Standard; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class DNSLookupViewModel : ViewModelBase { - public class DNSLookupViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - public readonly int TabId; - private bool _firstLoad = true; + public readonly int TabId; + private bool _firstLoad = true; - private string _lastSortDescriptionAscending = string.Empty; + private string _lastSortDescriptionAscending = string.Empty; - private readonly bool _isLoading; + private readonly bool _isLoading; - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; + if (value == _host) + return; - _host = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } + } - public ICollectionView HostHistoryView { get; } + public ICollectionView HostHistoryView { get; } - public ICollectionView DNSServers { get; } + public ICollectionView DNSServers { get; } - private DNSServerConnectionInfoProfile _dnsServer = new(); - public DNSServerConnectionInfoProfile DNSServer + private DNSServerConnectionInfoProfile _dnsServer = new(); + public DNSServerConnectionInfoProfile DNSServer + { + get => _dnsServer; + set { - get => _dnsServer; - set - { - if (value == _dnsServer) - return; + if (value == _dnsServer) + return; - if (!_isLoading) - SettingsManager.Current.DNSLookup_SelectedDNSServer_v2 = value; + if (!_isLoading) + SettingsManager.Current.DNSLookup_SelectedDNSServer_v2 = value; - _dnsServer = value; - OnPropertyChanged(); - } + _dnsServer = value; + OnPropertyChanged(); } + } - private List _queryTypes = new(); - public List QueryTypes + private List _queryTypes = new(); + public List QueryTypes + { + get => _queryTypes; + set { - get => _queryTypes; - set - { - if (value == _queryTypes) - return; + if (value == _queryTypes) + return; - _queryTypes = value; - OnPropertyChanged(); - } + _queryTypes = value; + OnPropertyChanged(); } + } - private QueryType _queryType; - public QueryType QueryType + private QueryType _queryType; + public QueryType QueryType + { + get => _queryType; + set { - get => _queryType; - set - { - if (value == _queryType) - return; + if (value == _queryType) + return; - if (!_isLoading) - SettingsManager.Current.DNSLookup_QueryType = value; + if (!_isLoading) + SettingsManager.Current.DNSLookup_QueryType = value; - _queryType = value; - OnPropertyChanged(); - } + _queryType = value; + OnPropertyChanged(); } + } - private bool _isLookupRunning; - public bool IsLookupRunning + private bool _isLookupRunning; + public bool IsLookupRunning + { + get => _isLookupRunning; + set { - get => _isLookupRunning; - set - { - if (value == _isLookupRunning) - return; + if (value == _isLookupRunning) + return; - _isLookupRunning = value; - OnPropertyChanged(); - } + _isLookupRunning = value; + OnPropertyChanged(); } + } - private ObservableCollection _lookupResults = new ObservableCollection(); - public ObservableCollection LookupResults + private ObservableCollection _lookupResults = new ObservableCollection(); + public ObservableCollection LookupResults + { + get => _lookupResults; + set { - get => _lookupResults; - set - { - if (Equals(value, _lookupResults)) - return; + if (Equals(value, _lookupResults)) + return; - _lookupResults = value; - } + _lookupResults = value; } + } - public ICollectionView LookupResultsView { get; } + public ICollectionView LookupResultsView { get; } - private DNSLookupRecordInfo _selectedLookupResult; - public DNSLookupRecordInfo SelectedLookupResult + private DNSLookupRecordInfo _selectedLookupResult; + public DNSLookupRecordInfo SelectedLookupResult + { + get => _selectedLookupResult; + set { - get => _selectedLookupResult; - set - { - if (value == _selectedLookupResult) - return; + if (value == _selectedLookupResult) + return; - _selectedLookupResult = value; - OnPropertyChanged(); - } + _selectedLookupResult = value; + OnPropertyChanged(); } + } - private IList _selectedLookupResults = new ArrayList(); - public IList SelectedLookupResults + private IList _selectedLookupResults = new ArrayList(); + public IList SelectedLookupResults + { + get => _selectedLookupResults; + set { - get => _selectedLookupResults; - set - { - if (Equals(value, _selectedLookupResults)) - return; + if (Equals(value, _selectedLookupResults)) + return; - _selectedLookupResults = value; - OnPropertyChanged(); - } + _selectedLookupResults = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public DNSLookupViewModel(IDialogCoordinator instance, int tabId, string host) - { - _isLoading = true; + #region Contructor, load settings + public DNSLookupViewModel(IDialogCoordinator instance, int tabId, string host) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - TabId = tabId; - Host = host; + TabId = tabId; + Host = host; - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.DNSLookup_HostHistory); + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.DNSLookup_HostHistory); - DNSServers = new CollectionViewSource { Source = SettingsManager.Current.DNSLookup_DNSServers_v2 }.View; - DNSServers.SortDescriptions.Add(new SortDescription(nameof(DNSServerConnectionInfoProfile.UseWindowsDNSServer), ListSortDirection.Descending)); - DNSServers.SortDescriptions.Add(new SortDescription(nameof(DNSServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); - DNSServer = DNSServers.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.DNSLookup_SelectedDNSServer_v2.Name) ?? DNSServers.SourceCollection.Cast().First(); + DNSServers = new CollectionViewSource { Source = SettingsManager.Current.DNSLookup_DNSServers_v2 }.View; + DNSServers.SortDescriptions.Add(new SortDescription(nameof(DNSServerConnectionInfoProfile.UseWindowsDNSServer), ListSortDirection.Descending)); + DNSServers.SortDescriptions.Add(new SortDescription(nameof(DNSServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); + DNSServer = DNSServers.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.DNSLookup_SelectedDNSServer_v2.Name) ?? DNSServers.SourceCollection.Cast().First(); - LookupResultsView = CollectionViewSource.GetDefaultView(LookupResults); - LookupResultsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(DNSLookupRecordInfo.Server))); - LookupResultsView.SortDescriptions.Add(new SortDescription(nameof(DNSLookupRecordInfo.Server), ListSortDirection.Descending)); + LookupResultsView = CollectionViewSource.GetDefaultView(LookupResults); + LookupResultsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(DNSLookupRecordInfo.Server))); + LookupResultsView.SortDescriptions.Add(new SortDescription(nameof(DNSLookupRecordInfo.Server), ListSortDirection.Descending)); - LoadSettings(); + LoadSettings(); - // Detect if settings have changed... - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + // Detect if settings have changed... + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - public void OnLoaded() - { - if (!_firstLoad) - return; + public void OnLoaded() + { + if (!_firstLoad) + return; - if (!string.IsNullOrEmpty(Host)) - StartLookup(); + if (!string.IsNullOrEmpty(Host)) + StartLookup(); - _firstLoad = false; - } + _firstLoad = false; + } - private void LoadSettings() - { - LoadTypes(); - } + private void LoadSettings() + { + LoadTypes(); + } - private void LoadTypes() - { - // Filter by common types... - QueryTypes = SettingsManager.Current.DNSLookup_ShowOnlyMostCommonQueryTypes ? Enum.GetValues(typeof(QueryType)).Cast().Where(x => (x == QueryType.A || x == QueryType.AAAA || x == QueryType.ANY || x == QueryType.CNAME || x == QueryType.MX || x == QueryType.NS || x == QueryType.PTR || x == QueryType.SOA || x == QueryType.TXT)).OrderBy(x => x.ToString()).ToList() : System.Enum.GetValues(typeof(QueryType)).Cast().OrderBy(x => x.ToString()).ToList(); - QueryType = QueryTypes.FirstOrDefault(x => x == SettingsManager.Current.DNSLookup_QueryType); + private void LoadTypes() + { + // Filter by common types... + QueryTypes = SettingsManager.Current.DNSLookup_ShowOnlyMostCommonQueryTypes ? Enum.GetValues(typeof(QueryType)).Cast().Where(x => (x == QueryType.A || x == QueryType.AAAA || x == QueryType.ANY || x == QueryType.CNAME || x == QueryType.MX || x == QueryType.NS || x == QueryType.PTR || x == QueryType.SOA || x == QueryType.TXT)).OrderBy(x => x.ToString()).ToList() : System.Enum.GetValues(typeof(QueryType)).Cast().OrderBy(x => x.ToString()).ToList(); + QueryType = QueryTypes.FirstOrDefault(x => x == SettingsManager.Current.DNSLookup_QueryType); - // Fallback - if (QueryType == 0) - QueryType = QueryType.ANY; - } - #endregion + // Fallback + if (QueryType == 0) + QueryType = QueryType.ANY; + } + #endregion - #region ICommands & Actions - public ICommand LookupCommand => new RelayCommand(p => LookupAction(), Lookup_CanExecute); + #region ICommands & Actions + public ICommand LookupCommand => new RelayCommand(p => LookupAction(), Lookup_CanExecute); - private bool Lookup_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Lookup_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void LookupAction() - { - if (!IsLookupRunning) - StartLookup(); - } + private void LookupAction() + { + if (!IsLookupRunning) + StartLookup(); + } - public ICommand CopySelectedDomainNameCommand => new RelayCommand(p => CopySelectedDomainNameAction()); + public ICommand CopySelectedDomainNameCommand => new RelayCommand(p => CopySelectedDomainNameAction()); - private void CopySelectedDomainNameAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.DomainName); - } + private void CopySelectedDomainNameAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.DomainName); + } - public ICommand CopySelectedTTLCommand => new RelayCommand(p => CopySelectedTTLAction()); + public ICommand CopySelectedTTLCommand => new RelayCommand(p => CopySelectedTTLAction()); - private void CopySelectedTTLAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.TTL.ToString()); - } + private void CopySelectedTTLAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.TTL.ToString()); + } - public ICommand CopySelectedClassCommand => new RelayCommand(p => CopySelectedClassAction()); + public ICommand CopySelectedClassCommand => new RelayCommand(p => CopySelectedClassAction()); - private void CopySelectedClassAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.Class); - } + private void CopySelectedClassAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.Class); + } - public ICommand CopySelectedTypeCommand => new RelayCommand(p => CopySelectedTypeAction()); + public ICommand CopySelectedTypeCommand => new RelayCommand(p => CopySelectedTypeAction()); - private void CopySelectedTypeAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.Type); - } + private void CopySelectedTypeAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.Type); + } - public ICommand CopySelectedResultCommand => new RelayCommand(p => CopySelectedResultAction()); + public ICommand CopySelectedResultCommand => new RelayCommand(p => CopySelectedResultAction()); - private void CopySelectedResultAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.Result); - } + private void CopySelectedResultAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.Result); + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private async Task ExportAction() + private async Task ExportAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + Title = Localization.Resources.Strings.Export + }; - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? LookupResults : new ObservableCollection(SelectedLookupResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + try + { + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? LookupResults : new ObservableCollection(SelectedLookupResults.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - SettingsManager.Current.DNSLookup_ExportFileType = instance.FileType; - SettingsManager.Current.DNSLookup_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.DNSLookup_ExportFileType, SettingsManager.Current.DNSLookup_ExportFilePath); + SettingsManager.Current.DNSLookup_ExportFileType = instance.FileType; + SettingsManager.Current.DNSLookup_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.DNSLookup_ExportFileType, SettingsManager.Current.DNSLookup_ExportFilePath); - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - #region Methods - private void StartLookup() - { - IsStatusMessageDisplayed = false; - StatusMessage = string.Empty; + #region Methods + private void StartLookup() + { + IsStatusMessageDisplayed = false; + StatusMessage = string.Empty; - IsLookupRunning = true; + IsLookupRunning = true; - // Reset the latest results - LookupResults.Clear(); + // Reset the latest results + LookupResults.Clear(); - // Change the tab title (not nice, but it works) - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + // Change the tab title (not nice, but it works) + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); - if (window != null) + if (window != null) + { + foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) { - foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) - { - tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Host; - } + tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Host; } + } - AddHostToHistory(Host); + AddHostToHistory(Host); - DNSLookupSettings dnsSettings = new() - { - AddDNSSuffix = SettingsManager.Current.DNSLookup_AddDNSSuffix, - QueryClass = SettingsManager.Current.DNSLookup_QueryClass, - QueryType = QueryType, - Recursion = SettingsManager.Current.DNSLookup_Recursion, - UseCache = SettingsManager.Current.DNSLookup_UseCache, - UseTCPOnly = SettingsManager.Current.DNSLookup_UseTCPOnly, - Retries = SettingsManager.Current.DNSLookup_Retries, - Timeout = TimeSpan.FromSeconds(SettingsManager.Current.DNSLookup_Timeout), - }; - - if (SettingsManager.Current.DNSLookup_UseCustomDNSSuffix) - { - dnsSettings.UseCustomDNSSuffix = true; - dnsSettings.CustomDNSSuffix = SettingsManager.Current.DNSLookup_CustomDNSSuffix?.TrimStart('.'); - } + DNSLookupSettings dnsSettings = new() + { + AddDNSSuffix = SettingsManager.Current.DNSLookup_AddDNSSuffix, + QueryClass = SettingsManager.Current.DNSLookup_QueryClass, + QueryType = QueryType, + Recursion = SettingsManager.Current.DNSLookup_Recursion, + UseCache = SettingsManager.Current.DNSLookup_UseCache, + UseTCPOnly = SettingsManager.Current.DNSLookup_UseTCPOnly, + Retries = SettingsManager.Current.DNSLookup_Retries, + Timeout = TimeSpan.FromSeconds(SettingsManager.Current.DNSLookup_Timeout), + }; + + if (SettingsManager.Current.DNSLookup_UseCustomDNSSuffix) + { + dnsSettings.UseCustomDNSSuffix = true; + dnsSettings.CustomDNSSuffix = SettingsManager.Current.DNSLookup_CustomDNSSuffix?.TrimStart('.'); + } - DNSLookup dnsLookup; + DNSLookup dnsLookup; - if (DNSServer.UseWindowsDNSServer) - dnsLookup = new(dnsSettings); - else - dnsLookup = new(dnsSettings, DNSServer.Servers); + if (DNSServer.UseWindowsDNSServer) + dnsLookup = new(dnsSettings); + else + dnsLookup = new(dnsSettings, DNSServer.Servers); - dnsLookup.RecordReceived += DNSLookup_RecordReceived; - dnsLookup.LookupError += DNSLookup_LookupError; - dnsLookup.LookupComplete += DNSLookup_LookupComplete; + dnsLookup.RecordReceived += DNSLookup_RecordReceived; + dnsLookup.LookupError += DNSLookup_LookupError; + dnsLookup.LookupComplete += DNSLookup_LookupComplete; - dnsLookup.ResolveAsync(Host.Split(';').Select(x => x.Trim()).ToList()); - } + dnsLookup.ResolveAsync(Host.Split(';').Select(x => x.Trim()).ToList()); + } - public void OnClose() - { + public void OnClose() + { - } + } - // Modify history list - private void AddHostToHistory(string host) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.DNSLookup_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); + // Modify history list + private void AddHostToHistory(string host) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.DNSLookup_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.DNSLookup_HostHistory.Clear(); - OnPropertyChanged(nameof(Host)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.DNSLookup_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.DNSLookup_HostHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.DNSLookup_HostHistory.Add(x)); + } - public void SortResultByPropertyName(string sortDescription) - { - LookupResultsView.SortDescriptions.Clear(); - LookupResultsView.SortDescriptions.Add(new SortDescription(nameof(DNSLookupRecordInfo.Server), ListSortDirection.Descending)); + public void SortResultByPropertyName(string sortDescription) + { + LookupResultsView.SortDescriptions.Clear(); + LookupResultsView.SortDescriptions.Add(new SortDescription(nameof(DNSLookupRecordInfo.Server), ListSortDirection.Descending)); - if (_lastSortDescriptionAscending.Equals(sortDescription)) - { - LookupResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Descending)); - _lastSortDescriptionAscending = string.Empty; - } - else - { - LookupResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Ascending)); - _lastSortDescriptionAscending = sortDescription; - } + if (_lastSortDescriptionAscending.Equals(sortDescription)) + { + LookupResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Descending)); + _lastSortDescriptionAscending = string.Empty; } - #endregion - - #region Events - private void DNSLookup_RecordReceived(object sender, DNSLookupRecordArgs e) + else { - var dnsLookupRecordInfo = DNSLookupRecordInfo.Parse(e); - - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - LookupResults.Add(dnsLookupRecordInfo); - })); + LookupResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Ascending)); + _lastSortDescriptionAscending = sortDescription; } + } + #endregion - private void DNSLookup_LookupError(object sender, DNSLookupErrorArgs e) + #region Events + private void DNSLookup_RecordReceived(object sender, DNSLookupRecordArgs e) + { + var dnsLookupRecordInfo = DNSLookupRecordInfo.Parse(e); + + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - // Build the message based on the information in the DNSLookupErrorArgs - var statusMessage = $"{e.Query} @ {e.IPEndPoint} ==> {e.ErrorMessage}"; + LookupResults.Add(dnsLookupRecordInfo); + })); + } - // Show the message - if (!IsStatusMessageDisplayed) - { - StatusMessage = statusMessage; - IsStatusMessageDisplayed = true; + private void DNSLookup_LookupError(object sender, DNSLookupErrorArgs e) + { + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate + { + // Build the message based on the information in the DNSLookupErrorArgs + var statusMessage = $"{e.Query} @ {e.IPEndPoint} ==> {e.ErrorMessage}"; - return; - } + // Show the message + if (!IsStatusMessageDisplayed) + { + StatusMessage = statusMessage; + IsStatusMessageDisplayed = true; - // Append the message - StatusMessage += Environment.NewLine + statusMessage; - })); - } + return; + } - private void DNSLookup_LookupComplete(object sender, EventArgs e) - { - IsLookupRunning = false; - } + // Append the message + StatusMessage += Environment.NewLine + statusMessage; + })); + } - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void DNSLookup_LookupComplete(object sender, EventArgs e) + { + IsLookupRunning = false; + } + + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) { - switch (e.PropertyName) - { - case nameof(SettingsInfo.DNSLookup_ShowOnlyMostCommonQueryTypes): - LoadTypes(); - break; - } + case nameof(SettingsInfo.DNSLookup_ShowOnlyMostCommonQueryTypes): + LoadTypes(); + break; } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs index 7a2d68d9ad..c4b6a8c07d 100644 --- a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs @@ -1,152 +1,151 @@ using NETworkManager.Settings; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class DashboardSettingsViewModel : ViewModelBase { - public class DashboardSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private string _publicIPv4Address; - public string PublicIPv4Address + private string _publicIPv4Address; + public string PublicIPv4Address + { + get => _publicIPv4Address; + set { - get => _publicIPv4Address; - set - { - if (value == _publicIPv4Address) - return; - - if (!_isLoading) - SettingsManager.Current.Dashboard_PublicIPv4Address = value; - - _publicIPv4Address = value; - OnPropertyChanged(); - } - } + if (value == _publicIPv4Address) + return; - private string _publicIPv6Address; - public string PublicIPv6Address - { - get => _publicIPv6Address; - set - { - if (value == _publicIPv6Address) - return; - - if (!_isLoading) - SettingsManager.Current.Dashboard_PublicIPv6Address = value; - - _publicIPv6Address = value; - OnPropertyChanged(); - } - } + if (!_isLoading) + SettingsManager.Current.Dashboard_PublicIPv4Address = value; - private bool _checkPublicIPAddress; - public bool CheckPublicIPAddress - { - get => _checkPublicIPAddress; - set - { - if (value == _checkPublicIPAddress) - return; - - if (!_isLoading) - SettingsManager.Current.Dashboard_CheckPublicIPAddress = value; - - _checkPublicIPAddress = value; - OnPropertyChanged(); - } + _publicIPv4Address = value; + OnPropertyChanged(); } + } - private bool _usePublicIPv4AddressCustomAPI; - public bool UsePublicIPv4AddressCustomAPI + private string _publicIPv6Address; + public string PublicIPv6Address + { + get => _publicIPv6Address; + set { - get => _usePublicIPv4AddressCustomAPI; - set - { - if (value == _usePublicIPv4AddressCustomAPI) - return; - - if (!_isLoading) - SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI = value; - - _usePublicIPv4AddressCustomAPI = value; - OnPropertyChanged(); - } + if (value == _publicIPv6Address) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_PublicIPv6Address = value; + + _publicIPv6Address = value; + OnPropertyChanged(); } + } - private string _customPublicIPv4AddressAPI; - public string CustomPublicIPv4AddressAPI + private bool _checkPublicIPAddress; + public bool CheckPublicIPAddress + { + get => _checkPublicIPAddress; + set { - get => _customPublicIPv4AddressAPI; - set - { - if (value == _customPublicIPv4AddressAPI) - return; - - if (!_isLoading) - SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI = value; - - _customPublicIPv4AddressAPI = value; - OnPropertyChanged(); - } + if (value == _checkPublicIPAddress) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_CheckPublicIPAddress = value; + + _checkPublicIPAddress = value; + OnPropertyChanged(); } + } - private bool _usePublicIPv6AddressCustomAPI; - public bool UsePublicIPv6AddressCustomAPI + private bool _usePublicIPv4AddressCustomAPI; + public bool UsePublicIPv4AddressCustomAPI + { + get => _usePublicIPv4AddressCustomAPI; + set { - get => _usePublicIPv6AddressCustomAPI; - set - { - if (value == _usePublicIPv6AddressCustomAPI) - return; - - if (!_isLoading) - SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI = value; - - _usePublicIPv6AddressCustomAPI = value; - OnPropertyChanged(); - } + if (value == _usePublicIPv4AddressCustomAPI) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI = value; + + _usePublicIPv4AddressCustomAPI = value; + OnPropertyChanged(); } + } - private string _customPublicIPv6AddressAPI; - public string CustomPublicIPv6AddressAPI + private string _customPublicIPv4AddressAPI; + public string CustomPublicIPv4AddressAPI + { + get => _customPublicIPv4AddressAPI; + set { - get => _customPublicIPv6AddressAPI; - set - { - if (value == _customPublicIPv6AddressAPI) - return; - - if (!_isLoading) - SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI = value; - - _customPublicIPv6AddressAPI = value; - OnPropertyChanged(); - } + if (value == _customPublicIPv4AddressAPI) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI = value; + + _customPublicIPv4AddressAPI = value; + OnPropertyChanged(); } - #endregion + } - #region Contructor, load settings - public DashboardSettingsViewModel() + private bool _usePublicIPv6AddressCustomAPI; + public bool UsePublicIPv6AddressCustomAPI + { + get => _usePublicIPv6AddressCustomAPI; + set { - _isLoading = true; + if (value == _usePublicIPv6AddressCustomAPI) + return; - LoadSettings(); + if (!_isLoading) + SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI = value; - _isLoading = false; + _usePublicIPv6AddressCustomAPI = value; + OnPropertyChanged(); } + } - private void LoadSettings() + private string _customPublicIPv6AddressAPI; + public string CustomPublicIPv6AddressAPI + { + get => _customPublicIPv6AddressAPI; + set { - PublicIPv4Address = SettingsManager.Current.Dashboard_PublicIPv4Address; - PublicIPv6Address = SettingsManager.Current.Dashboard_PublicIPv6Address; - CheckPublicIPAddress = SettingsManager.Current.Dashboard_CheckPublicIPAddress; - UsePublicIPv4AddressCustomAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI; - CustomPublicIPv4AddressAPI = SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI; - UsePublicIPv6AddressCustomAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI; - CustomPublicIPv6AddressAPI = SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI; + if (value == _customPublicIPv6AddressAPI) + return; + + if (!_isLoading) + SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI = value; + + _customPublicIPv6AddressAPI = value; + OnPropertyChanged(); } - #endregion } + #endregion + + #region Contructor, load settings + public DashboardSettingsViewModel() + { + _isLoading = true; + + LoadSettings(); + + _isLoading = false; + } + + private void LoadSettings() + { + PublicIPv4Address = SettingsManager.Current.Dashboard_PublicIPv4Address; + PublicIPv6Address = SettingsManager.Current.Dashboard_PublicIPv6Address; + CheckPublicIPAddress = SettingsManager.Current.Dashboard_CheckPublicIPAddress; + UsePublicIPv4AddressCustomAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI; + CustomPublicIPv4AddressAPI = SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI; + UsePublicIPv6AddressCustomAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI; + CustomPublicIPv6AddressAPI = SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI; + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/DashboardViewModel.cs b/Source/NETworkManager/ViewModels/DashboardViewModel.cs index 8b14513a3c..00db4008bc 100644 --- a/Source/NETworkManager/ViewModels/DashboardViewModel.cs +++ b/Source/NETworkManager/ViewModels/DashboardViewModel.cs @@ -1,44 +1,43 @@ -namespace NETworkManager.ViewModels -{ - public class DashboardViewModel : ViewModelBase - { - #region Variables - - #endregion +namespace NETworkManager.ViewModels; - #region Constructor, load settings +public class DashboardViewModel : ViewModelBase +{ + #region Variables + + #endregion - public DashboardViewModel() - { - LoadSettings(); - } + #region Constructor, load settings - private void LoadSettings() - { + public DashboardViewModel() + { + LoadSettings(); + } - } - #endregion + private void LoadSettings() + { - #region ICommands & Actions + } + #endregion - #endregion + #region ICommands & Actions - #region Methods + #endregion - public void OnViewVisible() - { + #region Methods - } + public void OnViewVisible() + { - public void OnViewHide() - { + } - } - #endregion + public void OnViewHide() + { - #region Events - - #endregion } + #endregion + + #region Events + + #endregion } diff --git a/Source/NETworkManager/ViewModels/DiscoveryProtocolViewModel.cs b/Source/NETworkManager/ViewModels/DiscoveryProtocolViewModel.cs index d791a24dfe..99772bf3b6 100644 --- a/Source/NETworkManager/ViewModels/DiscoveryProtocolViewModel.cs +++ b/Source/NETworkManager/ViewModels/DiscoveryProtocolViewModel.cs @@ -15,415 +15,414 @@ using static NETworkManager.Models.Network.DiscoveryProtocol; using System.Windows.Threading; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class DiscoveryProtocolViewModel : ViewModelBase { - public class DiscoveryProtocolViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private DiscoveryProtocol _discoveryProtocol = new DiscoveryProtocol(); - private readonly bool _isLoading; - System.Timers.Timer _remainingTimer; - private int _secondsRemaining; + private DiscoveryProtocol _discoveryProtocol = new DiscoveryProtocol(); + private readonly bool _isLoading; + System.Timers.Timer _remainingTimer; + private int _secondsRemaining; - private bool _firstRun = true; - public bool FirstRun + private bool _firstRun = true; + public bool FirstRun + { + get => _firstRun; + set { - get => _firstRun; - set - { - if (value == _firstRun) - return; + if (value == _firstRun) + return; - _firstRun = value; - OnPropertyChanged(); - } + _firstRun = value; + OnPropertyChanged(); } + } - /* - private bool _isNetworkInteraceLoading; - public bool IsNetworkInterfaceLoading + /* + private bool _isNetworkInteraceLoading; + public bool IsNetworkInterfaceLoading + { + get => _isNetworkInteraceLoading; + set { - get => _isNetworkInteraceLoading; - set - { - if (value == _isNetworkInteraceLoading) - return; + if (value == _isNetworkInteraceLoading) + return; - _isNetworkInteraceLoading = value; - OnPropertyChanged(); - } + _isNetworkInteraceLoading = value; + OnPropertyChanged(); } + } - private List _networkInterfaces; - public List NetworkInterfaces + private List _networkInterfaces; + public List NetworkInterfaces + { + get => _networkInterfaces; + set { - get => _networkInterfaces; - set - { - if (value == _networkInterfaces) - return; + if (value == _networkInterfaces) + return; - _networkInterfaces = value; - OnPropertyChanged(); - } + _networkInterfaces = value; + OnPropertyChanged(); } + } - private NetworkInterfaceInfo _selectedNetworkInterface; - public NetworkInterfaceInfo SelectedNetworkInterface + private NetworkInterfaceInfo _selectedNetworkInterface; + public NetworkInterfaceInfo SelectedNetworkInterface + { + get => _selectedNetworkInterface; + set { - get => _selectedNetworkInterface; - set - { - if (value == _selectedNetworkInterface) - return; - - if (value != null) - { - if (!_isLoading) - SettingsManager.Current.DiscoveryProtocol_InterfaceId = value.Id; + if (value == _selectedNetworkInterface) + return; - CanCapture = value.IsOperational; - } + if (value != null) + { + if (!_isLoading) + SettingsManager.Current.DiscoveryProtocol_InterfaceId = value.Id; - _selectedNetworkInterface = value; - OnPropertyChanged(); + CanCapture = value.IsOperational; } + + _selectedNetworkInterface = value; + OnPropertyChanged(); } - */ + } + */ - private List _protocols = new List(); - public List Protocols + private List _protocols = new List(); + public List Protocols + { + get => _protocols; + set { - get => _protocols; - set - { - if (value == _protocols) - return; + if (value == _protocols) + return; - _protocols = value; - OnPropertyChanged(); - } + _protocols = value; + OnPropertyChanged(); } + } - private Protocol _selectedProtocol; - public Protocol SelectedProtocol + private Protocol _selectedProtocol; + public Protocol SelectedProtocol + { + get => _selectedProtocol; + set { - get => _selectedProtocol; - set - { - if (value == _selectedProtocol) - return; + if (value == _selectedProtocol) + return; - if (!_isLoading) - SettingsManager.Current.DiscoveryProtocol_Protocol = value; + if (!_isLoading) + SettingsManager.Current.DiscoveryProtocol_Protocol = value; - _selectedProtocol = value; - OnPropertyChanged(); - } + _selectedProtocol = value; + OnPropertyChanged(); } + } - private List _durations; - public List Durations + private List _durations; + public List Durations + { + get => _durations; + set { - get => _durations; - set - { - if (value == _durations) - return; + if (value == _durations) + return; - _durations = value; - OnPropertyChanged(); - } + _durations = value; + OnPropertyChanged(); } + } - private int _selectedDuration; - public int SelectedDuration + private int _selectedDuration; + public int SelectedDuration + { + get => _selectedDuration; + set { - get => _selectedDuration; - set - { - if (value == _selectedDuration) - return; + if (value == _selectedDuration) + return; - if (!_isLoading) - SettingsManager.Current.DiscoveryProtocol_Duration = value; + if (!_isLoading) + SettingsManager.Current.DiscoveryProtocol_Duration = value; - _selectedDuration = value; - OnPropertyChanged(); - } + _selectedDuration = value; + OnPropertyChanged(); } + } - /* - private bool _canCapture; - public bool CanCapture + /* + private bool _canCapture; + public bool CanCapture + { + get => _canCapture; + set { - get => _canCapture; - set - { - if (value == _canCapture) - return; + if (value == _canCapture) + return; - _canCapture = value; - OnPropertyChanged(); - } + _canCapture = value; + OnPropertyChanged(); } - */ + } + */ - private bool _isCapturing; - public bool IsCapturing + private bool _isCapturing; + public bool IsCapturing + { + get => _isCapturing; + set { - get => _isCapturing; - set - { - if (value == _isCapturing) - return; + if (value == _isCapturing) + return; - _isCapturing = value; - OnPropertyChanged(); - } + _isCapturing = value; + OnPropertyChanged(); } + } - private string _timeRemainingMessage; - public string TimeRemainingMessage + private string _timeRemainingMessage; + public string TimeRemainingMessage + { + get => _timeRemainingMessage; + set { - get => _timeRemainingMessage; - set - { - if (value == _timeRemainingMessage) - return; + if (value == _timeRemainingMessage) + return; - _timeRemainingMessage = value; - OnPropertyChanged(); - } + _timeRemainingMessage = value; + OnPropertyChanged(); } - - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + } + + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } + } - private bool _discoveryPackageReceived; - public bool DiscoveryPackageReceived + private bool _discoveryPackageReceived; + public bool DiscoveryPackageReceived + { + get => _discoveryPackageReceived; + set { - get => _discoveryPackageReceived; - set - { - if (value == _discoveryPackageReceived) - return; + if (value == _discoveryPackageReceived) + return; - _discoveryPackageReceived = value; - OnPropertyChanged(); - } + _discoveryPackageReceived = value; + OnPropertyChanged(); } + } - private DiscoveryProtocolPackageInfo _discoveryPackage; - public DiscoveryProtocolPackageInfo DiscoveryPackage + private DiscoveryProtocolPackageInfo _discoveryPackage; + public DiscoveryProtocolPackageInfo DiscoveryPackage + { + get => _discoveryPackage; + set { - get => _discoveryPackage; - set - { - if (value == _discoveryPackage) - return; + if (value == _discoveryPackage) + return; - _discoveryPackage = value; - OnPropertyChanged(); - } + _discoveryPackage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, LoadSettings - public DiscoveryProtocolViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Constructor, LoadSettings + public DiscoveryProtocolViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - //LoadNetworkInterfaces(); + //LoadNetworkInterfaces(); - // Detect if network address or status changed... - //NetworkChange.NetworkAvailabilityChanged += (sender, args) => ReloadNetworkInterfacesAction(); - //NetworkChange.NetworkAddressChanged += (sender, args) => ReloadNetworkInterfacesAction(); - - _discoveryProtocol.PackageReceived += DiscoveryProtocol_PackageReceived; - _discoveryProtocol.ErrorReceived += DiscoveryProtocol_ErrorReceived; - _discoveryProtocol.WarningReceived += DiscoveryProtocol_WarningReceived; - _discoveryProtocol.Complete += DiscoveryProtocol_Complete; + // Detect if network address or status changed... + //NetworkChange.NetworkAvailabilityChanged += (sender, args) => ReloadNetworkInterfacesAction(); + //NetworkChange.NetworkAddressChanged += (sender, args) => ReloadNetworkInterfacesAction(); + + _discoveryProtocol.PackageReceived += DiscoveryProtocol_PackageReceived; + _discoveryProtocol.ErrorReceived += DiscoveryProtocol_ErrorReceived; + _discoveryProtocol.WarningReceived += DiscoveryProtocol_WarningReceived; + _discoveryProtocol.Complete += DiscoveryProtocol_Complete; - _remainingTimer = new System.Timers.Timer - { - Interval = 1000 - }; + _remainingTimer = new System.Timers.Timer + { + Interval = 1000 + }; - _remainingTimer.Elapsed += Timer_Elapsed; + _remainingTimer.Elapsed += Timer_Elapsed; - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - /* - private async Task LoadNetworkInterfaces() + /* + private async Task LoadNetworkInterfaces() + { + IsNetworkInterfaceLoading = true; + + NetworkInterfaces = await Models.Network.NetworkInterface.GetNetworkInterfacesAsync(); + + // Get the last selected interface, if it is still available on this machine... + if (NetworkInterfaces.Count > 0) { - IsNetworkInterfaceLoading = true; + var info = NetworkInterfaces.FirstOrDefault(s => s.Id == SettingsManager.Current.DiscoveryProtocol_InterfaceId); - NetworkInterfaces = await Models.Network.NetworkInterface.GetNetworkInterfacesAsync(); + SelectedNetworkInterface = info ?? NetworkInterfaces[0]; + } - // Get the last selected interface, if it is still available on this machine... - if (NetworkInterfaces.Count > 0) - { - var info = NetworkInterfaces.FirstOrDefault(s => s.Id == SettingsManager.Current.DiscoveryProtocol_InterfaceId); + IsNetworkInterfaceLoading = false; + } + */ - SelectedNetworkInterface = info ?? NetworkInterfaces[0]; - } + private void LoadSettings() + { + Protocols = Enum.GetValues(typeof(Protocol)).Cast().OrderBy(x => x.ToString()).ToList(); + SelectedProtocol = Protocols.FirstOrDefault(x => x == SettingsManager.Current.DiscoveryProtocol_Protocol); + Durations = new List() { 15, 30, 60, 90, 120 }; + SelectedDuration = Durations.FirstOrDefault(x => x == SettingsManager.Current.DiscoveryProtocol_Duration); + } + #endregion - IsNetworkInterfaceLoading = false; - } - */ + #region ICommands & Actions + public ICommand RestartAsAdminCommand => new RelayCommand(p => RestartAsAdminAction()); - private void LoadSettings() + public async Task RestartAsAdminAction() + { + try { - Protocols = Enum.GetValues(typeof(Protocol)).Cast().OrderBy(x => x.ToString()).ToList(); - SelectedProtocol = Protocols.FirstOrDefault(x => x == SettingsManager.Current.DiscoveryProtocol_Protocol); - Durations = new List() { 15, 30, 60, 90, 120 }; - SelectedDuration = Durations.FirstOrDefault(x => x == SettingsManager.Current.DiscoveryProtocol_Duration); + (Application.Current.MainWindow as MainWindow).RestartApplication(true); } - #endregion - - #region ICommands & Actions - public ICommand RestartAsAdminCommand => new RelayCommand(p => RestartAsAdminAction()); - - public async Task RestartAsAdminAction() + catch (Exception ex) { - try - { - (Application.Current.MainWindow as MainWindow).RestartApplication(true); - } - catch (Exception ex) - { - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); } + } - public ICommand CaptureCommand => new RelayCommand(p => CaptureAction()); + public ICommand CaptureCommand => new RelayCommand(p => CaptureAction()); - public async Task CaptureAction() - { - if (FirstRun) - FirstRun = false; + public async Task CaptureAction() + { + if (FirstRun) + FirstRun = false; - IsStatusMessageDisplayed = false; - StatusMessage = string.Empty; + IsStatusMessageDisplayed = false; + StatusMessage = string.Empty; - DiscoveryPackageReceived = false; + DiscoveryPackageReceived = false; - IsCapturing = true; + IsCapturing = true; - int duration = SelectedDuration + 2; // Capture 2 seconds more than the user chose + int duration = SelectedDuration + 2; // Capture 2 seconds more than the user chose - _secondsRemaining = duration + 1; // Init powershell etc. takes some time... + _secondsRemaining = duration + 1; // Init powershell etc. takes some time... - TimeRemainingMessage = string.Format(Localization.Resources.Strings.XXSecondsRemainingDots, _secondsRemaining); + TimeRemainingMessage = string.Format(Localization.Resources.Strings.XXSecondsRemainingDots, _secondsRemaining); - _remainingTimer.Start(); + _remainingTimer.Start(); - try - { - _discoveryProtocol.CaptureAsync(duration, SelectedProtocol); - } - catch (Exception ex) - { - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); - } + try + { + _discoveryProtocol.CaptureAsync(duration, SelectedProtocol); } + catch (Exception ex) + { + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); + } + } - private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - TimeRemainingMessage = string.Format(Localization.Resources.Strings.XXSecondsRemainingDots, _secondsRemaining); + TimeRemainingMessage = string.Format(Localization.Resources.Strings.XXSecondsRemainingDots, _secondsRemaining); - if (_secondsRemaining > 0) - _secondsRemaining--; - })); - } - #endregion + if (_secondsRemaining > 0) + _secondsRemaining--; + })); + } + #endregion - #region Methods - public void OnViewVisible() - { + #region Methods + public void OnViewVisible() + { - } + } - public void OnViewHide() - { + public void OnViewHide() + { - } - #endregion + } + #endregion - #region Events - private void DiscoveryProtocol_PackageReceived(object sender, DiscoveryProtocolPackageArgs e) - { - DiscoveryPackage = e.PackageInfo; + #region Events + private void DiscoveryProtocol_PackageReceived(object sender, DiscoveryProtocolPackageArgs e) + { + DiscoveryPackage = e.PackageInfo; - DiscoveryPackageReceived = true; - } + DiscoveryPackageReceived = true; + } - private void DiscoveryProtocol_WarningReceived(object sender, DiscoveryProtocolWarningArgs e) - { - if (!string.IsNullOrEmpty(StatusMessage)) - StatusMessage += Environment.NewLine; + private void DiscoveryProtocol_WarningReceived(object sender, DiscoveryProtocolWarningArgs e) + { + if (!string.IsNullOrEmpty(StatusMessage)) + StatusMessage += Environment.NewLine; - StatusMessage += e.Message; + StatusMessage += e.Message; - IsStatusMessageDisplayed = true; - } + IsStatusMessageDisplayed = true; + } - private void DiscoveryProtocol_ErrorReceived(object sender, DiscoveryProtocolErrorArgs e) - { - if (!string.IsNullOrEmpty(StatusMessage)) - StatusMessage += Environment.NewLine; + private void DiscoveryProtocol_ErrorReceived(object sender, DiscoveryProtocolErrorArgs e) + { + if (!string.IsNullOrEmpty(StatusMessage)) + StatusMessage += Environment.NewLine; - StatusMessage += e.Message; + StatusMessage += e.Message; - IsStatusMessageDisplayed = true; - } + IsStatusMessageDisplayed = true; + } - private void DiscoveryProtocol_Complete(object sender, EventArgs e) - { - _remainingTimer.Stop(); - IsCapturing = false; - } + private void DiscoveryProtocol_Complete(object sender, EventArgs e) + { + _remainingTimer.Stop(); + IsCapturing = false; + } - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - } - #endregion + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { } + #endregion } diff --git a/Source/NETworkManager/ViewModels/DropdownViewModel.cs b/Source/NETworkManager/ViewModels/DropdownViewModel.cs index db015d3d62..a347ffe30e 100644 --- a/Source/NETworkManager/ViewModels/DropdownViewModel.cs +++ b/Source/NETworkManager/ViewModels/DropdownViewModel.cs @@ -4,65 +4,64 @@ using System.Linq; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class DropdownViewModel : ViewModelBase { - public class DropdownViewModel : ViewModelBase - { - public ICommand OKCommand { get; } + public ICommand OKCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _valueDescription; - public string ValueDescription + private string _valueDescription; + public string ValueDescription + { + get => _valueDescription; + set { - get => _valueDescription; - set - { - if(value == _valueDescription) - return; + if(value == _valueDescription) + return; - _valueDescription = value; - OnPropertyChanged(); - } + _valueDescription = value; + OnPropertyChanged(); } + } - private List _values; - public List Values + private List _values; + public List Values + { + get => _values; + set { - get => _values; - set - { - if (value == _values) - return; + if (value == _values) + return; - _values = value; - OnPropertyChanged(); - } + _values = value; + OnPropertyChanged(); } + } - private string _selectedValue; - public string SelectedValue + private string _selectedValue; + public string SelectedValue + { + get => _selectedValue; + set { - get => _selectedValue; - set - { - if (value == _selectedValue) - return; + if (value == _selectedValue) + return; - _selectedValue = value; - OnPropertyChanged(); - } + _selectedValue = value; + OnPropertyChanged(); } + } - public DropdownViewModel(Action okCommand, Action cancelHandler, List values, string valueDescription) - { - ValueDescription = valueDescription; - Values = values; + public DropdownViewModel(Action okCommand, Action cancelHandler, List values, string valueDescription) + { + ValueDescription = valueDescription; + Values = values; - SelectedValue = Values.FirstOrDefault(); + SelectedValue = Values.FirstOrDefault(); - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - } - } + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ExportViewModel.cs b/Source/NETworkManager/ViewModels/ExportViewModel.cs index 246d0d9676..9bc2f753ca 100644 --- a/Source/NETworkManager/ViewModels/ExportViewModel.cs +++ b/Source/NETworkManager/ViewModels/ExportViewModel.cs @@ -7,298 +7,297 @@ using NETworkManager.Localization.Resources; using System.Linq; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +/// +/// +/// +public class ExportViewModel : ViewModelBase { /// /// /// - public class ExportViewModel : ViewModelBase + public ICommand ExportCommand { get; } + + /// + /// + /// + public ICommand CancelCommand { get; } + + /// + /// + /// + private bool _exportAll = true; + + /// + /// + /// + public bool ExportAll { - /// - /// - /// - public ICommand ExportCommand { get; } - - /// - /// - /// - public ICommand CancelCommand { get; } - - /// - /// - /// - private bool _exportAll = true; - - /// - /// - /// - public bool ExportAll + get => _exportAll; + set { - get => _exportAll; - set - { - if (value == _exportAll) - return; + if (value == _exportAll) + return; - _exportAll = value; - OnPropertyChanged(); - } + _exportAll = value; + OnPropertyChanged(); } + } - /// - /// - /// - private bool _showExportSelected; + /// + /// + /// + private bool _showExportSelected; - /// - /// - /// - public bool ShowExportSelected + /// + /// + /// + public bool ShowExportSelected + { + get => _showExportSelected; + set { - get => _showExportSelected; - set - { - if (value == _showExportSelected) - return; + if (value == _showExportSelected) + return; - _showExportSelected = value; - OnPropertyChanged(); - } + _showExportSelected = value; + OnPropertyChanged(); } + } - private bool _exportSelected; - public bool ExportSelected + private bool _exportSelected; + public bool ExportSelected + { + get => _exportSelected; + set { - get => _exportSelected; - set - { - if (value == _exportSelected) - return; + if (value == _exportSelected) + return; - _exportSelected = value; - OnPropertyChanged(); - } + _exportSelected = value; + OnPropertyChanged(); } + } - public ExportManager.ExportFileType FileType { get; set; } + public ExportManager.ExportFileType FileType { get; set; } - private bool _showCSV; - public bool ShowCSV + private bool _showCSV; + public bool ShowCSV + { + get => _showCSV; + set { - get => _showCSV; - set - { - if (value == _showCSV) - return; + if (value == _showCSV) + return; - _showCSV = value; - OnPropertyChanged(); - } + _showCSV = value; + OnPropertyChanged(); } + } - private bool _useCSV; - public bool UseCSV + private bool _useCSV; + public bool UseCSV + { + get => _useCSV; + set { - get => _useCSV; - set - { - if (value == _useCSV) - return; - - if (value) - { - FileType = ExportManager.ExportFileType.CSV; - ChangeFilePathExtension(FileType); - } + if (value == _useCSV) + return; - _useCSV = value; - OnPropertyChanged(); + if (value) + { + FileType = ExportManager.ExportFileType.CSV; + ChangeFilePathExtension(FileType); } + + _useCSV = value; + OnPropertyChanged(); } + } - private bool _showXML; - public bool ShowXML + private bool _showXML; + public bool ShowXML + { + get => _showXML; + set { - get => _showXML; - set - { - if (value == _showXML) - return; + if (value == _showXML) + return; - _showXML = value; - OnPropertyChanged(); - } + _showXML = value; + OnPropertyChanged(); } + } - private bool _useXML; - public bool UseXML + private bool _useXML; + public bool UseXML + { + get => _useXML; + set { - get => _useXML; - set - { - if (value == _useXML) - return; - - if (value) - { - FileType = ExportManager.ExportFileType.XML; - ChangeFilePathExtension(FileType); - } + if (value == _useXML) + return; - _useXML = value; - OnPropertyChanged(); + if (value) + { + FileType = ExportManager.ExportFileType.XML; + ChangeFilePathExtension(FileType); } + + _useXML = value; + OnPropertyChanged(); } + } - private bool _showJSON; - public bool ShowJSON + private bool _showJSON; + public bool ShowJSON + { + get => _showJSON; + set { - get => _showJSON; - set - { - if (value == _showJSON) - return; + if (value == _showJSON) + return; - _showJSON = value; - OnPropertyChanged(); - } + _showJSON = value; + OnPropertyChanged(); } + } - private bool _useJSON; - public bool UseJSON + private bool _useJSON; + public bool UseJSON + { + get => _useJSON; + set { - get => _useJSON; - set - { - if (value == _useJSON) - return; - - if (value) - { - FileType = ExportManager.ExportFileType.JSON; - ChangeFilePathExtension(FileType); - } + if (value == _useJSON) + return; - _useJSON = value; - OnPropertyChanged(); + if (value) + { + FileType = ExportManager.ExportFileType.JSON; + ChangeFilePathExtension(FileType); } + + _useJSON = value; + OnPropertyChanged(); } + } - private bool _showTXT; - public bool ShowTXT + private bool _showTXT; + public bool ShowTXT + { + get => _showTXT; + set { - get => _showTXT; - set - { - if (value == _showTXT) - return; + if (value == _showTXT) + return; - _showTXT = value; - OnPropertyChanged(); - } + _showTXT = value; + OnPropertyChanged(); } + } - private bool _useTXT; - public bool UseTXT + private bool _useTXT; + public bool UseTXT + { + get => _useTXT; + set { - get => _useTXT; - set - { - if (value == _useTXT) - return; - - if (value) - { - FileType = ExportManager.ExportFileType.TXT; - ChangeFilePathExtension(FileType); - } + if (value == _useTXT) + return; - _useTXT = value; - OnPropertyChanged(); + if (value) + { + FileType = ExportManager.ExportFileType.TXT; + ChangeFilePathExtension(FileType); } + + _useTXT = value; + OnPropertyChanged(); } + } - private string _filePath; - public string FilePath + private string _filePath; + public string FilePath + { + get => _filePath; + set { - get => _filePath; - set - { - if (value == _filePath) - return; + if (value == _filePath) + return; - _filePath = value; - OnPropertyChanged(); - } + _filePath = value; + OnPropertyChanged(); } + } - public ExportViewModel(Action deleteCommand, Action cancelHandler, ExportManager.ExportFileType[] showFilesTypes, bool showExportSelected) - { - ExportCommand = new RelayCommand(p => deleteCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + public ExportViewModel(Action deleteCommand, Action cancelHandler, ExportManager.ExportFileType[] showFilesTypes, bool showExportSelected) + { + ExportCommand = new RelayCommand(p => deleteCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - ShowCSV = showFilesTypes.Contains(ExportManager.ExportFileType.CSV); - ShowXML = showFilesTypes.Contains(ExportManager.ExportFileType.XML); - ShowJSON = showFilesTypes.Contains(ExportManager.ExportFileType.JSON); - ShowTXT = showFilesTypes.Contains(ExportManager.ExportFileType.TXT); + ShowCSV = showFilesTypes.Contains(ExportManager.ExportFileType.CSV); + ShowXML = showFilesTypes.Contains(ExportManager.ExportFileType.XML); + ShowJSON = showFilesTypes.Contains(ExportManager.ExportFileType.JSON); + ShowTXT = showFilesTypes.Contains(ExportManager.ExportFileType.TXT); - ShowExportSelected = showExportSelected; - } + ShowExportSelected = showExportSelected; + } - public ExportViewModel(Action deleteCommand, Action cancelHandler, ExportManager.ExportFileType[] showFilesTypes, bool showExportSelected, ExportManager.ExportFileType fileType, string filePath) : - this(deleteCommand, cancelHandler, showFilesTypes, showExportSelected) - { - FilePath = filePath; + public ExportViewModel(Action deleteCommand, Action cancelHandler, ExportManager.ExportFileType[] showFilesTypes, bool showExportSelected, ExportManager.ExportFileType fileType, string filePath) : + this(deleteCommand, cancelHandler, showFilesTypes, showExportSelected) + { + FilePath = filePath; - switch (fileType) - { - case ExportManager.ExportFileType.CSV: - UseCSV = true; - break; - case ExportManager.ExportFileType.XML: - UseXML = true; - break; - case ExportManager.ExportFileType.JSON: - UseJSON = true; - break; - case ExportManager.ExportFileType.TXT: - UseTXT = true; - break; - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + switch (fileType) + { + case ExportManager.ExportFileType.CSV: + UseCSV = true; + break; + case ExportManager.ExportFileType.XML: + UseXML = true; + break; + case ExportManager.ExportFileType.JSON: + UseJSON = true; + break; + case ExportManager.ExportFileType.TXT: + UseTXT = true; + break; + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); } + } - public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); + public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); - private void BrowseFileAction() - { - var saveFileDialog = new SaveFileDialog(); + private void BrowseFileAction() + { + var saveFileDialog = new SaveFileDialog(); - var fileExtension = ExportManager.GetFileExtensionAsString(FileType); + var fileExtension = ExportManager.GetFileExtensionAsString(FileType); - saveFileDialog.Filter = $@"{fileExtension}-{Strings.File} | *.{fileExtension.ToLower()}"; + saveFileDialog.Filter = $@"{fileExtension}-{Strings.File} | *.{fileExtension.ToLower()}"; - if (saveFileDialog.ShowDialog() == DialogResult.OK) - { - FilePath = saveFileDialog.FileName; - } + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + FilePath = saveFileDialog.FileName; } + } - private void ChangeFilePathExtension(ExportManager.ExportFileType fileType) - { - if (string.IsNullOrEmpty(FilePath)) - return; + private void ChangeFilePathExtension(ExportManager.ExportFileType fileType) + { + if (string.IsNullOrEmpty(FilePath)) + return; - var extension = Path.GetExtension(FilePath).Replace(".", ""); + var extension = Path.GetExtension(FilePath).Replace(".", ""); - var newExtension = ExportManager.GetFileExtensionAsString(fileType); + var newExtension = ExportManager.GetFileExtensionAsString(fileType); - if (extension.Equals(newExtension, StringComparison.OrdinalIgnoreCase)) - return; + if (extension.Equals(newExtension, StringComparison.OrdinalIgnoreCase)) + return; - FilePath = FilePath[..^extension.Length] + newExtension.ToLower(); - } + FilePath = FilePath[..^extension.Length] + newExtension.ToLower(); } } diff --git a/Source/NETworkManager/ViewModels/FirstRunViewModel.cs b/Source/NETworkManager/ViewModels/FirstRunViewModel.cs index bc12119c3d..7be65448c0 100644 --- a/Source/NETworkManager/ViewModels/FirstRunViewModel.cs +++ b/Source/NETworkManager/ViewModels/FirstRunViewModel.cs @@ -2,57 +2,56 @@ using System; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class FirstRunViewModel : ViewModelBase { - public class FirstRunViewModel : ViewModelBase - { - public ICommand ContinueCommand { get; } + public ICommand ContinueCommand { get; } - private bool _checkForUpdatesAtStartup = true; - public bool CheckForUpdatesAtStartup + private bool _checkForUpdatesAtStartup = true; + public bool CheckForUpdatesAtStartup + { + get => _checkForUpdatesAtStartup; + set { - get => _checkForUpdatesAtStartup; - set - { - if (value == _checkForUpdatesAtStartup) - return; - - _checkForUpdatesAtStartup = value; - OnPropertyChanged(); - } - } + if (value == _checkForUpdatesAtStartup) + return; - private bool _checkPublicIPAddress = true; - public bool CheckPublicIPAddress - { - get => _checkPublicIPAddress; - set - { - if (value == _checkPublicIPAddress) - return; - - _checkPublicIPAddress = value; - OnPropertyChanged(); - } + _checkForUpdatesAtStartup = value; + OnPropertyChanged(); } + } - private bool _powerShellModifyGlobalProfile; - public bool PowerShellModifyGlobalProfile + private bool _checkPublicIPAddress = true; + public bool CheckPublicIPAddress + { + get => _checkPublicIPAddress; + set { - get => _powerShellModifyGlobalProfile; - set - { - if (value == _powerShellModifyGlobalProfile) - return; - - _powerShellModifyGlobalProfile = value; - OnPropertyChanged(); - } + if (value == _checkPublicIPAddress) + return; + + _checkPublicIPAddress = value; + OnPropertyChanged(); } + } - public FirstRunViewModel(Action continueCommand) + private bool _powerShellModifyGlobalProfile; + public bool PowerShellModifyGlobalProfile + { + get => _powerShellModifyGlobalProfile; + set { - ContinueCommand = new RelayCommand(p => continueCommand(this)); + if (value == _powerShellModifyGlobalProfile) + return; + + _powerShellModifyGlobalProfile = value; + OnPropertyChanged(); } } + + public FirstRunViewModel(Action continueCommand) + { + ContinueCommand = new RelayCommand(p => continueCommand(this)); + } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/GroupViewModel.cs b/Source/NETworkManager/ViewModels/GroupViewModel.cs index 7724307503..f44384f612 100644 --- a/Source/NETworkManager/ViewModels/GroupViewModel.cs +++ b/Source/NETworkManager/ViewModels/GroupViewModel.cs @@ -12,1394 +12,1393 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class GroupViewModel : ViewModelBase { - public class GroupViewModel : ViewModelBase - { - private readonly bool _isLoading = true; + private readonly bool _isLoading = true; - public bool IsProfileFileEncrypted => ProfileManager.LoadedProfileFile.IsEncrypted; + public bool IsProfileFileEncrypted => ProfileManager.LoadedProfileFile.IsEncrypted; - public ICollectionView GroupViews { get; } - public GroupInfo Group { get; } + public ICollectionView GroupViews { get; } + public GroupInfo Group { get; } - private IReadOnlyCollection _groups { get; } + private IReadOnlyCollection _groups { get; } - #region General - private bool _nameIsValid = true; - public bool NameIsValid + #region General + private bool _nameIsValid = true; + public bool NameIsValid + { + get => _nameIsValid; + set { - get => _nameIsValid; - set - { - if (value == _nameIsValid) - return; + if (value == _nameIsValid) + return; - _nameIsValid = value; - OnPropertyChanged(); - } + _nameIsValid = value; + OnPropertyChanged(); } + } - private string _name; - public string Name + private string _name; + public string Name + { + get => _name; + set { - get => _name; - set - { - if (value == _name) - return; + if (value == _name) + return; - // Check name for duplicate... - if (_groups.Contains(value) && !value.Equals(Group.Name)) - NameIsValid = false; - else - NameIsValid = true; + // Check name for duplicate... + if (_groups.Contains(value) && !value.Equals(Group.Name)) + NameIsValid = false; + else + NameIsValid = true; - _name = value; - OnPropertyChanged(); - } + _name = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Remote Desktop - private bool _remoteDesktop_UseCredentials; - public bool RemoteDesktop_UseCredentials + #region Remote Desktop + private bool _remoteDesktop_UseCredentials; + public bool RemoteDesktop_UseCredentials + { + get => _remoteDesktop_UseCredentials; + set { - get => _remoteDesktop_UseCredentials; - set - { - if (value == _remoteDesktop_UseCredentials) - return; + if (value == _remoteDesktop_UseCredentials) + return; - _remoteDesktop_UseCredentials = value; - OnPropertyChanged(); - } + _remoteDesktop_UseCredentials = value; + OnPropertyChanged(); } + } - private string _remoteDesktop_Username; - public string RemoteDesktop_Username + private string _remoteDesktop_Username; + public string RemoteDesktop_Username + { + get => _remoteDesktop_Username; + set { - get => _remoteDesktop_Username; - set - { - if (value == _remoteDesktop_Username) - return; + if (value == _remoteDesktop_Username) + return; - _remoteDesktop_Username = value; - OnPropertyChanged(); - } + _remoteDesktop_Username = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_IsPasswordEmpty = true; // Initial it's empty - public bool RemoteDesktop_IsPasswordEmpty + private bool _remoteDesktop_IsPasswordEmpty = true; // Initial it's empty + public bool RemoteDesktop_IsPasswordEmpty + { + get => _remoteDesktop_IsPasswordEmpty; + set { - get => _remoteDesktop_IsPasswordEmpty; - set - { - if (value == _remoteDesktop_IsPasswordEmpty) - return; + if (value == _remoteDesktop_IsPasswordEmpty) + return; - _remoteDesktop_IsPasswordEmpty = value; - OnPropertyChanged(); - } + _remoteDesktop_IsPasswordEmpty = value; + OnPropertyChanged(); } + } - private SecureString _remoteDesktop_Password; + private SecureString _remoteDesktop_Password; - /// - /// RemoteDesktop password as secure string. - /// - public SecureString RemoteDesktop_Password + /// + /// RemoteDesktop password as secure string. + /// + public SecureString RemoteDesktop_Password + { + get => _remoteDesktop_Password; + set { - get => _remoteDesktop_Password; - set - { - if (value == _remoteDesktop_Password) - return; + if (value == _remoteDesktop_Password) + return; - // Validate the password string - RemoteDesktop_IsPasswordEmpty = value == null || string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); + // Validate the password string + RemoteDesktop_IsPasswordEmpty = value == null || string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); - _remoteDesktop_Password = value; - OnPropertyChanged(); - } + _remoteDesktop_Password = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_PasswordChanged; - public bool RemoteDesktop_PasswordChanged + private bool _remoteDesktop_PasswordChanged; + public bool RemoteDesktop_PasswordChanged + { + get => _remoteDesktop_PasswordChanged; + set { - get => _remoteDesktop_PasswordChanged; - set - { - if (value == _remoteDesktop_PasswordChanged) - return; + if (value == _remoteDesktop_PasswordChanged) + return; - _remoteDesktop_PasswordChanged = value; - OnPropertyChanged(); - } + _remoteDesktop_PasswordChanged = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideDisplay; - public bool RemoteDesktop_OverrideDisplay + private bool _remoteDesktop_OverrideDisplay; + public bool RemoteDesktop_OverrideDisplay + { + get => _remoteDesktop_OverrideDisplay; + set { - get => _remoteDesktop_OverrideDisplay; - set - { - if (value == _remoteDesktop_OverrideDisplay) - return; + if (value == _remoteDesktop_OverrideDisplay) + return; - _remoteDesktop_OverrideDisplay = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideDisplay = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_AdjustScreenAutomatically; - public bool RemoteDesktop_AdjustScreenAutomatically + private bool _remoteDesktop_AdjustScreenAutomatically; + public bool RemoteDesktop_AdjustScreenAutomatically + { + get => _remoteDesktop_AdjustScreenAutomatically; + set { - get => _remoteDesktop_AdjustScreenAutomatically; - set - { - if (value == _remoteDesktop_AdjustScreenAutomatically) - return; + if (value == _remoteDesktop_AdjustScreenAutomatically) + return; - _remoteDesktop_AdjustScreenAutomatically = value; - OnPropertyChanged(); - } + _remoteDesktop_AdjustScreenAutomatically = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_UseCurrentViewSize; - public bool RemoteDesktop_UseCurrentViewSize + private bool _remoteDesktop_UseCurrentViewSize; + public bool RemoteDesktop_UseCurrentViewSize + { + get => _remoteDesktop_UseCurrentViewSize; + set { - get => _remoteDesktop_UseCurrentViewSize; - set - { - if (value == _remoteDesktop_UseCurrentViewSize) - return; + if (value == _remoteDesktop_UseCurrentViewSize) + return; - _remoteDesktop_UseCurrentViewSize = value; - OnPropertyChanged(); - } + _remoteDesktop_UseCurrentViewSize = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_UseFixedScreenSize; - public bool RemoteDesktop_UseFixedScreenSize + private bool _remoteDesktop_UseFixedScreenSize; + public bool RemoteDesktop_UseFixedScreenSize + { + get => _remoteDesktop_UseFixedScreenSize; + set { - get => _remoteDesktop_UseFixedScreenSize; - set - { - if (value == _remoteDesktop_UseFixedScreenSize) - return; + if (value == _remoteDesktop_UseFixedScreenSize) + return; - _remoteDesktop_UseFixedScreenSize = value; - OnPropertyChanged(); - } + _remoteDesktop_UseFixedScreenSize = value; + OnPropertyChanged(); } + } - public List RemoteDesktop_ScreenResolutions => RemoteDesktop.ScreenResolutions; + public List RemoteDesktop_ScreenResolutions => RemoteDesktop.ScreenResolutions; - public int RemoteDesktop_ScreenWidth; - public int RemoteDesktop_ScreenHeight; + public int RemoteDesktop_ScreenWidth; + public int RemoteDesktop_ScreenHeight; - private string _remoteDesktop_SelectedScreenResolution; - public string RemoteDesktop_SelectedScreenResolution + private string _remoteDesktop_SelectedScreenResolution; + public string RemoteDesktop_SelectedScreenResolution + { + get => _remoteDesktop_SelectedScreenResolution; + set { - get => _remoteDesktop_SelectedScreenResolution; - set - { - if (value == _remoteDesktop_SelectedScreenResolution) - return; + if (value == _remoteDesktop_SelectedScreenResolution) + return; - var resolution = value.Split('x'); + var resolution = value.Split('x'); - RemoteDesktop_ScreenWidth = int.Parse(resolution[0]); - RemoteDesktop_ScreenHeight = int.Parse(resolution[1]); + RemoteDesktop_ScreenWidth = int.Parse(resolution[0]); + RemoteDesktop_ScreenHeight = int.Parse(resolution[1]); - _remoteDesktop_SelectedScreenResolution = value; - OnPropertyChanged(); - } + _remoteDesktop_SelectedScreenResolution = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_UseCustomScreenSize; - public bool RemoteDesktop_UseCustomScreenSize + private bool _remoteDesktop_UseCustomScreenSize; + public bool RemoteDesktop_UseCustomScreenSize + { + get => _remoteDesktop_UseCustomScreenSize; + set { - get => _remoteDesktop_UseCustomScreenSize; - set - { - if (value == _remoteDesktop_UseCustomScreenSize) - return; + if (value == _remoteDesktop_UseCustomScreenSize) + return; - _remoteDesktop_UseCustomScreenSize = value; - OnPropertyChanged(); - } + _remoteDesktop_UseCustomScreenSize = value; + OnPropertyChanged(); } + } - private string _remoteDesktop_CustomScreenWidth; - public string RemoteDesktop_CustomScreenWidth + private string _remoteDesktop_CustomScreenWidth; + public string RemoteDesktop_CustomScreenWidth + { + get => _remoteDesktop_CustomScreenWidth; + set { - get => _remoteDesktop_CustomScreenWidth; - set - { - if (value == _remoteDesktop_CustomScreenWidth) - return; + if (value == _remoteDesktop_CustomScreenWidth) + return; - _remoteDesktop_CustomScreenWidth = value; - OnPropertyChanged(); - } + _remoteDesktop_CustomScreenWidth = value; + OnPropertyChanged(); } + } - private string _remoteDesktop_CustomScreenHeight; - public string RemoteDesktop_CustomScreenHeight + private string _remoteDesktop_CustomScreenHeight; + public string RemoteDesktop_CustomScreenHeight + { + get => _remoteDesktop_CustomScreenHeight; + set { - get => _remoteDesktop_CustomScreenHeight; - set - { - if (value == _remoteDesktop_CustomScreenHeight) - return; + if (value == _remoteDesktop_CustomScreenHeight) + return; - _remoteDesktop_CustomScreenHeight = value; - OnPropertyChanged(); - } + _remoteDesktop_CustomScreenHeight = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideColorDepth; - public bool RemoteDesktop_OverrideColorDepth + private bool _remoteDesktop_OverrideColorDepth; + public bool RemoteDesktop_OverrideColorDepth + { + get => _remoteDesktop_OverrideColorDepth; + set { - get => _remoteDesktop_OverrideColorDepth; - set - { - if (value == _remoteDesktop_OverrideColorDepth) - return; + if (value == _remoteDesktop_OverrideColorDepth) + return; - _remoteDesktop_OverrideColorDepth = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideColorDepth = value; + OnPropertyChanged(); } + } - public List RemoteDesktop_ColorDepths => RemoteDesktop.ColorDepths; + public List RemoteDesktop_ColorDepths => RemoteDesktop.ColorDepths; - private int _remoteDesktop_SelectedColorDepth; - public int RemoteDesktop_SelectedColorDepth + private int _remoteDesktop_SelectedColorDepth; + public int RemoteDesktop_SelectedColorDepth + { + get => _remoteDesktop_SelectedColorDepth; + set { - get => _remoteDesktop_SelectedColorDepth; - set - { - if (value == _remoteDesktop_SelectedColorDepth) - return; + if (value == _remoteDesktop_SelectedColorDepth) + return; - _remoteDesktop_SelectedColorDepth = value; - OnPropertyChanged(); - } + _remoteDesktop_SelectedColorDepth = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverridePort; - public bool RemoteDesktop_OverridePort + private bool _remoteDesktop_OverridePort; + public bool RemoteDesktop_OverridePort + { + get => _remoteDesktop_OverridePort; + set { - get => _remoteDesktop_OverridePort; - set - { - if (value == _remoteDesktop_OverridePort) - return; + if (value == _remoteDesktop_OverridePort) + return; - _remoteDesktop_OverridePort = value; - OnPropertyChanged(); - } + _remoteDesktop_OverridePort = value; + OnPropertyChanged(); } + } - private int _remoteDesktop_Port; - public int RemoteDesktop_Port + private int _remoteDesktop_Port; + public int RemoteDesktop_Port + { + get => _remoteDesktop_Port; + set { - get => _remoteDesktop_Port; - set - { - if (value == _remoteDesktop_Port) - return; + if (value == _remoteDesktop_Port) + return; - _remoteDesktop_Port = value; - OnPropertyChanged(); - } + _remoteDesktop_Port = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideCredSspSupport; - public bool RemoteDesktop_OverrideCredSspSupport + private bool _remoteDesktop_OverrideCredSspSupport; + public bool RemoteDesktop_OverrideCredSspSupport + { + get => _remoteDesktop_OverrideCredSspSupport; + set { - get => _remoteDesktop_OverrideCredSspSupport; - set - { - if (value == _remoteDesktop_OverrideCredSspSupport) - return; + if (value == _remoteDesktop_OverrideCredSspSupport) + return; - _remoteDesktop_OverrideCredSspSupport = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideCredSspSupport = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_EnableCredSspSupport; - public bool RemoteDesktop_EnableCredSspSupport + private bool _remoteDesktop_EnableCredSspSupport; + public bool RemoteDesktop_EnableCredSspSupport + { + get => _remoteDesktop_EnableCredSspSupport; + set { - get => _remoteDesktop_EnableCredSspSupport; - set - { - if (value == _remoteDesktop_EnableCredSspSupport) - return; + if (value == _remoteDesktop_EnableCredSspSupport) + return; - _remoteDesktop_EnableCredSspSupport = value; - OnPropertyChanged(); - } + _remoteDesktop_EnableCredSspSupport = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideAuthenticationLevel; - public bool RemoteDesktop_OverrideAuthenticationLevel + private bool _remoteDesktop_OverrideAuthenticationLevel; + public bool RemoteDesktop_OverrideAuthenticationLevel + { + get => _remoteDesktop_OverrideAuthenticationLevel; + set { - get => _remoteDesktop_OverrideAuthenticationLevel; - set - { - if (value == _remoteDesktop_OverrideAuthenticationLevel) - return; + if (value == _remoteDesktop_OverrideAuthenticationLevel) + return; - _remoteDesktop_OverrideAuthenticationLevel = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideAuthenticationLevel = value; + OnPropertyChanged(); } + } - private uint _remoteDesktop_AuthenticationLevel; - public uint RemoteDesktop_AuthenticationLevel + private uint _remoteDesktop_AuthenticationLevel; + public uint RemoteDesktop_AuthenticationLevel + { + get => _remoteDesktop_AuthenticationLevel; + set { - get => _remoteDesktop_AuthenticationLevel; - set - { - if (value == _remoteDesktop_AuthenticationLevel) - return; + if (value == _remoteDesktop_AuthenticationLevel) + return; - _remoteDesktop_AuthenticationLevel = value; - OnPropertyChanged(); - } + _remoteDesktop_AuthenticationLevel = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideAudioRedirectionMode; - public bool RemoteDesktop_OverrideAudioRedirectionMode + private bool _remoteDesktop_OverrideAudioRedirectionMode; + public bool RemoteDesktop_OverrideAudioRedirectionMode + { + get => _remoteDesktop_OverrideAudioRedirectionMode; + set { - get => _remoteDesktop_OverrideAudioRedirectionMode; - set - { - if (value == _remoteDesktop_OverrideAudioRedirectionMode) - return; + if (value == _remoteDesktop_OverrideAudioRedirectionMode) + return; - _remoteDesktop_OverrideAudioRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideAudioRedirectionMode = value; + OnPropertyChanged(); } + } - public IEnumerable RemoteDesktop_AudioRedirectionModes => Enum.GetValues(typeof(AudioRedirectionMode)).Cast(); + public IEnumerable RemoteDesktop_AudioRedirectionModes => Enum.GetValues(typeof(AudioRedirectionMode)).Cast(); - private AudioRedirectionMode _remoteDesktop_AudioRedirectionMode; - public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode + private AudioRedirectionMode _remoteDesktop_AudioRedirectionMode; + public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode + { + get => _remoteDesktop_AudioRedirectionMode; + set { - get => _remoteDesktop_AudioRedirectionMode; - set - { - if (Equals(value, _remoteDesktop_AudioRedirectionMode)) - return; + if (Equals(value, _remoteDesktop_AudioRedirectionMode)) + return; - _remoteDesktop_AudioRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_AudioRedirectionMode = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideAudioCaptureRedirectionMode; - public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode + private bool _remoteDesktop_OverrideAudioCaptureRedirectionMode; + public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode + { + get => _remoteDesktop_OverrideAudioCaptureRedirectionMode; + set { - get => _remoteDesktop_OverrideAudioCaptureRedirectionMode; - set - { - if (value == _remoteDesktop_OverrideAudioCaptureRedirectionMode) - return; + if (value == _remoteDesktop_OverrideAudioCaptureRedirectionMode) + return; - _remoteDesktop_OverrideAudioCaptureRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideAudioCaptureRedirectionMode = value; + OnPropertyChanged(); } + } - public IEnumerable RemoteDesktop_AudioCaptureRedirectionModes => Enum.GetValues(typeof(AudioCaptureRedirectionMode)).Cast(); + public IEnumerable RemoteDesktop_AudioCaptureRedirectionModes => Enum.GetValues(typeof(AudioCaptureRedirectionMode)).Cast(); - private AudioCaptureRedirectionMode _remoteDesktop_AudioCaptureRedirectionMode; - public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode + private AudioCaptureRedirectionMode _remoteDesktop_AudioCaptureRedirectionMode; + public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode + { + get => _remoteDesktop_AudioCaptureRedirectionMode; + set { - get => _remoteDesktop_AudioCaptureRedirectionMode; - set - { - if (Equals(value, _remoteDesktop_AudioCaptureRedirectionMode)) - return; + if (Equals(value, _remoteDesktop_AudioCaptureRedirectionMode)) + return; - _remoteDesktop_AudioCaptureRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_AudioCaptureRedirectionMode = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideApplyWindowsKeyCombinations; - public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations + private bool _remoteDesktop_OverrideApplyWindowsKeyCombinations; + public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations + { + get => _remoteDesktop_OverrideApplyWindowsKeyCombinations; + set { - get => _remoteDesktop_OverrideApplyWindowsKeyCombinations; - set - { - if (value == _remoteDesktop_OverrideApplyWindowsKeyCombinations) - return; + if (value == _remoteDesktop_OverrideApplyWindowsKeyCombinations) + return; - _remoteDesktop_OverrideApplyWindowsKeyCombinations = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideApplyWindowsKeyCombinations = value; + OnPropertyChanged(); } + } - public IEnumerable RemoteDesktop_KeyboardHookModes => System.Enum.GetValues(typeof(KeyboardHookMode)).Cast(); + public IEnumerable RemoteDesktop_KeyboardHookModes => System.Enum.GetValues(typeof(KeyboardHookMode)).Cast(); - private KeyboardHookMode _remoteDesktop_KeyboardHookMode; - public KeyboardHookMode RemoteDesktop_KeyboardHookMode + private KeyboardHookMode _remoteDesktop_KeyboardHookMode; + public KeyboardHookMode RemoteDesktop_KeyboardHookMode + { + get => _remoteDesktop_KeyboardHookMode; + set { - get => _remoteDesktop_KeyboardHookMode; - set - { - if (Equals(value, _remoteDesktop_KeyboardHookMode)) - return; + if (Equals(value, _remoteDesktop_KeyboardHookMode)) + return; - _remoteDesktop_KeyboardHookMode = value; - OnPropertyChanged(); - } + _remoteDesktop_KeyboardHookMode = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectClipboard; - public bool RemoteDesktop_OverrideRedirectClipboard + private bool _remoteDesktop_OverrideRedirectClipboard; + public bool RemoteDesktop_OverrideRedirectClipboard + { + get => _remoteDesktop_OverrideRedirectClipboard; + set { - get => _remoteDesktop_OverrideRedirectClipboard; - set - { - if (value == _remoteDesktop_OverrideRedirectClipboard) - return; + if (value == _remoteDesktop_OverrideRedirectClipboard) + return; - _remoteDesktop_OverrideRedirectClipboard = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectClipboard = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectClipboard; - public bool RemoteDesktop_RedirectClipboard + private bool _remoteDesktop_RedirectClipboard; + public bool RemoteDesktop_RedirectClipboard + { + get => _remoteDesktop_RedirectClipboard; + set { - get => _remoteDesktop_RedirectClipboard; - set - { - if (value == _remoteDesktop_RedirectClipboard) - return; + if (value == _remoteDesktop_RedirectClipboard) + return; - _remoteDesktop_RedirectClipboard = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectClipboard = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectDevices; - public bool RemoteDesktop_OverrideRedirectDevices + private bool _remoteDesktop_OverrideRedirectDevices; + public bool RemoteDesktop_OverrideRedirectDevices + { + get => _remoteDesktop_OverrideRedirectDevices; + set { - get => _remoteDesktop_OverrideRedirectDevices; - set - { - if (value == _remoteDesktop_OverrideRedirectDevices) - return; + if (value == _remoteDesktop_OverrideRedirectDevices) + return; - _remoteDesktop_OverrideRedirectDevices = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectDevices = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectDevices; - public bool RemoteDesktop_RedirectDevices + private bool _remoteDesktop_RedirectDevices; + public bool RemoteDesktop_RedirectDevices + { + get => _remoteDesktop_RedirectDevices; + set { - get => _remoteDesktop_RedirectDevices; - set - { - if (value == _remoteDesktop_RedirectDevices) - return; + if (value == _remoteDesktop_RedirectDevices) + return; - _remoteDesktop_RedirectDevices = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectDevices = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectDrives; - public bool RemoteDesktop_OverrideRedirectDrives + private bool _remoteDesktop_OverrideRedirectDrives; + public bool RemoteDesktop_OverrideRedirectDrives + { + get => _remoteDesktop_OverrideRedirectDrives; + set { - get => _remoteDesktop_OverrideRedirectDrives; - set - { - if (value == _remoteDesktop_OverrideRedirectDrives) - return; + if (value == _remoteDesktop_OverrideRedirectDrives) + return; - _remoteDesktop_OverrideRedirectDrives = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectDrives = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectDrives; - public bool RemoteDesktop_RedirectDrives + private bool _remoteDesktop_RedirectDrives; + public bool RemoteDesktop_RedirectDrives + { + get => _remoteDesktop_RedirectDrives; + set { - get => _remoteDesktop_RedirectDrives; - set - { - if (value == _remoteDesktop_RedirectDrives) - return; + if (value == _remoteDesktop_RedirectDrives) + return; - _remoteDesktop_RedirectDrives = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectDrives = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectPorts; - public bool RemoteDesktop_OverrideRedirectPorts + private bool _remoteDesktop_OverrideRedirectPorts; + public bool RemoteDesktop_OverrideRedirectPorts + { + get => _remoteDesktop_OverrideRedirectPorts; + set { - get => _remoteDesktop_OverrideRedirectPorts; - set - { - if (value == _remoteDesktop_OverrideRedirectPorts) - return; + if (value == _remoteDesktop_OverrideRedirectPorts) + return; - _remoteDesktop_OverrideRedirectPorts = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectPorts = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectPorts; - public bool RemoteDesktop_RedirectPorts + private bool _remoteDesktop_RedirectPorts; + public bool RemoteDesktop_RedirectPorts + { + get => _remoteDesktop_RedirectPorts; + set { - get => _remoteDesktop_RedirectPorts; - set - { - if (value == _remoteDesktop_RedirectPorts) - return; + if (value == _remoteDesktop_RedirectPorts) + return; - _remoteDesktop_RedirectPorts = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectPorts = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectSmartcards; - public bool RemoteDesktop_OverrideRedirectSmartcards + private bool _remoteDesktop_OverrideRedirectSmartcards; + public bool RemoteDesktop_OverrideRedirectSmartcards + { + get => _remoteDesktop_OverrideRedirectSmartcards; + set { - get => _remoteDesktop_OverrideRedirectSmartcards; - set - { - if (value == _remoteDesktop_OverrideRedirectSmartcards) - return; + if (value == _remoteDesktop_OverrideRedirectSmartcards) + return; - _remoteDesktop_OverrideRedirectSmartcards = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectSmartcards = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectSmartCards; - public bool RemoteDesktop_RedirectSmartCards + private bool _remoteDesktop_RedirectSmartCards; + public bool RemoteDesktop_RedirectSmartCards + { + get => _remoteDesktop_RedirectSmartCards; + set { - get => _remoteDesktop_RedirectSmartCards; - set - { - if (value == _remoteDesktop_RedirectSmartCards) - return; + if (value == _remoteDesktop_RedirectSmartCards) + return; - _remoteDesktop_RedirectSmartCards = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectSmartCards = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectPrinters; - public bool RemoteDesktop_OverrideRedirectPrinters + private bool _remoteDesktop_OverrideRedirectPrinters; + public bool RemoteDesktop_OverrideRedirectPrinters + { + get => _remoteDesktop_OverrideRedirectPrinters; + set { - get => _remoteDesktop_OverrideRedirectPrinters; - set - { - if (value == _remoteDesktop_OverrideRedirectPrinters) - return; + if (value == _remoteDesktop_OverrideRedirectPrinters) + return; - _remoteDesktop_OverrideRedirectPrinters = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectPrinters = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectPrinters; - public bool RemoteDesktop_RedirectPrinters + private bool _remoteDesktop_RedirectPrinters; + public bool RemoteDesktop_RedirectPrinters + { + get => _remoteDesktop_RedirectPrinters; + set { - get => _remoteDesktop_RedirectPrinters; - set - { - if (value == _remoteDesktop_RedirectPrinters) - return; + if (value == _remoteDesktop_RedirectPrinters) + return; - _remoteDesktop_RedirectPrinters = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectPrinters = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverridePersistentBitmapCaching; - public bool RemoteDesktop_OverridePersistentBitmapCaching + private bool _remoteDesktop_OverridePersistentBitmapCaching; + public bool RemoteDesktop_OverridePersistentBitmapCaching + { + get => _remoteDesktop_OverridePersistentBitmapCaching; + set { - get => _remoteDesktop_OverridePersistentBitmapCaching; - set - { - if (value == _remoteDesktop_OverridePersistentBitmapCaching) - return; + if (value == _remoteDesktop_OverridePersistentBitmapCaching) + return; - _remoteDesktop_OverridePersistentBitmapCaching = value; - OnPropertyChanged(); - } + _remoteDesktop_OverridePersistentBitmapCaching = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_PersistentBitmapCaching; - public bool RemoteDesktop_PersistentBitmapCaching + private bool _remoteDesktop_PersistentBitmapCaching; + public bool RemoteDesktop_PersistentBitmapCaching + { + get => _remoteDesktop_PersistentBitmapCaching; + set { - get => _remoteDesktop_PersistentBitmapCaching; - set - { - if (value == _remoteDesktop_PersistentBitmapCaching) - return; + if (value == _remoteDesktop_PersistentBitmapCaching) + return; - _remoteDesktop_PersistentBitmapCaching = value; - OnPropertyChanged(); - } + _remoteDesktop_PersistentBitmapCaching = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped + private bool _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped + { + get => _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + set { - get => _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - set - { - if (value == _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped) - return; + if (value == _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped) + return; - _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_ReconnectIfTheConnectionIsDropped; - public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped + private bool _remoteDesktop_ReconnectIfTheConnectionIsDropped; + public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped + { + get => _remoteDesktop_ReconnectIfTheConnectionIsDropped; + set { - get => _remoteDesktop_ReconnectIfTheConnectionIsDropped; - set - { - if (value == _remoteDesktop_ReconnectIfTheConnectionIsDropped) - return; + if (value == _remoteDesktop_ReconnectIfTheConnectionIsDropped) + return; - _remoteDesktop_ReconnectIfTheConnectionIsDropped = value; - OnPropertyChanged(); - } + _remoteDesktop_ReconnectIfTheConnectionIsDropped = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideNetworkConnectionType; - public bool RemoteDesktop_OverrideNetworkConnectionType + private bool _remoteDesktop_OverrideNetworkConnectionType; + public bool RemoteDesktop_OverrideNetworkConnectionType + { + get => _remoteDesktop_OverrideNetworkConnectionType; + set { - get => _remoteDesktop_OverrideNetworkConnectionType; - set - { - if (value == _remoteDesktop_OverrideNetworkConnectionType) - return; + if (value == _remoteDesktop_OverrideNetworkConnectionType) + return; - _remoteDesktop_OverrideNetworkConnectionType = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideNetworkConnectionType = value; + OnPropertyChanged(); } + } + + public IEnumerable RemoteDesktop_NetworkConnectionTypes => Enum.GetValues(typeof(NetworkConnectionType)).Cast(); + + private NetworkConnectionType _remoteDesktop_NetworkConnectionType; + public NetworkConnectionType RemoteDesktop_NetworkConnectionType + { + get => _remoteDesktop_NetworkConnectionType; + set + { + if (Equals(value, _remoteDesktop_NetworkConnectionType)) + return; + + if (!_isLoading) + ChangeNetworkConnectionTypeSettings(value); - public IEnumerable RemoteDesktop_NetworkConnectionTypes => Enum.GetValues(typeof(NetworkConnectionType)).Cast(); + _remoteDesktop_NetworkConnectionType = value; + OnPropertyChanged(); + } + } - private NetworkConnectionType _remoteDesktop_NetworkConnectionType; - public NetworkConnectionType RemoteDesktop_NetworkConnectionType + private bool _remoteDesktop_DesktopBackground; + public bool RemoteDesktop_DesktopBackground + { + get => _remoteDesktop_DesktopBackground; + set { - get => _remoteDesktop_NetworkConnectionType; - set - { - if (Equals(value, _remoteDesktop_NetworkConnectionType)) - return; + if (value == _remoteDesktop_DesktopBackground) + return; - if (!_isLoading) - ChangeNetworkConnectionTypeSettings(value); + _remoteDesktop_DesktopBackground = value; + OnPropertyChanged(); + } + } - _remoteDesktop_NetworkConnectionType = value; - OnPropertyChanged(); - } + private bool _remoteDesktop_FontSmoothing; + public bool RemoteDesktop_FontSmoothing + { + get => _remoteDesktop_FontSmoothing; + set + { + if (value == _remoteDesktop_FontSmoothing) + return; + + _remoteDesktop_FontSmoothing = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_DesktopBackground; - public bool RemoteDesktop_DesktopBackground + private bool _remoteDesktop_DesktopComposition; + public bool RemoteDesktop_DesktopComposition + { + get => _remoteDesktop_DesktopComposition; + set { - get => _remoteDesktop_DesktopBackground; - set - { - if (value == _remoteDesktop_DesktopBackground) - return; + if (value == _remoteDesktop_DesktopComposition) + return; - _remoteDesktop_DesktopBackground = value; - OnPropertyChanged(); - } + _remoteDesktop_DesktopComposition = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_FontSmoothing; - public bool RemoteDesktop_FontSmoothing + private bool _remoteDesktop_ShowWindowContentsWhileDragging; + public bool RemoteDesktop_ShowWindowContentsWhileDragging + { + get => _remoteDesktop_ShowWindowContentsWhileDragging; + set { - get => _remoteDesktop_FontSmoothing; - set - { - if (value == _remoteDesktop_FontSmoothing) - return; + if (value == _remoteDesktop_ShowWindowContentsWhileDragging) + return; - _remoteDesktop_FontSmoothing = value; - OnPropertyChanged(); - } + _remoteDesktop_ShowWindowContentsWhileDragging = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_DesktopComposition; - public bool RemoteDesktop_DesktopComposition + private bool _remoteDesktop_MenuAndWindowAnimation; + public bool RemoteDesktop_MenuAndWindowAnimation + { + get => _remoteDesktop_MenuAndWindowAnimation; + set { - get => _remoteDesktop_DesktopComposition; - set - { - if (value == _remoteDesktop_DesktopComposition) - return; + if (value == _remoteDesktop_MenuAndWindowAnimation) + return; - _remoteDesktop_DesktopComposition = value; - OnPropertyChanged(); - } + _remoteDesktop_MenuAndWindowAnimation = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_ShowWindowContentsWhileDragging; - public bool RemoteDesktop_ShowWindowContentsWhileDragging + private bool _remoteDesktop_VisualStyles; + public bool RemoteDesktop_VisualStyles + { + get => _remoteDesktop_VisualStyles; + set { - get => _remoteDesktop_ShowWindowContentsWhileDragging; - set - { - if (value == _remoteDesktop_ShowWindowContentsWhileDragging) - return; + if (value == _remoteDesktop_VisualStyles) + return; - _remoteDesktop_ShowWindowContentsWhileDragging = value; - OnPropertyChanged(); - } + _remoteDesktop_VisualStyles = value; + OnPropertyChanged(); } + } + #endregion - private bool _remoteDesktop_MenuAndWindowAnimation; - public bool RemoteDesktop_MenuAndWindowAnimation + #region PowerShell + private bool _powerShell_OverrideCommand; + public bool PowerShell_OverrideCommand + { + get => _powerShell_OverrideCommand; + set { - get => _remoteDesktop_MenuAndWindowAnimation; - set - { - if (value == _remoteDesktop_MenuAndWindowAnimation) - return; + if (value == _powerShell_OverrideCommand) + return; - _remoteDesktop_MenuAndWindowAnimation = value; - OnPropertyChanged(); - } + _powerShell_OverrideCommand = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_VisualStyles; - public bool RemoteDesktop_VisualStyles + private string _powerShell_Command; + public string PowerShell_Command + { + get => _powerShell_Command; + set { - get => _remoteDesktop_VisualStyles; - set - { - if (value == _remoteDesktop_VisualStyles) - return; + if (value == _powerShell_Command) + return; - _remoteDesktop_VisualStyles = value; - OnPropertyChanged(); - } + _powerShell_Command = value; + OnPropertyChanged(); } - #endregion + } - #region PowerShell - private bool _powerShell_OverrideCommand; - public bool PowerShell_OverrideCommand + private bool _powerShell_OverrideAdditionalCommandLine; + public bool PowerShell_OverrideAdditionalCommandLine + { + get => _powerShell_OverrideAdditionalCommandLine; + set { - get => _powerShell_OverrideCommand; - set - { - if (value == _powerShell_OverrideCommand) - return; + if (value == _powerShell_OverrideAdditionalCommandLine) + return; - _powerShell_OverrideCommand = value; - OnPropertyChanged(); - } + _powerShell_OverrideAdditionalCommandLine = value; + OnPropertyChanged(); } + } - private string _powerShell_Command; - public string PowerShell_Command + private string _powerShell_AdditionalCommandLine; + public string PowerShell_AdditionalCommandLine + { + get => _powerShell_AdditionalCommandLine; + set { - get => _powerShell_Command; - set - { - if (value == _powerShell_Command) - return; + if (value == _powerShell_AdditionalCommandLine) + return; - _powerShell_Command = value; - OnPropertyChanged(); - } + _powerShell_AdditionalCommandLine = value; + OnPropertyChanged(); } + } - private bool _powerShell_OverrideAdditionalCommandLine; - public bool PowerShell_OverrideAdditionalCommandLine + private List _powerShell_ExecutionPolicies = new List(); + public List PowerShell_ExecutionPolicies + { + get => _powerShell_ExecutionPolicies; + set { - get => _powerShell_OverrideAdditionalCommandLine; - set - { - if (value == _powerShell_OverrideAdditionalCommandLine) - return; + if (value == _powerShell_ExecutionPolicies) + return; - _powerShell_OverrideAdditionalCommandLine = value; - OnPropertyChanged(); - } + _powerShell_ExecutionPolicies = value; + OnPropertyChanged(); } + } - private string _powerShell_AdditionalCommandLine; - public string PowerShell_AdditionalCommandLine + private bool _powerShell_OverrideExecutionPolicy; + public bool PowerShell_OverrideExecutionPolicy + { + get => _powerShell_OverrideExecutionPolicy; + set { - get => _powerShell_AdditionalCommandLine; - set - { - if (value == _powerShell_AdditionalCommandLine) - return; + if (value == _powerShell_OverrideExecutionPolicy) + return; - _powerShell_AdditionalCommandLine = value; - OnPropertyChanged(); - } + _powerShell_OverrideExecutionPolicy = value; + OnPropertyChanged(); } + } - private List _powerShell_ExecutionPolicies = new List(); - public List PowerShell_ExecutionPolicies + private PowerShell.ExecutionPolicy _powerShell_ExecutionPolicy; + public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy + { + get => _powerShell_ExecutionPolicy; + set { - get => _powerShell_ExecutionPolicies; - set - { - if (value == _powerShell_ExecutionPolicies) - return; + if (value == _powerShell_ExecutionPolicy) + return; - _powerShell_ExecutionPolicies = value; - OnPropertyChanged(); - } + _powerShell_ExecutionPolicy = value; + OnPropertyChanged(); } + } + #endregion - private bool _powerShell_OverrideExecutionPolicy; - public bool PowerShell_OverrideExecutionPolicy + #region PuTTY + private bool _puTTY_OverrideUsername; + public bool PuTTY_OverrideUsername + { + get => _puTTY_OverrideUsername; + set { - get => _powerShell_OverrideExecutionPolicy; - set - { - if (value == _powerShell_OverrideExecutionPolicy) - return; + if (value == _puTTY_OverrideUsername) + return; - _powerShell_OverrideExecutionPolicy = value; - OnPropertyChanged(); - } + _puTTY_OverrideUsername = value; + OnPropertyChanged(); } + } - private PowerShell.ExecutionPolicy _powerShell_ExecutionPolicy; - public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy + private string _puTTY__Username; + public string PuTTY_Username + { + get => _puTTY__Username; + set { - get => _powerShell_ExecutionPolicy; - set - { - if (value == _powerShell_ExecutionPolicy) - return; + if (value == _puTTY__Username) + return; - _powerShell_ExecutionPolicy = value; - OnPropertyChanged(); - } + _puTTY__Username = value; + OnPropertyChanged(); } - #endregion + } - #region PuTTY - private bool _puTTY_OverrideUsername; - public bool PuTTY_OverrideUsername + private bool _puTTY_OverridePrivateKeyFile; + public bool PuTTY_OverridePrivateKeyFile + { + get => _puTTY_OverridePrivateKeyFile; + set { - get => _puTTY_OverrideUsername; - set - { - if (value == _puTTY_OverrideUsername) - return; + if (value == _puTTY_OverridePrivateKeyFile) + return; - _puTTY_OverrideUsername = value; - OnPropertyChanged(); - } + _puTTY_OverridePrivateKeyFile = value; + OnPropertyChanged(); } + } - private string _puTTY__Username; - public string PuTTY_Username + private string _puTTY__PrivateKeyFile; + public string PuTTY_PrivateKeyFile + { + get => _puTTY__PrivateKeyFile; + set { - get => _puTTY__Username; - set - { - if (value == _puTTY__Username) - return; + if (value == _puTTY__PrivateKeyFile) + return; - _puTTY__Username = value; - OnPropertyChanged(); - } + _puTTY__PrivateKeyFile = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverridePrivateKeyFile; - public bool PuTTY_OverridePrivateKeyFile + private bool _puTTY_OverrideProfile; + public bool PuTTY_OverrideProfile + { + get => _puTTY_OverrideProfile; + set { - get => _puTTY_OverridePrivateKeyFile; - set - { - if (value == _puTTY_OverridePrivateKeyFile) - return; + if (value == _puTTY_OverrideProfile) + return; - _puTTY_OverridePrivateKeyFile = value; - OnPropertyChanged(); - } + _puTTY_OverrideProfile = value; + OnPropertyChanged(); } + } - private string _puTTY__PrivateKeyFile; - public string PuTTY_PrivateKeyFile + private string _puTTY_Profile; + public string PuTTY_Profile + { + get => _puTTY_Profile; + set { - get => _puTTY__PrivateKeyFile; - set - { - if (value == _puTTY__PrivateKeyFile) - return; + if (value == _puTTY_Profile) + return; - _puTTY__PrivateKeyFile = value; - OnPropertyChanged(); - } + _puTTY_Profile = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideProfile; - public bool PuTTY_OverrideProfile + private bool _puTTY_OverrideEnableLog; + public bool PuTTY_OverrideEnableLog + { + get => _puTTY_OverrideEnableLog; + set { - get => _puTTY_OverrideProfile; - set - { - if (value == _puTTY_OverrideProfile) - return; + if (value == _puTTY_OverrideEnableLog) + return; - _puTTY_OverrideProfile = value; - OnPropertyChanged(); - } + _puTTY_OverrideEnableLog = value; + OnPropertyChanged(); } + } - private string _puTTY_Profile; - public string PuTTY_Profile + private bool _puTTY_EnableLog; + public bool PuTTY_EnableLog + { + get => _puTTY_EnableLog; + set { - get => _puTTY_Profile; - set - { - if (value == _puTTY_Profile) - return; + if (value == _puTTY_EnableLog) + return; - _puTTY_Profile = value; - OnPropertyChanged(); - } + _puTTY_EnableLog = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideEnableLog; - public bool PuTTY_OverrideEnableLog + private bool _puTTY_OverrideLogMode; + public bool PuTTY_OverrideLogMode + { + get => _puTTY_OverrideLogMode; + set { - get => _puTTY_OverrideEnableLog; - set - { - if (value == _puTTY_OverrideEnableLog) - return; + if (value == _puTTY_OverrideLogMode) + return; - _puTTY_OverrideEnableLog = value; - OnPropertyChanged(); - } + _puTTY_OverrideLogMode = value; + OnPropertyChanged(); } + } + + public IEnumerable PuTTY_LogModes => Enum.GetValues(typeof(LogMode)).Cast(); - private bool _puTTY_EnableLog; - public bool PuTTY_EnableLog + private LogMode _puTTY_LogMode; + public LogMode PuTTY_LogMode + { + get => _puTTY_LogMode; + set { - get => _puTTY_EnableLog; - set - { - if (value == _puTTY_EnableLog) - return; + if (Equals(value, _puTTY_LogMode)) + return; - _puTTY_EnableLog = value; - OnPropertyChanged(); - } + _puTTY_LogMode = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideLogMode; - public bool PuTTY_OverrideLogMode + private bool _puTTY_OverrideLogPath; + public bool PuTTY_OverrideLogPath + { + get => _puTTY_OverrideLogPath; + set { - get => _puTTY_OverrideLogMode; - set - { - if (value == _puTTY_OverrideLogMode) - return; + if (value == _puTTY_OverrideLogPath) + return; - _puTTY_OverrideLogMode = value; - OnPropertyChanged(); - } + _puTTY_OverrideLogPath = value; + OnPropertyChanged(); } + } + + private string _puTTY_LogPath; + public string PuTTY_LogPath + { + get => _puTTY_LogPath; + set + { + if (value == _puTTY_LogPath) + return; - public IEnumerable PuTTY_LogModes => Enum.GetValues(typeof(LogMode)).Cast(); + _puTTY_LogPath = value; + OnPropertyChanged(); + } + } - private LogMode _puTTY_LogMode; - public LogMode PuTTY_LogMode + private bool _puTTY_OverrideLogFileName; + public bool PuTTY_OverrideLogFileName + { + get => _puTTY_OverrideLogFileName; + set { - get => _puTTY_LogMode; - set - { - if (Equals(value, _puTTY_LogMode)) - return; + if (value == _puTTY_OverrideLogFileName) + return; - _puTTY_LogMode = value; - OnPropertyChanged(); - } + _puTTY_OverrideLogFileName = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideLogPath; - public bool PuTTY_OverrideLogPath + private string _puTTY_LogFileName; + public string PuTTY_LogFileName + { + get => _puTTY_LogFileName; + set { - get => _puTTY_OverrideLogPath; - set - { - if (value == _puTTY_OverrideLogPath) - return; + if (value == _puTTY_LogFileName) + return; - _puTTY_OverrideLogPath = value; - OnPropertyChanged(); - } + _puTTY_LogFileName = value; + OnPropertyChanged(); } + } - private string _puTTY_LogPath; - public string PuTTY_LogPath + private bool _puTTY_OverrideAdditionalCommandLine; + public bool PuTTY_OverrideAdditionalCommandLine + { + get => _puTTY_OverrideAdditionalCommandLine; + set { - get => _puTTY_LogPath; - set - { - if (value == _puTTY_LogPath) - return; + if (value == _puTTY_OverrideAdditionalCommandLine) + return; - _puTTY_LogPath = value; - OnPropertyChanged(); - } + _puTTY_OverrideAdditionalCommandLine = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideLogFileName; - public bool PuTTY_OverrideLogFileName + private string _puTTY_AdditionalCommandLine; + public string PuTTY_AdditionalCommandLine + { + get => _puTTY_AdditionalCommandLine; + set { - get => _puTTY_OverrideLogFileName; - set - { - if (value == _puTTY_OverrideLogFileName) - return; + if (value == _puTTY_AdditionalCommandLine) + return; - _puTTY_OverrideLogFileName = value; - OnPropertyChanged(); - } + _puTTY_AdditionalCommandLine = value; + OnPropertyChanged(); } + } - private string _puTTY_LogFileName; - public string PuTTY_LogFileName + private ConnectionMode _puTTY_ConnectionMode; + public ConnectionMode PuTTY_ConnectionMode + { + get => _puTTY_ConnectionMode; + set { - get => _puTTY_LogFileName; - set - { - if (value == _puTTY_LogFileName) - return; + if (value == _puTTY_ConnectionMode) + return; - _puTTY_LogFileName = value; - OnPropertyChanged(); - } + _puTTY_ConnectionMode = value; } + } + #endregion - private bool _puTTY_OverrideAdditionalCommandLine; - public bool PuTTY_OverrideAdditionalCommandLine + #region AWS Session Manager + private bool _awsSessionManager_OverrideProfile; + public bool AWSSessionManager_OverrideProfile + { + get => _awsSessionManager_OverrideProfile; + set { - get => _puTTY_OverrideAdditionalCommandLine; - set - { - if (value == _puTTY_OverrideAdditionalCommandLine) - return; + if (value == _awsSessionManager_OverrideProfile) + return; - _puTTY_OverrideAdditionalCommandLine = value; - OnPropertyChanged(); - } + _awsSessionManager_OverrideProfile = value; + OnPropertyChanged(); } + } - private string _puTTY_AdditionalCommandLine; - public string PuTTY_AdditionalCommandLine + private string _awsSessionManager_Profile; + public string AWSSessionManager_Profile + { + get => _awsSessionManager_Profile; + set { - get => _puTTY_AdditionalCommandLine; - set - { - if (value == _puTTY_AdditionalCommandLine) - return; + if (value == _awsSessionManager_Profile) + return; - _puTTY_AdditionalCommandLine = value; - OnPropertyChanged(); - } + _awsSessionManager_Profile = value; + OnPropertyChanged(); } + } - private ConnectionMode _puTTY_ConnectionMode; - public ConnectionMode PuTTY_ConnectionMode + private bool _awsSessionManager_OverrideRegion; + public bool AWSSessionManager_OverrideRegion + { + get => _awsSessionManager_OverrideRegion; + set { - get => _puTTY_ConnectionMode; - set - { - if (value == _puTTY_ConnectionMode) - return; + if (value == _awsSessionManager_OverrideRegion) + return; - _puTTY_ConnectionMode = value; - } + _awsSessionManager_OverrideRegion = value; + OnPropertyChanged(); } - #endregion + } - #region AWS Session Manager - private bool _awsSessionManager_OverrideProfile; - public bool AWSSessionManager_OverrideProfile + private string _awsSessionManager_Region; + public string AWSSessionManager_Region + { + get => _awsSessionManager_Region; + set { - get => _awsSessionManager_OverrideProfile; - set - { - if (value == _awsSessionManager_OverrideProfile) - return; + if (value == _awsSessionManager_Region) + return; - _awsSessionManager_OverrideProfile = value; - OnPropertyChanged(); - } + _awsSessionManager_Region = value; + OnPropertyChanged(); } + } + #endregion - private string _awsSessionManager_Profile; - public string AWSSessionManager_Profile + #region TigerVNC + private bool _tigerVNC_OverridePort; + public bool TigerVNC_OverridePort + { + get => _tigerVNC_OverridePort; + set { - get => _awsSessionManager_Profile; - set - { - if (value == _awsSessionManager_Profile) - return; + if (value == _tigerVNC_OverridePort) + return; - _awsSessionManager_Profile = value; - OnPropertyChanged(); - } + _tigerVNC_OverridePort = value; + OnPropertyChanged(); } + } - private bool _awsSessionManager_OverrideRegion; - public bool AWSSessionManager_OverrideRegion + private int _tigerVNC_Port; + public int TigerVNC_Port + { + get => _tigerVNC_Port; + set { - get => _awsSessionManager_OverrideRegion; - set - { - if (value == _awsSessionManager_OverrideRegion) - return; - - _awsSessionManager_OverrideRegion = value; - OnPropertyChanged(); - } - } - - private string _awsSessionManager_Region; - public string AWSSessionManager_Region - { - get => _awsSessionManager_Region; - set - { - if (value == _awsSessionManager_Region) - return; - - _awsSessionManager_Region = value; - OnPropertyChanged(); - } - } - #endregion - - #region TigerVNC - private bool _tigerVNC_OverridePort; - public bool TigerVNC_OverridePort - { - get => _tigerVNC_OverridePort; - set - { - if (value == _tigerVNC_OverridePort) - return; - - _tigerVNC_OverridePort = value; - OnPropertyChanged(); - } - } - - private int _tigerVNC_Port; - public int TigerVNC_Port - { - get => _tigerVNC_Port; - set - { - if (value == _tigerVNC_Port) - return; - - _tigerVNC_Port = value; - OnPropertyChanged(); - } - } - #endregion - - public GroupViewModel(Action saveCommand, Action cancelHandler, IReadOnlyCollection groups, GroupEditMode editMode = GroupEditMode.Add, GroupInfo group = null) - { - // Load the view - GroupViews = new CollectionViewSource { Source = GroupViewManager.List }.View; - GroupViews.SortDescriptions.Add(new SortDescription(nameof(GroupViewInfo.Name), ListSortDirection.Ascending)); - - SaveCommand = new RelayCommand(p => saveCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - - var groupInfo = group ?? new GroupInfo(); - - Group = groupInfo; - _groups = groups; - - // General - Name = groupInfo.Name; - - // Remote Desktop - RemoteDesktop_UseCredentials = groupInfo.RemoteDesktop_UseCredentials; - RemoteDesktop_Username = groupInfo.RemoteDesktop_Username; - RemoteDesktop_Password = groupInfo.RemoteDesktop_Password; - RemoteDesktop_OverrideDisplay = groupInfo.RemoteDesktop_OverrideDisplay; - RemoteDesktop_AdjustScreenAutomatically = groupInfo.RemoteDesktop_AdjustScreenAutomatically; - RemoteDesktop_UseCurrentViewSize = groupInfo.RemoteDesktop_UseCurrentViewSize; - RemoteDesktop_UseFixedScreenSize = groupInfo.RemoteDesktop_UseFixedScreenSize; - RemoteDesktop_SelectedScreenResolution = RemoteDesktop_ScreenResolutions.FirstOrDefault(x => x == $"{groupInfo.RemoteDesktop_ScreenWidth}x{groupInfo.RemoteDesktop_ScreenHeight}"); - RemoteDesktop_UseCustomScreenSize = groupInfo.RemoteDesktop_UseCustomScreenSize; - RemoteDesktop_CustomScreenWidth = groupInfo.RemoteDesktop_CustomScreenWidth.ToString(); - RemoteDesktop_CustomScreenHeight = groupInfo.RemoteDesktop_CustomScreenHeight.ToString(); - RemoteDesktop_OverrideColorDepth = groupInfo.RemoteDesktop_OverrideColorDepth; - RemoteDesktop_SelectedColorDepth = RemoteDesktop_ColorDepths.FirstOrDefault(x => x == groupInfo.RemoteDesktop_ColorDepth); - RemoteDesktop_OverridePort = groupInfo.RemoteDesktop_OverridePort; - RemoteDesktop_Port = groupInfo.RemoteDesktop_Port; - RemoteDesktop_OverrideCredSspSupport = groupInfo.RemoteDesktop_OverrideCredSspSupport; - RemoteDesktop_EnableCredSspSupport = groupInfo.RemoteDesktop_EnableCredSspSupport; - RemoteDesktop_OverrideAuthenticationLevel = groupInfo.RemoteDesktop_OverrideAuthenticationLevel; - RemoteDesktop_AuthenticationLevel = groupInfo.RemoteDesktop_AuthenticationLevel; - RemoteDesktop_OverrideAudioRedirectionMode = groupInfo.RemoteDesktop_OverrideAudioRedirectionMode; - RemoteDesktop_AudioRedirectionMode = RemoteDesktop_AudioRedirectionModes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_AudioRedirectionMode); - RemoteDesktop_OverrideAudioCaptureRedirectionMode = groupInfo.RemoteDesktop_OverrideAudioCaptureRedirectionMode; - RemoteDesktop_AudioCaptureRedirectionMode = RemoteDesktop_AudioCaptureRedirectionModes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_AudioCaptureRedirectionMode); - RemoteDesktop_OverrideApplyWindowsKeyCombinations = groupInfo.RemoteDesktop_OverrideApplyWindowsKeyCombinations; - RemoteDesktop_KeyboardHookMode = RemoteDesktop_KeyboardHookModes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_KeyboardHookMode); - RemoteDesktop_OverrideRedirectClipboard = groupInfo.RemoteDesktop_OverrideRedirectClipboard; - RemoteDesktop_RedirectClipboard = groupInfo.RemoteDesktop_RedirectClipboard; - RemoteDesktop_OverrideRedirectDevices = groupInfo.RemoteDesktop_OverrideRedirectDevices; - RemoteDesktop_RedirectDevices = groupInfo.RemoteDesktop_RedirectDevices; - RemoteDesktop_OverrideRedirectDrives = groupInfo.RemoteDesktop_OverrideRedirectDrives; - RemoteDesktop_RedirectDrives = groupInfo.RemoteDesktop_RedirectDrives; - RemoteDesktop_OverrideRedirectPorts = groupInfo.RemoteDesktop_OverrideRedirectPorts; - RemoteDesktop_RedirectPorts = groupInfo.RemoteDesktop_RedirectPorts; - RemoteDesktop_OverrideRedirectSmartcards = groupInfo.RemoteDesktop_OverrideRedirectSmartcards; - RemoteDesktop_RedirectSmartCards = groupInfo.RemoteDesktop_RedirectSmartCards; - RemoteDesktop_OverrideRedirectPrinters = groupInfo.RemoteDesktop_OverrideRedirectPrinters; - RemoteDesktop_RedirectPrinters = groupInfo.RemoteDesktop_RedirectPrinters; - RemoteDesktop_OverridePersistentBitmapCaching = groupInfo.RemoteDesktop_OverridePersistentBitmapCaching; - RemoteDesktop_PersistentBitmapCaching = groupInfo.RemoteDesktop_PersistentBitmapCaching; - RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = groupInfo.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - RemoteDesktop_ReconnectIfTheConnectionIsDropped = groupInfo.RemoteDesktop_ReconnectIfTheConnectionIsDropped; - RemoteDesktop_NetworkConnectionType = RemoteDesktop_NetworkConnectionTypes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_NetworkConnectionType); - RemoteDesktop_DesktopBackground = groupInfo.RemoteDesktop_DesktopBackground; - RemoteDesktop_FontSmoothing = groupInfo.RemoteDesktop_FontSmoothing; - RemoteDesktop_DesktopComposition = groupInfo.RemoteDesktop_DesktopComposition; - RemoteDesktop_ShowWindowContentsWhileDragging = groupInfo.RemoteDesktop_ShowWindowContentsWhileDragging; - RemoteDesktop_MenuAndWindowAnimation = groupInfo.RemoteDesktop_MenuAndWindowAnimation; - RemoteDesktop_VisualStyles = groupInfo.RemoteDesktop_VisualStyles; - - // PowerShell - PowerShell_OverrideCommand = groupInfo.PowerShell_OverrideCommand; - PowerShell_Command = groupInfo.PowerShell_Command; - PowerShell_OverrideAdditionalCommandLine = groupInfo.PowerShell_OverrideAdditionalCommandLine; - PowerShell_AdditionalCommandLine = groupInfo.PowerShell_AdditionalCommandLine; - PowerShell_ExecutionPolicies = Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); - PowerShell_OverrideExecutionPolicy = groupInfo.PowerShell_OverrideExecutionPolicy; - PowerShell_ExecutionPolicy = editMode != GroupEditMode.Add ? groupInfo.PowerShell_ExecutionPolicy : PowerShell_ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); ; - - // PuTTY - PuTTY_OverrideUsername = groupInfo.PuTTY_OverrideUsername; - PuTTY_Username = groupInfo.PuTTY_Username; - PuTTY_OverridePrivateKeyFile = groupInfo.PuTTY_OverridePrivateKeyFile; - PuTTY_PrivateKeyFile = groupInfo.PuTTY_PrivateKeyFile; - PuTTY_OverrideProfile = groupInfo.PuTTY_OverrideProfile; - PuTTY_Profile = groupInfo.PuTTY_Profile; - PuTTY_OverrideEnableLog = groupInfo.PuTTY_OverrideEnableLog; - PuTTY_EnableLog = groupInfo.PuTTY_EnableLog; - PuTTY_OverrideLogMode = groupInfo.PuTTY_OverrideLogMode; - PuTTY_LogMode = PuTTY_LogModes.FirstOrDefault(x => x == groupInfo.PuTTY_LogMode); - PuTTY_OverrideLogPath = groupInfo.PuTTY_OverrideLogPath; - PuTTY_LogPath = groupInfo.PuTTY_LogPath; - PuTTY_OverrideLogFileName = groupInfo.PuTTY_OverrideLogFileName; - PuTTY_LogFileName = groupInfo.PuTTY_LogFileName; - PuTTY_OverrideAdditionalCommandLine = groupInfo.PuTTY_OverrideAdditionalCommandLine; - PuTTY_AdditionalCommandLine = groupInfo.PuTTY_AdditionalCommandLine; - - // AWS Session Manager - AWSSessionManager_OverrideProfile = groupInfo.AWSSessionManager_OverrideProfile; - AWSSessionManager_Profile = groupInfo.AWSSessionManager_Profile; - AWSSessionManager_OverrideRegion = groupInfo.AWSSessionManager_OverrideRegion; - AWSSessionManager_Region = groupInfo.AWSSessionManager_Region; - - - // TigerVNC - TigerVNC_OverridePort = groupInfo.TigerVNC_OverridePort; - TigerVNC_Port = groupInfo.TigerVNC_OverridePort ? groupInfo.TigerVNC_Port : SettingsManager.Current.TigerVNC_Port; - - _isLoading = false; - } - - #region ICommand & Actions - public ICommand SaveCommand { get; } - - public ICommand CancelCommand { get; } - - public ICommand RemoteDesktopPasswordChangedCommand => new RelayCommand(p => RemoteDesktopPasswordChangedAction()); - #endregion - - #region Methods - private void RemoteDesktopPasswordChangedAction() - { - RemoteDesktop_PasswordChanged = true; - } - - private void ChangeNetworkConnectionTypeSettings(NetworkConnectionType connectionSpeed) - { - switch (connectionSpeed) - { - case NetworkConnectionType.Modem: - RemoteDesktop_DesktopBackground = false; - RemoteDesktop_FontSmoothing = false; - RemoteDesktop_DesktopComposition = false; - RemoteDesktop_ShowWindowContentsWhileDragging = false; - RemoteDesktop_MenuAndWindowAnimation = false; - RemoteDesktop_VisualStyles = false; - break; - case NetworkConnectionType.BroadbandLow: - RemoteDesktop_DesktopBackground = false; - RemoteDesktop_FontSmoothing = false; - RemoteDesktop_DesktopComposition = false; - RemoteDesktop_ShowWindowContentsWhileDragging = false; - RemoteDesktop_MenuAndWindowAnimation = false; - RemoteDesktop_VisualStyles = true; - break; - case NetworkConnectionType.Satellite: - case NetworkConnectionType.BroadbandHigh: - RemoteDesktop_DesktopBackground = false; - RemoteDesktop_FontSmoothing = false; - RemoteDesktop_DesktopComposition = true; - RemoteDesktop_ShowWindowContentsWhileDragging = false; - RemoteDesktop_MenuAndWindowAnimation = false; - RemoteDesktop_VisualStyles = true; - break; - case NetworkConnectionType.WAN: - case NetworkConnectionType.LAN: - RemoteDesktop_DesktopBackground = true; - RemoteDesktop_FontSmoothing = true; - RemoteDesktop_DesktopComposition = true; - RemoteDesktop_ShowWindowContentsWhileDragging = true; - RemoteDesktop_MenuAndWindowAnimation = true; - RemoteDesktop_VisualStyles = true; - break; - } - } - #endregion + if (value == _tigerVNC_Port) + return; + + _tigerVNC_Port = value; + OnPropertyChanged(); + } + } + #endregion + + public GroupViewModel(Action saveCommand, Action cancelHandler, IReadOnlyCollection groups, GroupEditMode editMode = GroupEditMode.Add, GroupInfo group = null) + { + // Load the view + GroupViews = new CollectionViewSource { Source = GroupViewManager.List }.View; + GroupViews.SortDescriptions.Add(new SortDescription(nameof(GroupViewInfo.Name), ListSortDirection.Ascending)); + + SaveCommand = new RelayCommand(p => saveCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + + var groupInfo = group ?? new GroupInfo(); + + Group = groupInfo; + _groups = groups; + + // General + Name = groupInfo.Name; + + // Remote Desktop + RemoteDesktop_UseCredentials = groupInfo.RemoteDesktop_UseCredentials; + RemoteDesktop_Username = groupInfo.RemoteDesktop_Username; + RemoteDesktop_Password = groupInfo.RemoteDesktop_Password; + RemoteDesktop_OverrideDisplay = groupInfo.RemoteDesktop_OverrideDisplay; + RemoteDesktop_AdjustScreenAutomatically = groupInfo.RemoteDesktop_AdjustScreenAutomatically; + RemoteDesktop_UseCurrentViewSize = groupInfo.RemoteDesktop_UseCurrentViewSize; + RemoteDesktop_UseFixedScreenSize = groupInfo.RemoteDesktop_UseFixedScreenSize; + RemoteDesktop_SelectedScreenResolution = RemoteDesktop_ScreenResolutions.FirstOrDefault(x => x == $"{groupInfo.RemoteDesktop_ScreenWidth}x{groupInfo.RemoteDesktop_ScreenHeight}"); + RemoteDesktop_UseCustomScreenSize = groupInfo.RemoteDesktop_UseCustomScreenSize; + RemoteDesktop_CustomScreenWidth = groupInfo.RemoteDesktop_CustomScreenWidth.ToString(); + RemoteDesktop_CustomScreenHeight = groupInfo.RemoteDesktop_CustomScreenHeight.ToString(); + RemoteDesktop_OverrideColorDepth = groupInfo.RemoteDesktop_OverrideColorDepth; + RemoteDesktop_SelectedColorDepth = RemoteDesktop_ColorDepths.FirstOrDefault(x => x == groupInfo.RemoteDesktop_ColorDepth); + RemoteDesktop_OverridePort = groupInfo.RemoteDesktop_OverridePort; + RemoteDesktop_Port = groupInfo.RemoteDesktop_Port; + RemoteDesktop_OverrideCredSspSupport = groupInfo.RemoteDesktop_OverrideCredSspSupport; + RemoteDesktop_EnableCredSspSupport = groupInfo.RemoteDesktop_EnableCredSspSupport; + RemoteDesktop_OverrideAuthenticationLevel = groupInfo.RemoteDesktop_OverrideAuthenticationLevel; + RemoteDesktop_AuthenticationLevel = groupInfo.RemoteDesktop_AuthenticationLevel; + RemoteDesktop_OverrideAudioRedirectionMode = groupInfo.RemoteDesktop_OverrideAudioRedirectionMode; + RemoteDesktop_AudioRedirectionMode = RemoteDesktop_AudioRedirectionModes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_AudioRedirectionMode); + RemoteDesktop_OverrideAudioCaptureRedirectionMode = groupInfo.RemoteDesktop_OverrideAudioCaptureRedirectionMode; + RemoteDesktop_AudioCaptureRedirectionMode = RemoteDesktop_AudioCaptureRedirectionModes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_AudioCaptureRedirectionMode); + RemoteDesktop_OverrideApplyWindowsKeyCombinations = groupInfo.RemoteDesktop_OverrideApplyWindowsKeyCombinations; + RemoteDesktop_KeyboardHookMode = RemoteDesktop_KeyboardHookModes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_KeyboardHookMode); + RemoteDesktop_OverrideRedirectClipboard = groupInfo.RemoteDesktop_OverrideRedirectClipboard; + RemoteDesktop_RedirectClipboard = groupInfo.RemoteDesktop_RedirectClipboard; + RemoteDesktop_OverrideRedirectDevices = groupInfo.RemoteDesktop_OverrideRedirectDevices; + RemoteDesktop_RedirectDevices = groupInfo.RemoteDesktop_RedirectDevices; + RemoteDesktop_OverrideRedirectDrives = groupInfo.RemoteDesktop_OverrideRedirectDrives; + RemoteDesktop_RedirectDrives = groupInfo.RemoteDesktop_RedirectDrives; + RemoteDesktop_OverrideRedirectPorts = groupInfo.RemoteDesktop_OverrideRedirectPorts; + RemoteDesktop_RedirectPorts = groupInfo.RemoteDesktop_RedirectPorts; + RemoteDesktop_OverrideRedirectSmartcards = groupInfo.RemoteDesktop_OverrideRedirectSmartcards; + RemoteDesktop_RedirectSmartCards = groupInfo.RemoteDesktop_RedirectSmartCards; + RemoteDesktop_OverrideRedirectPrinters = groupInfo.RemoteDesktop_OverrideRedirectPrinters; + RemoteDesktop_RedirectPrinters = groupInfo.RemoteDesktop_RedirectPrinters; + RemoteDesktop_OverridePersistentBitmapCaching = groupInfo.RemoteDesktop_OverridePersistentBitmapCaching; + RemoteDesktop_PersistentBitmapCaching = groupInfo.RemoteDesktop_PersistentBitmapCaching; + RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = groupInfo.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + RemoteDesktop_ReconnectIfTheConnectionIsDropped = groupInfo.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + RemoteDesktop_NetworkConnectionType = RemoteDesktop_NetworkConnectionTypes.FirstOrDefault(x => x == groupInfo.RemoteDesktop_NetworkConnectionType); + RemoteDesktop_DesktopBackground = groupInfo.RemoteDesktop_DesktopBackground; + RemoteDesktop_FontSmoothing = groupInfo.RemoteDesktop_FontSmoothing; + RemoteDesktop_DesktopComposition = groupInfo.RemoteDesktop_DesktopComposition; + RemoteDesktop_ShowWindowContentsWhileDragging = groupInfo.RemoteDesktop_ShowWindowContentsWhileDragging; + RemoteDesktop_MenuAndWindowAnimation = groupInfo.RemoteDesktop_MenuAndWindowAnimation; + RemoteDesktop_VisualStyles = groupInfo.RemoteDesktop_VisualStyles; + + // PowerShell + PowerShell_OverrideCommand = groupInfo.PowerShell_OverrideCommand; + PowerShell_Command = groupInfo.PowerShell_Command; + PowerShell_OverrideAdditionalCommandLine = groupInfo.PowerShell_OverrideAdditionalCommandLine; + PowerShell_AdditionalCommandLine = groupInfo.PowerShell_AdditionalCommandLine; + PowerShell_ExecutionPolicies = Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); + PowerShell_OverrideExecutionPolicy = groupInfo.PowerShell_OverrideExecutionPolicy; + PowerShell_ExecutionPolicy = editMode != GroupEditMode.Add ? groupInfo.PowerShell_ExecutionPolicy : PowerShell_ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); ; + + // PuTTY + PuTTY_OverrideUsername = groupInfo.PuTTY_OverrideUsername; + PuTTY_Username = groupInfo.PuTTY_Username; + PuTTY_OverridePrivateKeyFile = groupInfo.PuTTY_OverridePrivateKeyFile; + PuTTY_PrivateKeyFile = groupInfo.PuTTY_PrivateKeyFile; + PuTTY_OverrideProfile = groupInfo.PuTTY_OverrideProfile; + PuTTY_Profile = groupInfo.PuTTY_Profile; + PuTTY_OverrideEnableLog = groupInfo.PuTTY_OverrideEnableLog; + PuTTY_EnableLog = groupInfo.PuTTY_EnableLog; + PuTTY_OverrideLogMode = groupInfo.PuTTY_OverrideLogMode; + PuTTY_LogMode = PuTTY_LogModes.FirstOrDefault(x => x == groupInfo.PuTTY_LogMode); + PuTTY_OverrideLogPath = groupInfo.PuTTY_OverrideLogPath; + PuTTY_LogPath = groupInfo.PuTTY_LogPath; + PuTTY_OverrideLogFileName = groupInfo.PuTTY_OverrideLogFileName; + PuTTY_LogFileName = groupInfo.PuTTY_LogFileName; + PuTTY_OverrideAdditionalCommandLine = groupInfo.PuTTY_OverrideAdditionalCommandLine; + PuTTY_AdditionalCommandLine = groupInfo.PuTTY_AdditionalCommandLine; + + // AWS Session Manager + AWSSessionManager_OverrideProfile = groupInfo.AWSSessionManager_OverrideProfile; + AWSSessionManager_Profile = groupInfo.AWSSessionManager_Profile; + AWSSessionManager_OverrideRegion = groupInfo.AWSSessionManager_OverrideRegion; + AWSSessionManager_Region = groupInfo.AWSSessionManager_Region; + + + // TigerVNC + TigerVNC_OverridePort = groupInfo.TigerVNC_OverridePort; + TigerVNC_Port = groupInfo.TigerVNC_OverridePort ? groupInfo.TigerVNC_Port : SettingsManager.Current.TigerVNC_Port; + + _isLoading = false; + } + + #region ICommand & Actions + public ICommand SaveCommand { get; } + + public ICommand CancelCommand { get; } + + public ICommand RemoteDesktopPasswordChangedCommand => new RelayCommand(p => RemoteDesktopPasswordChangedAction()); + #endregion + + #region Methods + private void RemoteDesktopPasswordChangedAction() + { + RemoteDesktop_PasswordChanged = true; + } + + private void ChangeNetworkConnectionTypeSettings(NetworkConnectionType connectionSpeed) + { + switch (connectionSpeed) + { + case NetworkConnectionType.Modem: + RemoteDesktop_DesktopBackground = false; + RemoteDesktop_FontSmoothing = false; + RemoteDesktop_DesktopComposition = false; + RemoteDesktop_ShowWindowContentsWhileDragging = false; + RemoteDesktop_MenuAndWindowAnimation = false; + RemoteDesktop_VisualStyles = false; + break; + case NetworkConnectionType.BroadbandLow: + RemoteDesktop_DesktopBackground = false; + RemoteDesktop_FontSmoothing = false; + RemoteDesktop_DesktopComposition = false; + RemoteDesktop_ShowWindowContentsWhileDragging = false; + RemoteDesktop_MenuAndWindowAnimation = false; + RemoteDesktop_VisualStyles = true; + break; + case NetworkConnectionType.Satellite: + case NetworkConnectionType.BroadbandHigh: + RemoteDesktop_DesktopBackground = false; + RemoteDesktop_FontSmoothing = false; + RemoteDesktop_DesktopComposition = true; + RemoteDesktop_ShowWindowContentsWhileDragging = false; + RemoteDesktop_MenuAndWindowAnimation = false; + RemoteDesktop_VisualStyles = true; + break; + case NetworkConnectionType.WAN: + case NetworkConnectionType.LAN: + RemoteDesktop_DesktopBackground = true; + RemoteDesktop_FontSmoothing = true; + RemoteDesktop_DesktopComposition = true; + RemoteDesktop_ShowWindowContentsWhileDragging = true; + RemoteDesktop_MenuAndWindowAnimation = true; + RemoteDesktop_VisualStyles = true; + break; + } } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/IPAddressAndSubnetmaskViewModel.cs b/Source/NETworkManager/ViewModels/IPAddressAndSubnetmaskViewModel.cs index c4b8f6d268..a704a343a9 100644 --- a/Source/NETworkManager/ViewModels/IPAddressAndSubnetmaskViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPAddressAndSubnetmaskViewModel.cs @@ -2,46 +2,45 @@ using System; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class IPAddressAndSubnetmaskViewModel : ViewModelBase { - public class IPAddressAndSubnetmaskViewModel : ViewModelBase - { - public ICommand OKCommand { get; } + public ICommand OKCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _ipAddress; - public string IPAddress + private string _ipAddress; + public string IPAddress + { + get => _ipAddress; + set { - get => _ipAddress; - set - { - if (value == _ipAddress) - return; - - _ipAddress = value; - OnPropertyChanged(); - } - } + if (value == _ipAddress) + return; - private string _subnetmaskOrCidr; - public string SubnetmaskOrCidr - { - get => _subnetmaskOrCidr; - set - { - if (value == _subnetmaskOrCidr) - return; - - _subnetmaskOrCidr = value; - OnPropertyChanged(); - } + _ipAddress = value; + OnPropertyChanged(); } + } - public IPAddressAndSubnetmaskViewModel(Action okCommand, Action cancelHandler) + private string _subnetmaskOrCidr; + public string SubnetmaskOrCidr + { + get => _subnetmaskOrCidr; + set { - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - } + if (value == _subnetmaskOrCidr) + return; + + _subnetmaskOrCidr = value; + OnPropertyChanged(); + } } + + public IPAddressAndSubnetmaskViewModel(Action okCommand, Action cancelHandler) + { + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/IPAddressViewModel.cs b/Source/NETworkManager/ViewModels/IPAddressViewModel.cs index 6b61a59d18..57d2b0ff5a 100644 --- a/Source/NETworkManager/ViewModels/IPAddressViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPAddressViewModel.cs @@ -2,32 +2,31 @@ using System; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class IPAddressViewModel : ViewModelBase { - public class IPAddressViewModel : ViewModelBase - { - public ICommand OKCommand { get; } + public ICommand OKCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _ipAddress; - public string IPAddress + private string _ipAddress; + public string IPAddress + { + get => _ipAddress; + set { - get => _ipAddress; - set - { - if (value == _ipAddress) - return; + if (value == _ipAddress) + return; - _ipAddress = value; - OnPropertyChanged(); - } + _ipAddress = value; + OnPropertyChanged(); } - - public IPAddressViewModel(Action okCommand, Action cancelHandler) - { - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - } } + + public IPAddressViewModel(Action okCommand, Action cancelHandler) + { + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs b/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs index 3b68d02828..8046968905 100644 --- a/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPScannerHostViewModel.cs @@ -16,370 +16,369 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class IPScannerHostViewModel : ViewModelBase, IProfileManager { - public class IPScannerHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } - - private readonly bool _isLoading = true; - private bool _isViewActive = true; + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } + + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private int _tabId; + private int _tabId; - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } - - private bool _isSearching; - public bool IsSearching + } + + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.IPScanner_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.IPScanner_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.IPScanner_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.IPScanner_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public IPScannerHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public IPScannerHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - InterTabClient = new DragablzInterTabClient(ApplicationName.IPScanner); + InterTabClient = new DragablzInterTabClient(ApplicationName.IPScanner); - TabItems = new ObservableCollection - { - new DragablzTabItem(Localization.Resources.Strings.NewTab, new IPScannerView(_tabId), _tabId) - }; - - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + TabItems = new ObservableCollection + { + new DragablzTabItem(Localization.Resources.Strings.NewTab, new IPScannerView(_tabId), _tabId) + }; + + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.IPScanner_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.IPScanner_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.IPScanner_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.IPScanner_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, IPScanner_IPRange - return info.IPScanner_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.IPScanner_HostOrIPRange.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, IPScanner_IPRange + return info.IPScanner_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.IPScanner_HostOrIPRange.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.IPScanner_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.IPScanner_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.IPScanner_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.IPScanner_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.IPScanner_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.IPScanner_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.IPScanner_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.IPScanner_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); + #region ICommand & Actions + public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); - private void AddTabAction() - { - AddTab(); - } + private void AddTabAction() + { + AddTab(); + } - public ICommand ScanProfileCommand => new RelayCommand(p => ScanProfileAction(), ScanProfile_CanExecute); + public ICommand ScanProfileCommand => new RelayCommand(p => ScanProfileAction(), ScanProfile_CanExecute); - private bool ScanProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool ScanProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ScanProfileAction() - { - AddTab(SelectedProfile); - } + private void ScanProfileAction() + { + AddTab(SelectedProfile); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.IPScanner); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.IPScanner); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ItemActionCallback CloseItemCommand => CloseItemAction; + public ItemActionCallback CloseItemCommand => CloseItemAction; - private static void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as IPScannerView)?.CloseTab(); - } - #endregion + private static void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as IPScannerView)?.CloseTab(); + } + #endregion - #region Methods - private void StartDelayedSearch() + #region Methods + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); + + RefreshProfiles(); - IsSearching = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; + + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; } - - private void ResizeProfile(bool dueToChangedSize) + else { - _canProfileWidthChange = false; - - if (dueToChangedSize) + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void AddTab(string hostOrIPRange = null) - { - _tabId++; + _canProfileWidthChange = true; + } - TabItems.Add(new DragablzTabItem(Localization.Resources.Strings.NewTab, new IPScannerView(_tabId, hostOrIPRange), _tabId)); + public void AddTab(string hostOrIPRange = null) + { + _tabId++; - SelectedTabIndex = TabItems.Count - 1; - } + TabItems.Add(new DragablzTabItem(Localization.Resources.Strings.NewTab, new IPScannerView(_tabId, hostOrIPRange), _tabId)); - public void AddTab(ProfileInfo profile) - { - AddTab(profile.IPScanner_HostOrIPRange); - } + SelectedTabIndex = TabItems.Count - 1; + } - public void OnViewVisible() - { - _isViewActive = true; + public void AddTab(ProfileInfo profile) + { + AddTab(profile.IPScanner_HostOrIPRange); + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } - - public void RefreshProfiles() - { - if (!_isViewActive) - return; + RefreshProfiles(); + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } - - public void OnProfileDialogOpen() + public void OnViewHide() + { + _isViewActive = false; + } + + public void RefreshProfiles() + { + if (!_isViewActive) + return; + + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Profiles.Refresh(); + })); + } + + public void OnProfileDialogOpen() + { - } + } - public void OnProfileDialogClose() - { + public void OnProfileDialogClose() + { - } + } - #endregion + #endregion - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/IPScannerSettingsViewModel.cs b/Source/NETworkManager/ViewModels/IPScannerSettingsViewModel.cs index f3b0230f99..56f2b007d3 100644 --- a/Source/NETworkManager/ViewModels/IPScannerSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPScannerSettingsViewModel.cs @@ -6,296 +6,295 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class IPScannerSettingsViewModel : ViewModelBase { - public class IPScannerSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - private bool _showScanResultForAllIPAddresses; - public bool ShowScanResultForAllIPAddresses + private bool _showScanResultForAllIPAddresses; + public bool ShowScanResultForAllIPAddresses + { + get => _showScanResultForAllIPAddresses; + set { - get => _showScanResultForAllIPAddresses; - set - { - if (value == _showScanResultForAllIPAddresses) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_ShowScanResultForAllIPAddresses = value; - - _showScanResultForAllIPAddresses = value; - OnPropertyChanged(); - } + if (value == _showScanResultForAllIPAddresses) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_ShowScanResultForAllIPAddresses = value; + + _showScanResultForAllIPAddresses = value; + OnPropertyChanged(); } + } - private int _threads; - public int Threads + private int _threads; + public int Threads + { + get => _threads; + set { - get => _threads; - set - { - if (value == _threads) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_Threads = value; - - _threads = value; - OnPropertyChanged(); - } + if (value == _threads) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_Threads = value; + + _threads = value; + OnPropertyChanged(); } + } - private int _icmpTimeout; - public int ICMPTimeout + private int _icmpTimeout; + public int ICMPTimeout + { + get => _icmpTimeout; + set { - get => _icmpTimeout; - set - { - if (value == _icmpTimeout) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_ICMPTimeout = value; - - _icmpTimeout = value; - OnPropertyChanged(); - } + if (value == _icmpTimeout) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_ICMPTimeout = value; + + _icmpTimeout = value; + OnPropertyChanged(); } + } - private int _icmpBuffer; - public int ICMPBuffer + private int _icmpBuffer; + public int ICMPBuffer + { + get => _icmpBuffer; + set { - get => _icmpBuffer; - set - { - if (value == _icmpBuffer) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_ICMPBuffer = value; - - _icmpBuffer = value; - OnPropertyChanged(); - } + if (value == _icmpBuffer) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_ICMPBuffer = value; + + _icmpBuffer = value; + OnPropertyChanged(); } + } - private int _icmpAttempts; - public int ICMPAttempts + private int _icmpAttempts; + public int ICMPAttempts + { + get => _icmpAttempts; + set { - get => _icmpAttempts; - set - { - if (value == _icmpAttempts) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_ICMPAttempts = value; - - _icmpAttempts = value; - OnPropertyChanged(); - } + if (value == _icmpAttempts) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_ICMPAttempts = value; + + _icmpAttempts = value; + OnPropertyChanged(); } + } - private bool _resolveHostname; - public bool ResolveHostname + private bool _resolveHostname; + public bool ResolveHostname + { + get => _resolveHostname; + set { - get => _resolveHostname; - set - { - if (value == _resolveHostname) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_ResolveHostname = value; - - _resolveHostname = value; - OnPropertyChanged(); - } + if (value == _resolveHostname) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_ResolveHostname = value; + + _resolveHostname = value; + OnPropertyChanged(); } - - private bool _dnsShowErrorMessage; - public bool DNSShowErrorMessage + } + + private bool _dnsShowErrorMessage; + public bool DNSShowErrorMessage + { + get => _dnsShowErrorMessage; + set { - get => _dnsShowErrorMessage; - set - { - if (value == _dnsShowErrorMessage) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_DNSShowErrorMessage = value; - - _dnsShowErrorMessage = value; - OnPropertyChanged(); - } + if (value == _dnsShowErrorMessage) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_DNSShowErrorMessage = value; + + _dnsShowErrorMessage = value; + OnPropertyChanged(); } + } - private bool _resolveMACAddress; - public bool ResolveMACAddress + private bool _resolveMACAddress; + public bool ResolveMACAddress + { + get => _resolveMACAddress; + set { - get => _resolveMACAddress; - set - { - if (value == _resolveMACAddress) - return; - - if (!_isLoading) - SettingsManager.Current.IPScanner_ResolveMACAddress = value; - - _resolveMACAddress = value; - OnPropertyChanged(); - } + if (value == _resolveMACAddress) + return; + + if (!_isLoading) + SettingsManager.Current.IPScanner_ResolveMACAddress = value; + + _resolveMACAddress = value; + OnPropertyChanged(); } + } - public ICollectionView CustomCommands { get; } + public ICollectionView CustomCommands { get; } - private CustomCommandInfo _selectedCustomCommand = new(); - public CustomCommandInfo SelectedCustomCommand + private CustomCommandInfo _selectedCustomCommand = new(); + public CustomCommandInfo SelectedCustomCommand + { + get => _selectedCustomCommand; + set { - get => _selectedCustomCommand; - set - { - if (value == _selectedCustomCommand) - return; - - _selectedCustomCommand = value; - OnPropertyChanged(); - } + if (value == _selectedCustomCommand) + return; + + _selectedCustomCommand = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public IPScannerSettingsViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Constructor, load settings + public IPScannerSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - CustomCommands = CollectionViewSource.GetDefaultView(SettingsManager.Current.IPScanner_CustomCommands); - CustomCommands.SortDescriptions.Add(new SortDescription(nameof(CustomCommandInfo.Name), ListSortDirection.Ascending)); + CustomCommands = CollectionViewSource.GetDefaultView(SettingsManager.Current.IPScanner_CustomCommands); + CustomCommands.SortDescriptions.Add(new SortDescription(nameof(CustomCommandInfo.Name), ListSortDirection.Ascending)); - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } + + private void LoadSettings() + { + ShowScanResultForAllIPAddresses = SettingsManager.Current.IPScanner_ShowScanResultForAllIPAddresses; + Threads = SettingsManager.Current.IPScanner_Threads; + ICMPTimeout = SettingsManager.Current.IPScanner_ICMPTimeout; + ICMPBuffer = SettingsManager.Current.IPScanner_ICMPBuffer; + ICMPAttempts = SettingsManager.Current.IPScanner_ICMPAttempts; + ResolveHostname = SettingsManager.Current.IPScanner_ResolveHostname; + DNSShowErrorMessage = SettingsManager.Current.IPScanner_DNSShowErrorMessage; + ResolveMACAddress = SettingsManager.Current.IPScanner_ResolveMACAddress; + } + #endregion + + #region ICommand & Actions + public ICommand AddCustomCommandCommand => new RelayCommand(p => AddCustomCommandAction()); + + private void AddCustomCommandAction() + { + AddCustomCommand(); + } + + public ICommand EditCustomCommandCommand => new RelayCommand(p => EditCustomCommandAction()); - private void LoadSettings() + private void EditCustomCommandAction() + { + EditCustomCommand(); + } + + public ICommand DeleteCustomCommandCommand => new RelayCommand(p => DeleteCustomCommandAction()); + + private void DeleteCustomCommandAction() + { + DeleteCustomCommand(); + } + + #endregion + + #region Methods + public async void AddCustomCommand() + { + var customDialog = new CustomDialog { - ShowScanResultForAllIPAddresses = SettingsManager.Current.IPScanner_ShowScanResultForAllIPAddresses; - Threads = SettingsManager.Current.IPScanner_Threads; - ICMPTimeout = SettingsManager.Current.IPScanner_ICMPTimeout; - ICMPBuffer = SettingsManager.Current.IPScanner_ICMPBuffer; - ICMPAttempts = SettingsManager.Current.IPScanner_ICMPAttempts; - ResolveHostname = SettingsManager.Current.IPScanner_ResolveHostname; - DNSShowErrorMessage = SettingsManager.Current.IPScanner_DNSShowErrorMessage; - ResolveMACAddress = SettingsManager.Current.IPScanner_ResolveMACAddress; - } - #endregion + Title = Localization.Resources.Strings.AddCustomCommand + }; - #region ICommand & Actions - public ICommand AddCustomCommandCommand => new RelayCommand(p => AddCustomCommandAction()); + var customCommandViewModel = new CustomCommandViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - private void AddCustomCommandAction() + SettingsManager.Current.IPScanner_CustomCommands.Add(new CustomCommandInfo(instance.ID, instance.Name, instance.FilePath, instance.Arguments)); + }, instance => { - AddCustomCommand(); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - public ICommand EditCustomCommandCommand => new RelayCommand(p => EditCustomCommandAction()); + customDialog.Content = new CustomCommandDialog + { + DataContext = customCommandViewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - private void EditCustomCommandAction() + public async void EditCustomCommand() + { + var customDialog = new CustomDialog { - EditCustomCommand(); - } + Title = Localization.Resources.Strings.EditCustomCommand + }; - public ICommand DeleteCustomCommandCommand => new RelayCommand(p => DeleteCustomCommandAction()); + var customCommandViewModel = new CustomCommandViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - private void DeleteCustomCommandAction() + SettingsManager.Current.IPScanner_CustomCommands.Remove(SelectedCustomCommand); + SettingsManager.Current.IPScanner_CustomCommands.Add(new CustomCommandInfo(instance.ID, instance.Name, instance.FilePath, instance.Arguments)); + }, instance => { - DeleteCustomCommand(); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, true, SelectedCustomCommand); - #endregion + customDialog.Content = new CustomCommandDialog + { + DataContext = customCommandViewModel + }; - #region Methods - public async void AddCustomCommand() + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + public async void DeleteCustomCommand() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddCustomCommand - }; - - var customCommandViewModel = new CustomCommandViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.IPScanner_CustomCommands.Add(new CustomCommandInfo(instance.ID, instance.Name, instance.FilePath, instance.Arguments)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); - - customDialog.Content = new CustomCommandDialog - { - DataContext = customCommandViewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + Title = Localization.Resources.Strings.DeleteCustomCommand + }; - public async void EditCustomCommand() + var confirmDeleteViewModel = new ConfirmDeleteViewModel(instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.EditCustomCommand - }; - - var customCommandViewModel = new CustomCommandViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.IPScanner_CustomCommands.Remove(SelectedCustomCommand); - SettingsManager.Current.IPScanner_CustomCommands.Add(new CustomCommandInfo(instance.ID, instance.Name, instance.FilePath, instance.Arguments)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, true, SelectedCustomCommand); - - customDialog.Content = new CustomCommandDialog - { - DataContext = customCommandViewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - public async void DeleteCustomCommand() + SettingsManager.Current.IPScanner_CustomCommands.Remove(SelectedCustomCommand); + }, instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.DeleteCustomCommand - }; - - var confirmDeleteViewModel = new ConfirmDeleteViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.IPScanner_CustomCommands.Remove(SelectedCustomCommand); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, Localization.Resources.Strings.DeleteCustomCommandMessage); - - customDialog.Content = new ConfirmDeleteDialog - { - DataContext = confirmDeleteViewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, Localization.Resources.Strings.DeleteCustomCommandMessage); + + customDialog.Content = new ConfirmDeleteDialog + { + DataContext = confirmDeleteViewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); } + #endregion } diff --git a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs index 2676692cda..b83f58fdba 100644 --- a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs @@ -27,662 +27,661 @@ using NETworkManager.Models.EventSystem; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class IPScannerViewModel : ViewModelBase, IProfileManagerMinimal { - public class IPScannerViewModel : ViewModelBase, IProfileManagerMinimal - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private CancellationTokenSource _cancellationTokenSource; + private CancellationTokenSource _cancellationTokenSource; - public readonly int TabId; - private bool _firstLoad = true; + public readonly int TabId; + private bool _firstLoad = true; - private readonly bool _isLoading; + private readonly bool _isLoading; - private string _hosts; - public string Hosts + private string _hosts; + public string Hosts + { + get => _hosts; + set { - get => _hosts; - set - { - if (value == _hosts) - return; + if (value == _hosts) + return; - _hosts = value; - OnPropertyChanged(); - } + _hosts = value; + OnPropertyChanged(); } + } - public ICollectionView HostsHistoryView { get; } + public ICollectionView HostsHistoryView { get; } - private bool _isSubnetDetectionRunning; - public bool IsSubnetDetectionRunning + private bool _isSubnetDetectionRunning; + public bool IsSubnetDetectionRunning + { + get => _isSubnetDetectionRunning; + set { - get => _isSubnetDetectionRunning; - set - { - if (value == _isSubnetDetectionRunning) - return; + if (value == _isSubnetDetectionRunning) + return; - _isSubnetDetectionRunning = value; - OnPropertyChanged(); - } + _isSubnetDetectionRunning = value; + OnPropertyChanged(); } + } - private bool _isScanRunning; - public bool IsScanRunning + private bool _isScanRunning; + public bool IsScanRunning + { + get => _isScanRunning; + set { - get => _isScanRunning; - set - { - if (value == _isScanRunning) - return; + if (value == _isScanRunning) + return; - _isScanRunning = value; - OnPropertyChanged(); - } + _isScanRunning = value; + OnPropertyChanged(); } + } - private bool _cancelScan; - public bool CancelScan + private bool _cancelScan; + public bool CancelScan + { + get => _cancelScan; + set { - get => _cancelScan; - set - { - if (value == _cancelScan) - return; + if (value == _cancelScan) + return; - _cancelScan = value; - OnPropertyChanged(); - } + _cancelScan = value; + OnPropertyChanged(); } + } - private ObservableCollection _results = new(); - public ObservableCollection Results + private ObservableCollection _results = new(); + public ObservableCollection Results + { + get => _results; + set { - get => _results; - set - { - if (value != null && value == _results) - return; + if (value != null && value == _results) + return; - _results = value; - } + _results = value; } + } - public ICollectionView ResultsView { get; } + public ICollectionView ResultsView { get; } - private HostInfo _selectedResult; - public HostInfo SelectedResult + private HostInfo _selectedResult; + public HostInfo SelectedResult + { + get => _selectedResult; + set { - get => _selectedResult; - set - { - if (value == _selectedResult) - return; + if (value == _selectedResult) + return; - _selectedResult = value; - OnPropertyChanged(); - } + _selectedResult = value; + OnPropertyChanged(); } + } - private IList _selectedResults = new ArrayList(); - public IList SelectedResults + private IList _selectedResults = new ArrayList(); + public IList SelectedResults + { + get => _selectedResults; + set { - get => _selectedResults; - set - { - if (Equals(value, _selectedResults)) - return; + if (Equals(value, _selectedResults)) + return; - _selectedResults = value; - OnPropertyChanged(); - } + _selectedResults = value; + OnPropertyChanged(); } + } - public bool ResolveHostname => SettingsManager.Current.IPScanner_ResolveHostname; + public bool ResolveHostname => SettingsManager.Current.IPScanner_ResolveHostname; - public bool ResolveMACAddress => SettingsManager.Current.IPScanner_ResolveMACAddress; + public bool ResolveMACAddress => SettingsManager.Current.IPScanner_ResolveMACAddress; - private int _hostsToScan; - public int HostsToScan + private int _hostsToScan; + public int HostsToScan + { + get => _hostsToScan; + set { - get => _hostsToScan; - set - { - if (value == _hostsToScan) - return; + if (value == _hostsToScan) + return; - _hostsToScan = value; - OnPropertyChanged(); - } + _hostsToScan = value; + OnPropertyChanged(); } + } - private int _hostsScanned; - public int HostsScanned + private int _hostsScanned; + public int HostsScanned + { + get => _hostsScanned; + set { - get => _hostsScanned; - set - { - if (value == _hostsScanned) - return; + if (value == _hostsScanned) + return; - _hostsScanned = value; - OnPropertyChanged(); - } + _hostsScanned = value; + OnPropertyChanged(); } + } - private bool _preparingScan; - public bool PreparingScan + private bool _preparingScan; + public bool PreparingScan + { + get => _preparingScan; + set { - get => _preparingScan; - set - { - if (value == _preparingScan) - return; + if (value == _preparingScan) + return; - _preparingScan = value; - OnPropertyChanged(); - } + _preparingScan = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } + } - public IEnumerable CustomCommands => SettingsManager.Current.IPScanner_CustomCommands; - #endregion + public IEnumerable CustomCommands => SettingsManager.Current.IPScanner_CustomCommands; + #endregion - #region Constructor, load settings, shutdown - public IPScannerViewModel(IDialogCoordinator instance, int tabId, string hostOrIPRange) - { - _isLoading = true; + #region Constructor, load settings, shutdown + public IPScannerViewModel(IDialogCoordinator instance, int tabId, string hostOrIPRange) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - TabId = tabId; - Hosts = hostOrIPRange; + TabId = tabId; + Hosts = hostOrIPRange; - // Host history - HostsHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.IPScanner_HostsHistory); + // Host history + HostsHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.IPScanner_HostsHistory); - // Result view - ResultsView = CollectionViewSource.GetDefaultView(Results); - ResultsView.SortDescriptions.Add(new SortDescription(nameof(HostInfo.PingInfo) + "." + nameof(PingInfo.IPAddressInt32), ListSortDirection.Ascending)); + // Result view + ResultsView = CollectionViewSource.GetDefaultView(Results); + ResultsView.SortDescriptions.Add(new SortDescription(nameof(HostInfo.PingInfo) + "." + nameof(PingInfo.IPAddressInt32), ListSortDirection.Ascending)); - LoadSettings(); + LoadSettings(); - // Detect if settings have changed... - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + // Detect if settings have changed... + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - public void OnLoaded() - { - if (!_firstLoad) - return; + public void OnLoaded() + { + if (!_firstLoad) + return; - if (!string.IsNullOrEmpty(Hosts)) - StartScan(); + if (!string.IsNullOrEmpty(Hosts)) + StartScan(); - _firstLoad = false; - } + _firstLoad = false; + } - private void LoadSettings() - { + private void LoadSettings() + { - } - #endregion + } + #endregion - #region ICommands & Actions + #region ICommands & Actions - public ICommand ScanCommand => new RelayCommand(p => ScanAction(), Scan_CanExecute); + public ICommand ScanCommand => new RelayCommand(p => ScanAction(), Scan_CanExecute); - private bool Scan_CanExecute(object paramter) - { - return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - } + private bool Scan_CanExecute(object paramter) + { + return Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + } - private void ScanAction() - { - Scan(); - } + private void ScanAction() + { + Scan(); + } - public ICommand DetectSubnetCommand => new RelayCommand(p => DetectSubnetAction()); + public ICommand DetectSubnetCommand => new RelayCommand(p => DetectSubnetAction()); - private void DetectSubnetAction() - { - DetectIPRange(); - } + private void DetectSubnetAction() + { + DetectIPRange(); + } - public ICommand RedirectDataToApplicationCommand => new RelayCommand(RedirectDataToApplicationAction); + public ICommand RedirectDataToApplicationCommand => new RelayCommand(RedirectDataToApplicationAction); - private void RedirectDataToApplicationAction(object name) - { - if (name is not string appName) - return; + private void RedirectDataToApplicationAction(object name) + { + if (name is not string appName) + return; - if (!Enum.TryParse(appName, out ApplicationName applicationName)) - return; + if (!Enum.TryParse(appName, out ApplicationName applicationName)) + return; - var host = !string.IsNullOrEmpty(SelectedResult.Hostname) ? SelectedResult.Hostname : SelectedResult.PingInfo.IPAddress.ToString(); + var host = !string.IsNullOrEmpty(SelectedResult.Hostname) ? SelectedResult.Hostname : SelectedResult.PingInfo.IPAddress.ToString(); - EventSystem.RedirectToApplication(applicationName, host); - } + EventSystem.RedirectToApplication(applicationName, host); + } - public ICommand PerformDNSLookupIPAddressCommand => new RelayCommand(p => PerformDNSLookupIPAddressAction()); + public ICommand PerformDNSLookupIPAddressCommand => new RelayCommand(p => PerformDNSLookupIPAddressAction()); - private void PerformDNSLookupIPAddressAction() - { - EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedResult.PingInfo.IPAddress.ToString()); - } + private void PerformDNSLookupIPAddressAction() + { + EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedResult.PingInfo.IPAddress.ToString()); + } - public ICommand PerformDNSLookupHostnameCommand => new RelayCommand(p => PerformDNSLookupHostnameAction()); + public ICommand PerformDNSLookupHostnameCommand => new RelayCommand(p => PerformDNSLookupHostnameAction()); - private void PerformDNSLookupHostnameAction() - { - EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedResult.Hostname); - } + private void PerformDNSLookupHostnameAction() + { + EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedResult.Hostname); + } - public ICommand CustomCommandCommand => new RelayCommand(CustomCommandAction); + public ICommand CustomCommandCommand => new RelayCommand(CustomCommandAction); - private void CustomCommandAction(object guid) - { - CustomCommand(guid); - } + private void CustomCommandAction(object guid) + { + CustomCommand(guid); + } - public ICommand AddProfileSelectedHostCommand => new RelayCommand(p => AddProfileSelectedHostAction()); + public ICommand AddProfileSelectedHostCommand => new RelayCommand(p => AddProfileSelectedHostAction()); - private async void AddProfileSelectedHostAction() + private async void AddProfileSelectedHostAction() + { + ProfileInfo profileInfo = new() { - ProfileInfo profileInfo = new() - { - Name = string.IsNullOrEmpty(SelectedResult.Hostname) ? SelectedResult.PingInfo.IPAddress.ToString() : SelectedResult.Hostname.TrimEnd('.'), - Host = SelectedResult.PingInfo.IPAddress.ToString(), + Name = string.IsNullOrEmpty(SelectedResult.Hostname) ? SelectedResult.PingInfo.IPAddress.ToString() : SelectedResult.Hostname.TrimEnd('.'), + Host = SelectedResult.PingInfo.IPAddress.ToString(), - // Additional data - WakeOnLAN_MACAddress = SelectedResult.MACAddressString - }; + // Additional data + WakeOnLAN_MACAddress = SelectedResult.MACAddressString + }; - await ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, profileInfo); - } + await ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, profileInfo); + } - public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); + public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); - private void CopySelectedIPAddressAction() - { - ClipboardHelper.SetClipboard(SelectedResult.PingInfo.IPAddress.ToString()); - } + private void CopySelectedIPAddressAction() + { + ClipboardHelper.SetClipboard(SelectedResult.PingInfo.IPAddress.ToString()); + } - public ICommand CopySelectedHostnameCommand => new RelayCommand(p => CopySelectedHostnameAction()); + public ICommand CopySelectedHostnameCommand => new RelayCommand(p => CopySelectedHostnameAction()); - private void CopySelectedHostnameAction() - { - ClipboardHelper.SetClipboard(SelectedResult.Hostname); - } + private void CopySelectedHostnameAction() + { + ClipboardHelper.SetClipboard(SelectedResult.Hostname); + } - public ICommand CopySelectedMACAddressCommand => new RelayCommand(p => CopySelectedMACAddressAction()); + public ICommand CopySelectedMACAddressCommand => new RelayCommand(p => CopySelectedMACAddressAction()); - private void CopySelectedMACAddressAction() - { - ClipboardHelper.SetClipboard(MACAddressHelper.GetDefaultFormat(SelectedResult.MACAddress.ToString())); - } + private void CopySelectedMACAddressAction() + { + ClipboardHelper.SetClipboard(MACAddressHelper.GetDefaultFormat(SelectedResult.MACAddress.ToString())); + } - public ICommand CopySelectedVendorCommand => new RelayCommand(p => CopySelectedVendorAction()); + public ICommand CopySelectedVendorCommand => new RelayCommand(p => CopySelectedVendorAction()); - private void CopySelectedVendorAction() - { - ClipboardHelper.SetClipboard(SelectedResult.Vendor); - } + private void CopySelectedVendorAction() + { + ClipboardHelper.SetClipboard(SelectedResult.Vendor); + } - public ICommand CopySelectedBytesCommand => new RelayCommand(p => CopySelectedBytesAction()); + public ICommand CopySelectedBytesCommand => new RelayCommand(p => CopySelectedBytesAction()); - private void CopySelectedBytesAction() - { - ClipboardHelper.SetClipboard(SelectedResult.PingInfo.Bytes.ToString()); - } + private void CopySelectedBytesAction() + { + ClipboardHelper.SetClipboard(SelectedResult.PingInfo.Bytes.ToString()); + } - public ICommand CopySelectedTimeCommand => new RelayCommand(p => CopySelectedTimeAction()); + public ICommand CopySelectedTimeCommand => new RelayCommand(p => CopySelectedTimeAction()); - private void CopySelectedTimeAction() - { - ClipboardHelper.SetClipboard(SelectedResult.PingInfo.Time.ToString()); - } + private void CopySelectedTimeAction() + { + ClipboardHelper.SetClipboard(SelectedResult.PingInfo.Time.ToString()); + } - public ICommand CopySelectedTTLCommand => new RelayCommand(p => CopySelectedTTLAction()); + public ICommand CopySelectedTTLCommand => new RelayCommand(p => CopySelectedTTLAction()); - private void CopySelectedTTLAction() - { - ClipboardHelper.SetClipboard(SelectedResult.PingInfo.TTL.ToString()); - } + private void CopySelectedTTLAction() + { + ClipboardHelper.SetClipboard(SelectedResult.PingInfo.TTL.ToString()); + } - public ICommand CopySelectedStatusCommand => new RelayCommand(p => CopySelectedStatusAction()); + public ICommand CopySelectedStatusCommand => new RelayCommand(p => CopySelectedStatusAction()); - private void CopySelectedStatusAction() + private void CopySelectedStatusAction() + { + ClipboardHelper.SetClipboard(IPStatusTranslator.GetInstance().Translate(SelectedResult.PingInfo.Status)); + } + + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + + private void ExportAction() + { + Export(); + } + #endregion + + #region Methods + private void Scan() + { + if (IsScanRunning) + StopScan(); + else + StartScan(); + } + + private async Task StartScan() + { + IsStatusMessageDisplayed = false; + IsScanRunning = true; + PreparingScan = true; + + Results.Clear(); + + // Change the tab title (not nice, but it works) + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + + if (window != null) { - ClipboardHelper.SetClipboard(IPStatusTranslator.GetInstance().Translate(SelectedResult.PingInfo.Status)); + foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) + { + tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Hosts; + } } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - - private void ExportAction() + _cancellationTokenSource = new CancellationTokenSource(); + + // Resolve hostnames + List ipRanges; + + try { - Export(); + ipRanges = await HostRangeHelper.ResolveHostnamesInIPRangesAsync(Hosts.Replace(" ", "").Split(';'), SettingsManager.Current.Network_ResolveHostnamePreferIPv4, _cancellationTokenSource.Token); } - #endregion - - #region Methods - private void Scan() + catch (OperationCanceledException) { - if (IsScanRunning) - StopScan(); - else - StartScan(); + UserHasCanceled(this, EventArgs.Empty); + return; } - - private async Task StartScan() + catch (AggregateException exceptions) // DNS error (could not resolve hostname...) { - IsStatusMessageDisplayed = false; - IsScanRunning = true; - PreparingScan = true; + DnsResolveFailed(exceptions); + return; + } - Results.Clear(); + // Create ip addresses + IPAddress[] ipAddresses; - // Change the tab title (not nice, but it works) - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + try + { + // Create a list of all ip addresses + ipAddresses = await HostRangeHelper.CreateIPAddressesFromIPRangesAsync(ipRanges.ToArray(), _cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + UserHasCanceled(this, EventArgs.Empty); + return; + } - if (window != null) - { - foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) - { - tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Hosts; - } - } + HostsToScan = ipAddresses.Length; + HostsScanned = 0; - _cancellationTokenSource = new CancellationTokenSource(); + PreparingScan = false; - // Resolve hostnames - List ipRanges; + // Add host(s) to the history + AddHostToHistory(Hosts); - try - { - ipRanges = await HostRangeHelper.ResolveHostnamesInIPRangesAsync(Hosts.Replace(" ", "").Split(';'), SettingsManager.Current.Network_ResolveHostnamePreferIPv4, _cancellationTokenSource.Token); - } - catch (OperationCanceledException) - { - UserHasCanceled(this, EventArgs.Empty); - return; - } - catch (AggregateException exceptions) // DNS error (could not resolve hostname...) - { - DnsResolveFailed(exceptions); - return; - } - - // Create ip addresses - IPAddress[] ipAddresses; - - try - { - // Create a list of all ip addresses - ipAddresses = await HostRangeHelper.CreateIPAddressesFromIPRangesAsync(ipRanges.ToArray(), _cancellationTokenSource.Token); - } - catch (OperationCanceledException) - { - UserHasCanceled(this, EventArgs.Empty); - return; - } + var ipScanner = new IPScanner + { + Threads = SettingsManager.Current.IPScanner_Threads, + ICMPTimeout = SettingsManager.Current.IPScanner_ICMPTimeout, + ICMPBuffer = new byte[SettingsManager.Current.IPScanner_ICMPBuffer], + ICMPAttempts = SettingsManager.Current.IPScanner_ICMPAttempts, + ResolveHostname = SettingsManager.Current.IPScanner_ResolveHostname, + DNSShowErrorMessage = SettingsManager.Current.IPScanner_DNSShowErrorMessage, + ResolveMACAddress = SettingsManager.Current.IPScanner_ResolveMACAddress, + ShowScanResultForAllIPAddresses = SettingsManager.Current.IPScanner_ShowScanResultForAllIPAddresses + }; - HostsToScan = ipAddresses.Length; - HostsScanned = 0; + ipScanner.HostFound += HostFound; + ipScanner.ScanComplete += ScanComplete; + ipScanner.ProgressChanged += ProgressChanged; + ipScanner.UserHasCanceled += UserHasCanceled; - PreparingScan = false; + ipScanner.ScanAsync(ipAddresses, _cancellationTokenSource.Token); + } - // Add host(s) to the history - AddHostToHistory(Hosts); + private void StopScan() + { + CancelScan = true; + _cancellationTokenSource.Cancel(); + } - var ipScanner = new IPScanner - { - Threads = SettingsManager.Current.IPScanner_Threads, - ICMPTimeout = SettingsManager.Current.IPScanner_ICMPTimeout, - ICMPBuffer = new byte[SettingsManager.Current.IPScanner_ICMPBuffer], - ICMPAttempts = SettingsManager.Current.IPScanner_ICMPAttempts, - ResolveHostname = SettingsManager.Current.IPScanner_ResolveHostname, - DNSShowErrorMessage = SettingsManager.Current.IPScanner_DNSShowErrorMessage, - ResolveMACAddress = SettingsManager.Current.IPScanner_ResolveMACAddress, - ShowScanResultForAllIPAddresses = SettingsManager.Current.IPScanner_ShowScanResultForAllIPAddresses - }; - - ipScanner.HostFound += HostFound; - ipScanner.ScanComplete += ScanComplete; - ipScanner.ProgressChanged += ProgressChanged; - ipScanner.UserHasCanceled += UserHasCanceled; - - ipScanner.ScanAsync(ipAddresses, _cancellationTokenSource.Token); - } + private async Task DetectIPRange() + { + IsSubnetDetectionRunning = true; - private void StopScan() - { - CancelScan = true; - _cancellationTokenSource.Cancel(); - } + var localIP = await NetworkInterface.DetectLocalIPAddressBasedOnRoutingAsync(IPAddress.Parse("1.1.1.1")); - private async Task DetectIPRange() + // Could not detect local ip address + if (localIP != null) { - IsSubnetDetectionRunning = true; - - var localIP = await NetworkInterface.DetectLocalIPAddressBasedOnRoutingAsync(IPAddress.Parse("1.1.1.1")); + var subnetmaskDetected = false; - // Could not detect local ip address - if (localIP != null) + // Get subnetmask, based on ip address + foreach (var networkInterface in await NetworkInterface.GetNetworkInterfacesAsync()) { - var subnetmaskDetected = false; - - // Get subnetmask, based on ip address - foreach (var networkInterface in await NetworkInterface.GetNetworkInterfacesAsync()) + if (networkInterface.IPv4Address.Any(x => x.Item1.Equals(localIP))) { - if (networkInterface.IPv4Address.Any(x => x.Item1.Equals(localIP))) - { - subnetmaskDetected = true; + subnetmaskDetected = true; - Hosts = $"{localIP}/{Subnetmask.ConvertSubnetmaskToCidr(networkInterface.IPv4Address.First().Item2)}"; + Hosts = $"{localIP}/{Subnetmask.ConvertSubnetmaskToCidr(networkInterface.IPv4Address.First().Item2)}"; - // Fix: If the user clears the textbox and then clicks again on the button, the textbox remains empty... - OnPropertyChanged(nameof(Hosts)); + // Fix: If the user clears the textbox and then clicks again on the button, the textbox remains empty... + OnPropertyChanged(nameof(Hosts)); - break; - } + break; } - - if (!subnetmaskDetected) - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.CouldNotDetectSubnetmask, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); - } - else - { - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.CouldNotDetectLocalIPAddressMessage, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); } - IsSubnetDetectionRunning = false; + if (!subnetmaskDetected) + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.CouldNotDetectSubnetmask, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); + } + else + { + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.CouldNotDetectLocalIPAddressMessage, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); } - private async Task CustomCommand(object guid) + IsSubnetDetectionRunning = false; + } + + private async Task CustomCommand(object guid) + { + if (guid is Guid id) { - if (guid is Guid id) - { - CustomCommandInfo info = (CustomCommandInfo)CustomCommands.FirstOrDefault(x => x.ID == id).Clone(); + CustomCommandInfo info = (CustomCommandInfo)CustomCommands.FirstOrDefault(x => x.ID == id).Clone(); - if (info == null) - return; // ToDo: Log and error message + if (info == null) + return; // ToDo: Log and error message - // Replace vars - string hostname = !string.IsNullOrEmpty(SelectedResult.Hostname) ? SelectedResult.Hostname.TrimEnd('.') : ""; - string ipAddress = SelectedResult.PingInfo.IPAddress.ToString(); + // Replace vars + string hostname = !string.IsNullOrEmpty(SelectedResult.Hostname) ? SelectedResult.Hostname.TrimEnd('.') : ""; + string ipAddress = SelectedResult.PingInfo.IPAddress.ToString(); - info.FilePath = Regex.Replace(info.FilePath, "\\$\\$hostname\\$\\$", hostname, RegexOptions.IgnoreCase); - info.FilePath = Regex.Replace(info.FilePath, "\\$\\$ipaddress\\$\\$", ipAddress, RegexOptions.IgnoreCase); + info.FilePath = Regex.Replace(info.FilePath, "\\$\\$hostname\\$\\$", hostname, RegexOptions.IgnoreCase); + info.FilePath = Regex.Replace(info.FilePath, "\\$\\$ipaddress\\$\\$", ipAddress, RegexOptions.IgnoreCase); - if (!string.IsNullOrEmpty(info.Arguments)) - { - info.Arguments = Regex.Replace(info.Arguments, "\\$\\$hostname\\$\\$", hostname, RegexOptions.IgnoreCase); - info.Arguments = Regex.Replace(info.Arguments, "\\$\\$ipaddress\\$\\$", ipAddress, RegexOptions.IgnoreCase); - } + if (!string.IsNullOrEmpty(info.Arguments)) + { + info.Arguments = Regex.Replace(info.Arguments, "\\$\\$hostname\\$\\$", hostname, RegexOptions.IgnoreCase); + info.Arguments = Regex.Replace(info.Arguments, "\\$\\$ipaddress\\$\\$", ipAddress, RegexOptions.IgnoreCase); + } - try - { - Utilities.CustomCommand.Run(info); - } - catch (Exception ex) - { - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.ResourceManager.GetString("Error", LocalizationManager.GetInstance().Culture), ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); - } + try + { + Utilities.CustomCommand.Run(info); + } + catch (Exception ex) + { + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.ResourceManager.GetString("Error", LocalizationManager.GetInstance().Culture), ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); } } + } - private void AddHostToHistory(string ipRange) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.IPScanner_HostsHistory.ToList(), ipRange, SettingsManager.Current.General_HistoryListEntries); + private void AddHostToHistory(string ipRange) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.IPScanner_HostsHistory.ToList(), ipRange, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.IPScanner_HostsHistory.Clear(); - OnPropertyChanged(nameof(Hosts)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.IPScanner_HostsHistory.Clear(); + OnPropertyChanged(nameof(Hosts)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.IPScanner_HostsHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.IPScanner_HostsHistory.Add(x)); + } - private async Task Export() + private async Task Export() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + Title = Localization.Resources.Strings.Export + }; + + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - var exportViewModel = new ExportViewModel(async instance => + try { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? Results : new ObservableCollection(SelectedResults.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? Results : new ObservableCollection(SelectedResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + SettingsManager.Current.IPScanner_ExportFileType = instance.FileType; + SettingsManager.Current.IPScanner_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.IPScanner_ExportFileType, SettingsManager.Current.IPScanner_ExportFilePath); - SettingsManager.Current.IPScanner_ExportFileType = instance.FileType; - SettingsManager.Current.IPScanner_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.IPScanner_ExportFileType, SettingsManager.Current.IPScanner_ExportFilePath); + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + public void OnClose() + { + // Stop scan + if (IsScanRunning) + StopScan(); + } - public void OnClose() - { - // Stop scan - if (IsScanRunning) - StopScan(); - } + #endregion - #endregion + #region Events + private void HostFound(object sender, HostFoundArgs e) + { + var ipScannerHostInfo = HostInfo.Parse(e); - #region Events - private void HostFound(object sender, HostFoundArgs e) + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - var ipScannerHostInfo = HostInfo.Parse(e); - - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - //lock (Results) - Results.Add(ipScannerHostInfo); - })); - } + //lock (Results) + Results.Add(ipScannerHostInfo); + })); + } - private void ScanComplete(object sender, EventArgs e) - { - CancelScan = false; - IsScanRunning = false; - } + private void ScanComplete(object sender, EventArgs e) + { + CancelScan = false; + IsScanRunning = false; + } - private void ProgressChanged(object sender, ProgressChangedArgs e) - { - HostsScanned = e.Value; - } + private void ProgressChanged(object sender, ProgressChangedArgs e) + { + HostsScanned = e.Value; + } - private void DnsResolveFailed(AggregateException e) - { - StatusMessage = $"{Localization.Resources.Strings.TheFollowingHostnamesCouldNotBeResolved} {string.Join(", ", e.Flatten().InnerExceptions.Select(x => x.Message))}"; - IsStatusMessageDisplayed = true; + private void DnsResolveFailed(AggregateException e) + { + StatusMessage = $"{Localization.Resources.Strings.TheFollowingHostnamesCouldNotBeResolved} {string.Join(", ", e.Flatten().InnerExceptions.Select(x => x.Message))}"; + IsStatusMessageDisplayed = true; - CancelScan = false; - IsScanRunning = false; - } + CancelScan = false; + IsScanRunning = false; + } - private void UserHasCanceled(object sender, EventArgs e) - { - StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; - IsStatusMessageDisplayed = true; - } + private void UserHasCanceled(object sender, EventArgs e) + { + StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; + IsStatusMessageDisplayed = true; + } - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) { - switch (e.PropertyName) - { - case nameof(SettingsInfo.IPScanner_ResolveMACAddress): - OnPropertyChanged(nameof(ResolveMACAddress)); - break; - case nameof(SettingsInfo.IPScanner_ResolveHostname): - OnPropertyChanged(nameof(ResolveHostname)); - break; - } + case nameof(SettingsInfo.IPScanner_ResolveMACAddress): + OnPropertyChanged(nameof(ResolveMACAddress)); + break; + case nameof(SettingsInfo.IPScanner_ResolveHostname): + OnPropertyChanged(nameof(ResolveHostname)); + break; } + } - public void OnProfileDialogOpen() - { - - } + public void OnProfileDialogOpen() + { + + } - public void OnProfileDialogClose() - { - - } - #endregion + public void OnProfileDialogClose() + { + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ListenersViewModel.cs b/Source/NETworkManager/ViewModels/ListenersViewModel.cs index 5e92b61cba..2b8798b2f6 100644 --- a/Source/NETworkManager/ViewModels/ListenersViewModel.cs +++ b/Source/NETworkManager/ViewModels/ListenersViewModel.cs @@ -16,362 +16,361 @@ using NETworkManager.Views; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ListenersViewModel : ViewModelBase { - public class ListenersViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading; - private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); - private bool _isTimerPaused; + private readonly bool _isLoading; + private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); + private bool _isTimerPaused; - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - ListenerResultsView.Refresh(); + ListenerResultsView.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private ObservableCollection _listenerResults = new ObservableCollection(); - public ObservableCollection ListenerResults + private ObservableCollection _listenerResults = new ObservableCollection(); + public ObservableCollection ListenerResults + { + get => _listenerResults; + set { - get => _listenerResults; - set - { - if (value == _listenerResults) - return; + if (value == _listenerResults) + return; - _listenerResults = value; - OnPropertyChanged(); - } + _listenerResults = value; + OnPropertyChanged(); } + } - public ICollectionView ListenerResultsView { get; } + public ICollectionView ListenerResultsView { get; } - private ListenerInfo _selectedListenerInfo; - public ListenerInfo SelectedListenerInfo + private ListenerInfo _selectedListenerInfo; + public ListenerInfo SelectedListenerInfo + { + get => _selectedListenerInfo; + set { - get => _selectedListenerInfo; - set - { - if (value == _selectedListenerInfo) - return; + if (value == _selectedListenerInfo) + return; - _selectedListenerInfo = value; - OnPropertyChanged(); - } + _selectedListenerInfo = value; + OnPropertyChanged(); } + } - private IList _selectedListenerInfos = new ArrayList(); - public IList SelectedListenerInfos + private IList _selectedListenerInfos = new ArrayList(); + public IList SelectedListenerInfos + { + get => _selectedListenerInfos; + set { - get => _selectedListenerInfos; - set - { - if (Equals(value, _selectedListenerInfos)) - return; + if (Equals(value, _selectedListenerInfos)) + return; - _selectedListenerInfos = value; - OnPropertyChanged(); - } + _selectedListenerInfos = value; + OnPropertyChanged(); } + } - private bool _autoRefresh; - public bool AutoRefresh + private bool _autoRefresh; + public bool AutoRefresh + { + get => _autoRefresh; + set { - get => _autoRefresh; - set - { - if (value == _autoRefresh) - return; - - if (!_isLoading) - SettingsManager.Current.Listeners_AutoRefresh = value; + if (value == _autoRefresh) + return; - _autoRefresh = value; + if (!_isLoading) + SettingsManager.Current.Listeners_AutoRefresh = value; - // Start timer to refresh automatically - if (!_isLoading) - { - if (value) - StartAutoRefreshTimer(); - else - StopAutoRefreshTimer(); - } + _autoRefresh = value; - OnPropertyChanged(); + // Start timer to refresh automatically + if (!_isLoading) + { + if (value) + StartAutoRefreshTimer(); + else + StopAutoRefreshTimer(); } + + OnPropertyChanged(); } + } - public ICollectionView AutoRefreshTimes { get; } + public ICollectionView AutoRefreshTimes { get; } - private AutoRefreshTimeInfo _selectedAutoRefreshTime; - public AutoRefreshTimeInfo SelectedAutoRefreshTime + private AutoRefreshTimeInfo _selectedAutoRefreshTime; + public AutoRefreshTimeInfo SelectedAutoRefreshTime + { + get => _selectedAutoRefreshTime; + set { - get => _selectedAutoRefreshTime; - set - { - if (value == _selectedAutoRefreshTime) - return; + if (value == _selectedAutoRefreshTime) + return; - if (!_isLoading) - SettingsManager.Current.Listeners_AutoRefreshTime = value; + if (!_isLoading) + SettingsManager.Current.Listeners_AutoRefreshTime = value; - _selectedAutoRefreshTime = value; + _selectedAutoRefreshTime = value; - if (AutoRefresh) - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); + if (AutoRefresh) + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isRefreshing; - public bool IsRefreshing + private bool _isRefreshing; + public bool IsRefreshing + { + get => _isRefreshing; + set { - get => _isRefreshing; - set - { - if (value == _isRefreshing) - return; + if (value == _isRefreshing) + return; - _isRefreshing = value; - OnPropertyChanged(); - } + _isRefreshing = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion + + #region Contructor, load settings + public ListenersViewModel(IDialogCoordinator instance) + { + _isLoading = true; - #region Contructor, load settings - public ListenersViewModel(IDialogCoordinator instance) + _dialogCoordinator = instance; + + // Result view + search + ListenerResultsView = CollectionViewSource.GetDefaultView(ListenerResults); + ListenerResultsView.SortDescriptions.Add(new SortDescription(nameof(ListenerInfo.Protocol), ListSortDirection.Ascending)); + ListenerResultsView.SortDescriptions.Add(new SortDescription(nameof(ListenerInfo.IPAddressInt32), ListSortDirection.Ascending)); + ListenerResultsView.Filter = o => { - _isLoading = true; - _dialogCoordinator = instance; + if (!(o is ListenerInfo info)) + return false; - // Result view + search - ListenerResultsView = CollectionViewSource.GetDefaultView(ListenerResults); - ListenerResultsView.SortDescriptions.Add(new SortDescription(nameof(ListenerInfo.Protocol), ListSortDirection.Ascending)); - ListenerResultsView.SortDescriptions.Add(new SortDescription(nameof(ListenerInfo.IPAddressInt32), ListSortDirection.Ascending)); - ListenerResultsView.Filter = o => - { + if (string.IsNullOrEmpty(Search)) + return true; - if (!(o is ListenerInfo info)) - return false; + // Search by IP Address, Port and Protocol + return info.IPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.Port.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.Protocol.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1; + }; - if (string.IsNullOrEmpty(Search)) - return true; + AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); + SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.Listeners_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.Listeners_AutoRefreshTime.TimeUnit)); - // Search by IP Address, Port and Protocol - return info.IPAddress.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.Port.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || info.Protocol.ToString().IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1; - }; + _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; - AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); - SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.Listeners_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.Listeners_AutoRefreshTime.TimeUnit)); + LoadSettings(); - _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; + _isLoading = false; - LoadSettings(); + Run(); + } - _isLoading = false; + private async Task Run() + { + await Refresh(); - Run(); - } + if (AutoRefresh) + StartAutoRefreshTimer(); + } - private async Task Run() - { - await Refresh(); - if (AutoRefresh) - StartAutoRefreshTimer(); - } + private void LoadSettings() + { + AutoRefresh = SettingsManager.Current.Listeners_AutoRefresh; + } + #endregion + #region ICommands & Actions + public ICommand RefreshCommand => new RelayCommand(p => RefreshAction(), Refresh_CanExecute); - private void LoadSettings() - { - AutoRefresh = SettingsManager.Current.Listeners_AutoRefresh; - } - #endregion + private bool Refresh_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - #region ICommands & Actions - public ICommand RefreshCommand => new RelayCommand(p => RefreshAction(), Refresh_CanExecute); + private async Task RefreshAction() + { + IsStatusMessageDisplayed = false; - private bool Refresh_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + await Refresh(); + } - private async Task RefreshAction() - { - IsStatusMessageDisplayed = false; + public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); - await Refresh(); - } + private void CopySelectedProtocolAction() + { + ClipboardHelper.SetClipboard(SelectedListenerInfo.Protocol.ToString()); + } - public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); + public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); - private void CopySelectedProtocolAction() - { - ClipboardHelper.SetClipboard(SelectedListenerInfo.Protocol.ToString()); - } + private void CopySelectedIPAddressAction() + { + ClipboardHelper.SetClipboard(SelectedListenerInfo.IPAddress.ToString()); + } - public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); + public ICommand CopySelectedPortCommand => new RelayCommand(p => CopySelectedPortAction()); - private void CopySelectedIPAddressAction() - { - ClipboardHelper.SetClipboard(SelectedListenerInfo.IPAddress.ToString()); - } + private void CopySelectedPortAction() + { + ClipboardHelper.SetClipboard(SelectedListenerInfo.Port.ToString()); + } - public ICommand CopySelectedPortCommand => new RelayCommand(p => CopySelectedPortAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private void CopySelectedPortAction() + private async Task ExportAction() + { + var customDialog = new CustomDialog { - ClipboardHelper.SetClipboard(SelectedListenerInfo.Port.ToString()); - } - - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + Title = Localization.Resources.Strings.Export + }; - private async Task ExportAction() + var exportViewModel = new ExportViewModel(async instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - var exportViewModel = new ExportViewModel(async instance => + try { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? ListenerResults : new ObservableCollection(SelectedListenerInfos.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? ListenerResults : new ObservableCollection(SelectedListenerInfos.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - SettingsManager.Current.Listeners_ExportFileType = instance.FileType; - SettingsManager.Current.Listeners_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Listeners_ExportFileType, SettingsManager.Current.Listeners_ExportFilePath); + SettingsManager.Current.Listeners_ExportFileType = instance.FileType; + SettingsManager.Current.Listeners_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Listeners_ExportFileType, SettingsManager.Current.Listeners_ExportFilePath); - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - #region Methods - private async Task Refresh() - { - IsRefreshing = true; + #region Methods + private async Task Refresh() + { + IsRefreshing = true; - ListenerResults.Clear(); + ListenerResults.Clear(); - (await Listener.GetAllActiveListenersAsync()).ForEach(x => ListenerResults.Add(x)); + (await Listener.GetAllActiveListenersAsync()).ForEach(x => ListenerResults.Add(x)); - IsRefreshing = false; - } + IsRefreshing = false; + } - private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) - { - _autoRefreshTimer.Interval = timeSpan; - } + private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) + { + _autoRefreshTimer.Interval = timeSpan; + } - private void StartAutoRefreshTimer() - { - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); + private void StartAutoRefreshTimer() + { + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); - _autoRefreshTimer.Start(); - } + _autoRefreshTimer.Start(); + } - private void StopAutoRefreshTimer() - { - _autoRefreshTimer.Stop(); - } + private void StopAutoRefreshTimer() + { + _autoRefreshTimer.Stop(); + } - private void PauseAutoRefreshTimer() - { - if (!_autoRefreshTimer.IsEnabled) - return; + private void PauseAutoRefreshTimer() + { + if (!_autoRefreshTimer.IsEnabled) + return; - _autoRefreshTimer.Stop(); - _isTimerPaused = true; - } + _autoRefreshTimer.Stop(); + _isTimerPaused = true; + } - private void ResumeAutoRefreshTimer() - { - if (!_isTimerPaused) - return; + private void ResumeAutoRefreshTimer() + { + if (!_isTimerPaused) + return; - _autoRefreshTimer.Start(); - _isTimerPaused = false; - } - public void OnViewHide() - { - PauseAutoRefreshTimer(); - } + _autoRefreshTimer.Start(); + _isTimerPaused = false; + } + public void OnViewHide() + { + PauseAutoRefreshTimer(); + } - public void OnViewVisible() - { - ResumeAutoRefreshTimer(); - } - #endregion + public void OnViewVisible() + { + ResumeAutoRefreshTimer(); + } + #endregion - #region Events - private async void AutoRefreshTimer_Tick(object sender, EventArgs e) - { - // Stop timer... - _autoRefreshTimer.Stop(); + #region Events + private async void AutoRefreshTimer_Tick(object sender, EventArgs e) + { + // Stop timer... + _autoRefreshTimer.Stop(); - // Refresh - await Refresh(); + // Refresh + await Refresh(); - // Restart timer... - _autoRefreshTimer.Start(); - } - #endregion + // Restart timer... + _autoRefreshTimer.Start(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/LookupHostViewModel.cs b/Source/NETworkManager/ViewModels/LookupHostViewModel.cs index e9784fb074..0449ec274f 100644 --- a/Source/NETworkManager/ViewModels/LookupHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupHostViewModel.cs @@ -1,22 +1,21 @@ -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class LookupHostViewModel : ViewModelBase { - public class LookupHostViewModel : ViewModelBase - { - private bool _isViewActive = true; + private bool _isViewActive = true; - public LookupHostViewModel() - { + public LookupHostViewModel() + { - } + } - public void OnViewVisible() - { - _isViewActive = true; - } + public void OnViewVisible() + { + _isViewActive = true; + } - public void OnViewHide() - { - _isViewActive = false; - } + public void OnViewHide() + { + _isViewActive = false; } } diff --git a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs index f19e0070d7..909941dc0a 100644 --- a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs @@ -17,239 +17,238 @@ using NETworkManager.Views; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class LookupOUILookupViewModel : ViewModelBase { - public class LookupOUILookupViewModel : ViewModelBase + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + + private string _macOrVendorAddress; + public string MACAddressOrVendor { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - - private string _macOrVendorAddress; - public string MACAddressOrVendor + get => _macOrVendorAddress; + set { - get => _macOrVendorAddress; - set - { - if (value == _macOrVendorAddress) - return; + if (value == _macOrVendorAddress) + return; - _macOrVendorAddress = value; - OnPropertyChanged(); - } + _macOrVendorAddress = value; + OnPropertyChanged(); } + } - private bool _macAddressOrVendorHasError; - public bool MACAddressOrVendorHasError + private bool _macAddressOrVendorHasError; + public bool MACAddressOrVendorHasError + { + get => _macAddressOrVendorHasError; + set { - get => _macAddressOrVendorHasError; - set - { - if (value == _macAddressOrVendorHasError) - return; + if (value == _macAddressOrVendorHasError) + return; - _macAddressOrVendorHasError = value; - OnPropertyChanged(); - } + _macAddressOrVendorHasError = value; + OnPropertyChanged(); } + } - public ICollectionView MACAddressOrVendorHistoryView { get; } + public ICollectionView MACAddressOrVendorHistoryView { get; } - private bool _isLookupRunning; - public bool IsLookupRunning + private bool _isLookupRunning; + public bool IsLookupRunning + { + get => _isLookupRunning; + set { - get => _isLookupRunning; - set - { - if (value == _isLookupRunning) - return; + if (value == _isLookupRunning) + return; - _isLookupRunning = value; - OnPropertyChanged(); - } + _isLookupRunning = value; + OnPropertyChanged(); } + } - private ObservableCollection _ouiLookupResults = new ObservableCollection(); - public ObservableCollection OUILookupResults + private ObservableCollection _ouiLookupResults = new ObservableCollection(); + public ObservableCollection OUILookupResults + { + get => _ouiLookupResults; + set { - get => _ouiLookupResults; - set - { - if (value != null && value == _ouiLookupResults) - return; + if (value != null && value == _ouiLookupResults) + return; - _ouiLookupResults = value; - } + _ouiLookupResults = value; } + } - public ICollectionView OUILookupResultsView { get; } + public ICollectionView OUILookupResultsView { get; } - private OUIInfo _selectedOUILookupResult; - public OUIInfo SelectedOUILookupResult + private OUIInfo _selectedOUILookupResult; + public OUIInfo SelectedOUILookupResult + { + get => _selectedOUILookupResult; + set { - get => _selectedOUILookupResult; - set - { - if (value == _selectedOUILookupResult) - return; + if (value == _selectedOUILookupResult) + return; - _selectedOUILookupResult = value; - OnPropertyChanged(); - } + _selectedOUILookupResult = value; + OnPropertyChanged(); } + } - private IList _selectedOUILookupResults = new ArrayList(); - public IList SelectedOUILookupResults + private IList _selectedOUILookupResults = new ArrayList(); + public IList SelectedOUILookupResults + { + get => _selectedOUILookupResults; + set { - get => _selectedOUILookupResults; - set - { - if (Equals(value, _selectedOUILookupResults)) - return; + if (Equals(value, _selectedOUILookupResults)) + return; - _selectedOUILookupResults = value; - OnPropertyChanged(); - } + _selectedOUILookupResults = value; + OnPropertyChanged(); } + } - private bool _noVendorFound; - public bool NoVendorFound + private bool _noVendorFound; + public bool NoVendorFound + { + get => _noVendorFound; + set { - get => _noVendorFound; - set - { - if (value == _noVendorFound) - return; + if (value == _noVendorFound) + return; - _noVendorFound = value; - OnPropertyChanged(); - } + _noVendorFound = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, Load settings - public LookupOUILookupViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, Load settings + public LookupOUILookupViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - // Set collection view - MACAddressOrVendorHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory); - OUILookupResultsView = CollectionViewSource.GetDefaultView(OUILookupResults); - } - #endregion + // Set collection view + MACAddressOrVendorHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory); + OUILookupResultsView = CollectionViewSource.GetDefaultView(OUILookupResults); + } + #endregion - #region ICommands & Actions - public ICommand OUILookupCommand => new RelayCommand(p => OUILookupAction(), OUILookup_CanExecute); + #region ICommands & Actions + public ICommand OUILookupCommand => new RelayCommand(p => OUILookupAction(), OUILookup_CanExecute); - private bool OUILookup_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && !MACAddressOrVendorHasError; + private bool OUILookup_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && !MACAddressOrVendorHasError; - private async void OUILookupAction() - { - IsLookupRunning = true; + private async void OUILookupAction() + { + IsLookupRunning = true; - OUILookupResults.Clear(); + OUILookupResults.Clear(); - var vendors = new List(); + var vendors = new List(); - foreach (var macAddressOrVendor in MACAddressOrVendor.Split(';')) - { - var macAddressOrVendor1 = macAddressOrVendor.Trim(); + foreach (var macAddressOrVendor in MACAddressOrVendor.Split(';')) + { + var macAddressOrVendor1 = macAddressOrVendor.Trim(); - if (Regex.IsMatch(macAddressOrVendor1, RegexHelper.MACAddressRegex) || Regex.IsMatch(macAddressOrVendor1, RegexHelper.MACAddressFirst3BytesRegex)) - { - foreach (var info in await OUILookup.LookupAsync(macAddressOrVendor1)) - { - OUILookupResults.Add(info); - } - } - else + if (Regex.IsMatch(macAddressOrVendor1, RegexHelper.MACAddressRegex) || Regex.IsMatch(macAddressOrVendor1, RegexHelper.MACAddressFirst3BytesRegex)) + { + foreach (var info in await OUILookup.LookupAsync(macAddressOrVendor1)) { - vendors.Add(macAddressOrVendor1); + OUILookupResults.Add(info); } } - - foreach (var info in await OUILookup.LookupByVendorAsync(vendors)) - { - OUILookupResults.Add(info); - } - - if (OUILookupResults.Count == 0) - { - NoVendorFound = true; - } else { - AddMACAddressOrVendorToHistory(MACAddressOrVendor); - NoVendorFound = false; + vendors.Add(macAddressOrVendor1); } - - IsLookupRunning = false; } - public ICommand CopySelectedMACAddressCommand => new RelayCommand(p => CopySelectedMACAddressAction()); - - private void CopySelectedMACAddressAction() + foreach (var info in await OUILookup.LookupByVendorAsync(vendors)) { - ClipboardHelper.SetClipboard(SelectedOUILookupResult.MACAddress); + OUILookupResults.Add(info); } - public ICommand CopySelectedVendorCommand => new RelayCommand(p => CopySelectedVendorAction()); - - private void CopySelectedVendorAction() + if (OUILookupResults.Count == 0) { - ClipboardHelper.SetClipboard(SelectedOUILookupResult.Vendor); + NoVendorFound = true; + } + else + { + AddMACAddressOrVendorToHistory(MACAddressOrVendor); + NoVendorFound = false; } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + IsLookupRunning = false; + } - private async Task ExportAction() - { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + public ICommand CopySelectedMACAddressCommand => new RelayCommand(p => CopySelectedMACAddressAction()); - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + private void CopySelectedMACAddressAction() + { + ClipboardHelper.SetClipboard(SelectedOUILookupResult.MACAddress); + } - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? OUILookupResults : new ObservableCollection(SelectedOUILookupResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + public ICommand CopySelectedVendorCommand => new RelayCommand(p => CopySelectedVendorAction()); - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + private void CopySelectedVendorAction() + { + ClipboardHelper.SetClipboard(SelectedOUILookupResult.Vendor); + } + + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - SettingsManager.Current.Lookup_OUI_ExportFileType = instance.FileType; - SettingsManager.Current.Lookup_OUI_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Lookup_OUI_ExportFileType, SettingsManager.Current.Lookup_OUI_ExportFilePath); + private async Task ExportAction() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.Export + }; - customDialog.Content = new ExportDialog + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + + try { - DataContext = exportViewModel - }; + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? OUILookupResults : new ObservableCollection(SelectedOUILookupResults.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - #region Methods - private void AddMACAddressOrVendorToHistory(string macAddressOrVendor) + SettingsManager.Current.Lookup_OUI_ExportFileType = instance.FileType; + SettingsManager.Current.Lookup_OUI_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Lookup_OUI_ExportFileType, SettingsManager.Current.Lookup_OUI_ExportFilePath); + + customDialog.Content = new ExportDialog { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory.ToList(), macAddressOrVendor, SettingsManager.Current.General_HistoryListEntries); + DataContext = exportViewModel + }; - // Clear the old items - SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory.Clear(); - OnPropertyChanged(nameof(MACAddressOrVendor)); // Raise property changed again, after the collection has been cleared + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - // Fill with the new items - list.ForEach(x => SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory.Add(x)); - } - #endregion + #region Methods + private void AddMACAddressOrVendorToHistory(string macAddressOrVendor) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory.ToList(), macAddressOrVendor, SettingsManager.Current.General_HistoryListEntries); + + // Clear the old items + SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory.Clear(); + OnPropertyChanged(nameof(MACAddressOrVendor)); // Raise property changed again, after the collection has been cleared + + // Fill with the new items + list.ForEach(x => SettingsManager.Current.Lookup_OUI_MACAddressOrVendorHistory.Add(x)); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs index a594c266c1..e597c15d32 100644 --- a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs @@ -16,183 +16,178 @@ using NETworkManager.Views; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class LookupPortLookupViewModel : ViewModelBase { - public class LookupPortLookupViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private string _portOrService; - public string PortOrService + private string _portOrService; + public string PortOrService + { + get => _portOrService; + set { - get => _portOrService; - set - { - if (value == _portOrService) - return; + if (value == _portOrService) + return; - _portOrService = value; - OnPropertyChanged(); - } + _portOrService = value; + OnPropertyChanged(); } + } - private bool _portOrServiceHasError; - public bool PortOrServiceHasError + private bool _portOrServiceHasError; + public bool PortOrServiceHasError + { + get => _portOrServiceHasError; + set { - get => _portOrServiceHasError; - set - { - if (value == _portOrServiceHasError) - return; - _portOrServiceHasError = value; - OnPropertyChanged(); - } + if (value == _portOrServiceHasError) + return; + _portOrServiceHasError = value; + OnPropertyChanged(); } + } - public ICollectionView PortsOrServicesHistoryView { get; } + public ICollectionView PortsOrServicesHistoryView { get; } - private bool _isLookupRunning; - public bool IsLookupRunning + private bool _isLookupRunning; + public bool IsLookupRunning + { + get => _isLookupRunning; + set { - get => _isLookupRunning; - set - { - if (value == _isLookupRunning) - return; + if (value == _isLookupRunning) + return; - _isLookupRunning = value; - OnPropertyChanged(); - } + _isLookupRunning = value; + OnPropertyChanged(); } + } - private ObservableCollection _portLookupResults = new ObservableCollection(); - public ObservableCollection PortLookupResults + private ObservableCollection _portLookupResults = new ObservableCollection(); + public ObservableCollection PortLookupResults + { + get => _portLookupResults; + set { - get => _portLookupResults; - set - { - if (value != null && value == _portLookupResults) - return; + if (value != null && value == _portLookupResults) + return; - _portLookupResults = value; - } + _portLookupResults = value; } + } - public ICollectionView PortLookupResultsView { get; } + public ICollectionView PortLookupResultsView { get; } - private PortLookupInfo _selectedPortLookupResult; - public PortLookupInfo SelectedPortLookupResult + private PortLookupInfo _selectedPortLookupResult; + public PortLookupInfo SelectedPortLookupResult + { + get => _selectedPortLookupResult; + set { - get => _selectedPortLookupResult; - set - { - if (value == _selectedPortLookupResult) - return; + if (value == _selectedPortLookupResult) + return; - _selectedPortLookupResult = value; - OnPropertyChanged(); - } + _selectedPortLookupResult = value; + OnPropertyChanged(); } + } - private IList _selectedPortLookupResults = new ArrayList(); - public IList SelectedPortLookupResults + private IList _selectedPortLookupResults = new ArrayList(); + public IList SelectedPortLookupResults + { + get => _selectedPortLookupResults; + set { - get => _selectedPortLookupResults; - set - { - if (Equals(value, _selectedPortLookupResults)) - return; + if (Equals(value, _selectedPortLookupResults)) + return; - _selectedPortLookupResults = value; - OnPropertyChanged(); - } + _selectedPortLookupResults = value; + OnPropertyChanged(); } + } - private bool _noPortsFound; - public bool NoPortsFound + private bool _noPortsFound; + public bool NoPortsFound + { + get => _noPortsFound; + set { - get => _noPortsFound; - set - { - if (value == _noPortsFound) - return; + if (value == _noPortsFound) + return; - _noPortsFound = value; - OnPropertyChanged(); - } + _noPortsFound = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, Load settings - public LookupPortLookupViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, Load settings + public LookupPortLookupViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - PortsOrServicesHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Lookup_Port_PortsHistory); - PortLookupResultsView = CollectionViewSource.GetDefaultView(PortLookupResults); - } - #endregion + PortsOrServicesHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Lookup_Port_PortsHistory); + PortLookupResultsView = CollectionViewSource.GetDefaultView(PortLookupResults); + } + #endregion - #region ICommands & Actions - public ICommand PortLookupCommand => new RelayCommand(p => PortLookupAction(), PortLookup_CanExecute); + #region ICommands & Actions + public ICommand PortLookupCommand => new RelayCommand(p => PortLookupAction(), PortLookup_CanExecute); - private bool PortLookup_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && !PortOrServiceHasError; + private bool PortLookup_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen && !PortOrServiceHasError; - private async Task PortLookupAction() - { - IsLookupRunning = true; + private async Task PortLookupAction() + { + IsLookupRunning = true; + + PortLookupResults.Clear(); - PortLookupResults.Clear(); + var portsByService = new List(); - var portsByService = new List(); + foreach (var portOrService in PortOrService.Split(';')) + { + var portOrService1 = portOrService.Trim(); - foreach (var portOrService in PortOrService.Split(';')) + if (portOrService1.Contains("-")) { - var portOrService1 = portOrService.Trim(); + var portRange = portOrService1.Split('-'); - if (portOrService1.Contains("-")) + if (int.TryParse(portRange[0], out var startPort) && int.TryParse(portRange[1], out var endPort)) { - var portRange = portOrService1.Split('-'); - - if (int.TryParse(portRange[0], out var startPort) && int.TryParse(portRange[1], out var endPort)) + if ((startPort > 0) && (startPort < 65536) && (endPort > 0) && (endPort < 65536) && (startPort < endPort)) { - if ((startPort > 0) && (startPort < 65536) && (endPort > 0) && (endPort < 65536) && (startPort < endPort)) + for (var i = startPort; i < endPort + 1; i++) { - for (var i = startPort; i < endPort + 1; i++) + foreach (var info in await PortLookup.LookupAsync(i)) { - foreach (var info in await PortLookup.LookupAsync(i)) - { - PortLookupResults.Add(info); - } + PortLookupResults.Add(info); } } - else - { - portsByService.Add(portOrService1); - } - } else { portsByService.Add(portOrService1); } + } else { - if (int.TryParse(portOrService1, out int port)) + portsByService.Add(portOrService1); + } + } + else + { + if (int.TryParse(portOrService1, out int port)) + { + if (port > 0 && port < 65536) { - if (port > 0 && port < 65536) - { - foreach (var info in await PortLookup.LookupAsync(port)) - { - PortLookupResults.Add(info); - } - } - else + foreach (var info in await PortLookup.LookupAsync(port)) { - portsByService.Add(portOrService1); + PortLookupResults.Add(info); } } else @@ -200,105 +195,109 @@ private async Task PortLookupAction() portsByService.Add(portOrService1); } } + else + { + portsByService.Add(portOrService1); + } } - - foreach (var info in await PortLookup.LookupByServiceAsync(portsByService)) - { - PortLookupResults.Add(info); - } - - if (PortLookupResults.Count == 0) - { - NoPortsFound = true; - } - else - { - AddPortOrServiceToHistory(PortOrService); - NoPortsFound = false; - } - - IsLookupRunning = false; } - public ICommand CopySelectedPortCommand => new RelayCommand(p => CopySelectedPortAction()); - - private void CopySelectedPortAction() + foreach (var info in await PortLookup.LookupByServiceAsync(portsByService)) { - ClipboardHelper.SetClipboard(SelectedPortLookupResult.Number.ToString()); + PortLookupResults.Add(info); } - public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); - - private void CopySelectedProtocolAction() + if (PortLookupResults.Count == 0) { - ClipboardHelper.SetClipboard(SelectedPortLookupResult.Protocol.ToString()); + NoPortsFound = true; } - - public ICommand CopySelectedServiceCommand => new RelayCommand(p => CopySelectedServiceAction()); - - private void CopySelectedServiceAction() + else { - ClipboardHelper.SetClipboard(SelectedPortLookupResult.Service); + AddPortOrServiceToHistory(PortOrService); + NoPortsFound = false; } - public ICommand CopySelectedDescriptionCommand => new RelayCommand(p => CopySelectedDescriptionAction()); + IsLookupRunning = false; + } - private void CopySelectedDescriptionAction() - { - ClipboardHelper.SetClipboard(SelectedPortLookupResult.Description); - } + public ICommand CopySelectedPortCommand => new RelayCommand(p => CopySelectedPortAction()); - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + private void CopySelectedPortAction() + { + ClipboardHelper.SetClipboard(SelectedPortLookupResult.Number.ToString()); + } - private async Task ExportAction() - { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + private void CopySelectedProtocolAction() + { + ClipboardHelper.SetClipboard(SelectedPortLookupResult.Protocol.ToString()); + } - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? PortLookupResults : new ObservableCollection(SelectedPortLookupResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + public ICommand CopySelectedServiceCommand => new RelayCommand(p => CopySelectedServiceAction()); - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + private void CopySelectedServiceAction() + { + ClipboardHelper.SetClipboard(SelectedPortLookupResult.Service); + } + + public ICommand CopySelectedDescriptionCommand => new RelayCommand(p => CopySelectedDescriptionAction()); + + private void CopySelectedDescriptionAction() + { + ClipboardHelper.SetClipboard(SelectedPortLookupResult.Description); + } + + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + + private async Task ExportAction() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.Export + }; - SettingsManager.Current.Lookup_Port_ExportFileType = instance.FileType; - SettingsManager.Current.Lookup_Port_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Lookup_Port_ExportFileType, SettingsManager.Current.Lookup_Port_ExportFilePath); + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - customDialog.Content = new ExportDialog + try { - DataContext = exportViewModel - }; + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? PortLookupResults : new ObservableCollection(SelectedPortLookupResults.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - #region Methods - private void AddPortOrServiceToHistory(string portOrService) + SettingsManager.Current.Lookup_Port_ExportFileType = instance.FileType; + SettingsManager.Current.Lookup_Port_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Lookup_Port_ExportFileType, SettingsManager.Current.Lookup_Port_ExportFilePath); + + customDialog.Content = new ExportDialog { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.Lookup_Port_PortsHistory.ToList(), portOrService, SettingsManager.Current.General_HistoryListEntries); + DataContext = exportViewModel + }; - // Clear the old items - SettingsManager.Current.Lookup_Port_PortsHistory.Clear(); - OnPropertyChanged(nameof(PortOrService)); // Raise property changed again, after the collection has been cleared + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - // Fill with the new items - list.ForEach(x => SettingsManager.Current.Lookup_Port_PortsHistory.Add(x)); - } - #endregion + #region Methods + private void AddPortOrServiceToHistory(string portOrService) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.Lookup_Port_PortsHistory.ToList(), portOrService, SettingsManager.Current.General_HistoryListEntries); + + // Clear the old items + SettingsManager.Current.Lookup_Port_PortsHistory.Clear(); + OnPropertyChanged(nameof(PortOrService)); // Raise property changed again, after the collection has been cleared + + // Fill with the new items + list.ForEach(x => SettingsManager.Current.Lookup_Port_PortsHistory.Add(x)); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/NetworkConnectionViewModel.cs b/Source/NETworkManager/ViewModels/NetworkConnectionViewModel.cs index 78df4940d5..bf6cd58f4a 100644 --- a/Source/NETworkManager/ViewModels/NetworkConnectionViewModel.cs +++ b/Source/NETworkManager/ViewModels/NetworkConnectionViewModel.cs @@ -13,842 +13,841 @@ using System.Threading.Tasks; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class NetworkConnectionViewModel : ViewModelBase { - public class NetworkConnectionViewModel : ViewModelBase + #region Variables + private bool _isChecking; + public bool IsChecking { - #region Variables - private bool _isChecking; - public bool IsChecking + get => _isChecking; + set { - get => _isChecking; - set - { - if (value == _isChecking) - return; + if (value == _isChecking) + return; - _isChecking = value; - OnPropertyChanged(); - } + _isChecking = value; + OnPropertyChanged(); } + } - #region Computer - private bool _isComputerIPv4Checking; + #region Computer + private bool _isComputerIPv4Checking; - public bool IsComputerIPv4Checking + public bool IsComputerIPv4Checking + { + get => _isComputerIPv4Checking; + set { - get => _isComputerIPv4Checking; - set - { - if (value == _isComputerIPv4Checking) - return; + if (value == _isComputerIPv4Checking) + return; - _isComputerIPv4Checking = value; - OnPropertyChanged(); - } + _isComputerIPv4Checking = value; + OnPropertyChanged(); } + } - private string _computerIPv4; - public string ComputerIPv4 + private string _computerIPv4; + public string ComputerIPv4 + { + get => _computerIPv4; + set { - get => _computerIPv4; - set - { - if (value == _computerIPv4) - return; + if (value == _computerIPv4) + return; - _computerIPv4 = value; - OnPropertyChanged(); - } + _computerIPv4 = value; + OnPropertyChanged(); } + } - private ConnectionState _computerIPv4State = ConnectionState.None; - public ConnectionState ComputerIPv4State + private ConnectionState _computerIPv4State = ConnectionState.None; + public ConnectionState ComputerIPv4State + { + get => _computerIPv4State; + set { - get => _computerIPv4State; - set - { - if (value == _computerIPv4State) - return; + if (value == _computerIPv4State) + return; - _computerIPv4State = value; - OnPropertyChanged(); - } + _computerIPv4State = value; + OnPropertyChanged(); } + } - private bool _isComputerIPv6Checking; - public bool IsComputerIPv6Checking + private bool _isComputerIPv6Checking; + public bool IsComputerIPv6Checking + { + get => _isComputerIPv6Checking; + set { - get => _isComputerIPv6Checking; - set - { - if (value == _isComputerIPv6Checking) - return; + if (value == _isComputerIPv6Checking) + return; - _isComputerIPv6Checking = value; - OnPropertyChanged(); - } + _isComputerIPv6Checking = value; + OnPropertyChanged(); } + } - private string _computerIPv6; - public string ComputerIPv6 + private string _computerIPv6; + public string ComputerIPv6 + { + get => _computerIPv6; + set { - get => _computerIPv6; - set - { - if (value == _computerIPv6) - return; + if (value == _computerIPv6) + return; - _computerIPv6 = value; - OnPropertyChanged(); - } + _computerIPv6 = value; + OnPropertyChanged(); } + } - private ConnectionState _computerIPv6State = ConnectionState.None; - public ConnectionState ComputerIPv6State + private ConnectionState _computerIPv6State = ConnectionState.None; + public ConnectionState ComputerIPv6State + { + get => _computerIPv6State; + set { - get => _computerIPv6State; - set - { - if (value == _computerIPv6State) - return; + if (value == _computerIPv6State) + return; - _computerIPv6State = value; - OnPropertyChanged(); - } + _computerIPv6State = value; + OnPropertyChanged(); } + } - private bool _isComputerDNSChecking; - public bool IsComputerDNSChecking + private bool _isComputerDNSChecking; + public bool IsComputerDNSChecking + { + get => _isComputerDNSChecking; + set { - get => _isComputerDNSChecking; - set - { - if (value == _isComputerDNSChecking) - return; + if (value == _isComputerDNSChecking) + return; - _isComputerDNSChecking = value; - OnPropertyChanged(); - } + _isComputerDNSChecking = value; + OnPropertyChanged(); } + } - private string _computerDNS; - public string ComputerDNS + private string _computerDNS; + public string ComputerDNS + { + get => _computerDNS; + set { - get => _computerDNS; - set - { - if (value == _computerDNS) - return; + if (value == _computerDNS) + return; - _computerDNS = value; - OnPropertyChanged(); - } + _computerDNS = value; + OnPropertyChanged(); } + } - private ConnectionState _computerDNSState = ConnectionState.None; - public ConnectionState ComputerDNSState + private ConnectionState _computerDNSState = ConnectionState.None; + public ConnectionState ComputerDNSState + { + get => _computerDNSState; + set { - get => _computerDNSState; - set - { - if (value == _computerDNSState) - return; + if (value == _computerDNSState) + return; - _computerDNSState = value; - OnPropertyChanged(); - } + _computerDNSState = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Router - private bool _isRouterIPv4Checking; - public bool IsRouterIPv4Checking + #region Router + private bool _isRouterIPv4Checking; + public bool IsRouterIPv4Checking + { + get => _isRouterIPv4Checking; + set { - get => _isRouterIPv4Checking; - set - { - if (value == _isRouterIPv4Checking) - return; + if (value == _isRouterIPv4Checking) + return; - _isRouterIPv4Checking = value; - OnPropertyChanged(); - } + _isRouterIPv4Checking = value; + OnPropertyChanged(); } + } - private string _routerIPv4; - public string RouterIPv4 + private string _routerIPv4; + public string RouterIPv4 + { + get => _routerIPv4; + set { - get => _routerIPv4; - set - { - if (value == _routerIPv4) - return; + if (value == _routerIPv4) + return; - _routerIPv4 = value; - OnPropertyChanged(); - } + _routerIPv4 = value; + OnPropertyChanged(); } + } - private ConnectionState _routerIPv4State = ConnectionState.None; - public ConnectionState RouterIPv4State + private ConnectionState _routerIPv4State = ConnectionState.None; + public ConnectionState RouterIPv4State + { + get => _routerIPv4State; + set { - get => _routerIPv4State; - set - { - if (value == _routerIPv4State) - return; + if (value == _routerIPv4State) + return; - _routerIPv4State = value; - OnPropertyChanged(); - } + _routerIPv4State = value; + OnPropertyChanged(); } + } - private bool _isRouterIPv6Checking; - public bool IsRouterIPv6Checking + private bool _isRouterIPv6Checking; + public bool IsRouterIPv6Checking + { + get => _isRouterIPv6Checking; + set { - get => _isRouterIPv6Checking; - set - { - if (value == _isRouterIPv6Checking) - return; + if (value == _isRouterIPv6Checking) + return; - _isRouterIPv6Checking = value; - OnPropertyChanged(); - } + _isRouterIPv6Checking = value; + OnPropertyChanged(); } + } - private string _routerIPv6; - public string RouterIPv6 + private string _routerIPv6; + public string RouterIPv6 + { + get => _routerIPv6; + set { - get => _routerIPv6; - set - { - if (value == _routerIPv6) - return; + if (value == _routerIPv6) + return; - _routerIPv6 = value; - OnPropertyChanged(); - } + _routerIPv6 = value; + OnPropertyChanged(); } + } - private ConnectionState _routerIPv6State = ConnectionState.None; - public ConnectionState RouterIPv6State + private ConnectionState _routerIPv6State = ConnectionState.None; + public ConnectionState RouterIPv6State + { + get => _routerIPv6State; + set { - get => _routerIPv6State; - set - { - if (value == _routerIPv6State) - return; + if (value == _routerIPv6State) + return; - _routerIPv6State = value; - OnPropertyChanged(); - } + _routerIPv6State = value; + OnPropertyChanged(); } + } - private bool _isRouterDNSChecking; - public bool IsRouterDNSChecking + private bool _isRouterDNSChecking; + public bool IsRouterDNSChecking + { + get => _isRouterDNSChecking; + set { - get => _isRouterDNSChecking; - set - { - if (value == _isRouterDNSChecking) - return; + if (value == _isRouterDNSChecking) + return; - _isRouterDNSChecking = value; - OnPropertyChanged(); - } + _isRouterDNSChecking = value; + OnPropertyChanged(); } + } - private string _routerDNS; - public string RouterDNS + private string _routerDNS; + public string RouterDNS + { + get => _routerDNS; + set { - get => _routerDNS; - set - { - if (value == _routerDNS) - return; + if (value == _routerDNS) + return; - _routerDNS = value; - OnPropertyChanged(); - } + _routerDNS = value; + OnPropertyChanged(); } + } - private ConnectionState _routerDNSState = ConnectionState.None; - public ConnectionState RouterDNSState + private ConnectionState _routerDNSState = ConnectionState.None; + public ConnectionState RouterDNSState + { + get => _routerDNSState; + set { - get => _routerDNSState; - set - { - if (value == _routerDNSState) - return; + if (value == _routerDNSState) + return; - _routerDNSState = value; - OnPropertyChanged(); - } + _routerDNSState = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Internet - private bool _isInternetIPv4Checking; - public bool IsInternetIPv4Checking + #region Internet + private bool _isInternetIPv4Checking; + public bool IsInternetIPv4Checking + { + get => _isInternetIPv4Checking; + set { - get => _isInternetIPv4Checking; - set - { - if (value == _isInternetIPv4Checking) - return; + if (value == _isInternetIPv4Checking) + return; - _isInternetIPv4Checking = value; - OnPropertyChanged(); - } + _isInternetIPv4Checking = value; + OnPropertyChanged(); } + } - private string _internetIPv4; - public string InternetIPv4 + private string _internetIPv4; + public string InternetIPv4 + { + get => _internetIPv4; + set { - get => _internetIPv4; - set - { - if (value == _internetIPv4) - return; + if (value == _internetIPv4) + return; - _internetIPv4 = value; - OnPropertyChanged(); - } + _internetIPv4 = value; + OnPropertyChanged(); } + } - private ConnectionState _internetIPv4State = ConnectionState.None; - public ConnectionState InternetIPv4State + private ConnectionState _internetIPv4State = ConnectionState.None; + public ConnectionState InternetIPv4State + { + get => _internetIPv4State; + set { - get => _internetIPv4State; - set - { - if (value == _internetIPv4State) - return; + if (value == _internetIPv4State) + return; - _internetIPv4State = value; - OnPropertyChanged(); - } + _internetIPv4State = value; + OnPropertyChanged(); } + } - private bool _isInternetIPv6Checking; - public bool IsInternetIPv6Checking + private bool _isInternetIPv6Checking; + public bool IsInternetIPv6Checking + { + get => _isInternetIPv6Checking; + set { - get => _isInternetIPv6Checking; - set - { - if (value == _isInternetIPv6Checking) - return; + if (value == _isInternetIPv6Checking) + return; - _isInternetIPv6Checking = value; - OnPropertyChanged(); - } + _isInternetIPv6Checking = value; + OnPropertyChanged(); } + } - private string _internetIPv6; - public string InternetIPv6 + private string _internetIPv6; + public string InternetIPv6 + { + get => _internetIPv6; + set { - get => _internetIPv6; - set - { - if (value == _internetIPv6) - return; + if (value == _internetIPv6) + return; - _internetIPv6 = value; - OnPropertyChanged(); - } + _internetIPv6 = value; + OnPropertyChanged(); } + } - private ConnectionState _internetIPv6State = ConnectionState.None; - public ConnectionState InternetIPv6State + private ConnectionState _internetIPv6State = ConnectionState.None; + public ConnectionState InternetIPv6State + { + get => _internetIPv6State; + set { - get => _internetIPv6State; - set - { - if (value == _internetIPv6State) - return; + if (value == _internetIPv6State) + return; - _internetIPv6State = value; - OnPropertyChanged(); - } + _internetIPv6State = value; + OnPropertyChanged(); } + } - private bool _isInternetDNSChecking; - public bool IsInternetDNSChecking + private bool _isInternetDNSChecking; + public bool IsInternetDNSChecking + { + get => _isInternetDNSChecking; + set { - get => _isInternetDNSChecking; - set - { - if (value == _isInternetDNSChecking) - return; + if (value == _isInternetDNSChecking) + return; - _isInternetDNSChecking = value; - OnPropertyChanged(); - } + _isInternetDNSChecking = value; + OnPropertyChanged(); } + } - private string _internetDNS; - public string InternetDNS + private string _internetDNS; + public string InternetDNS + { + get => _internetDNS; + set { - get => _internetDNS; - set - { - if (value == _internetDNS) - return; + if (value == _internetDNS) + return; - _internetDNS = value; - OnPropertyChanged(); - } + _internetDNS = value; + OnPropertyChanged(); } + } - private ConnectionState _internetDNSState = ConnectionState.None; - public ConnectionState InternetDNSState + private ConnectionState _internetDNSState = ConnectionState.None; + public ConnectionState InternetDNSState + { + get => _internetDNSState; + set { - get => _internetDNSState; - set - { - if (value == _internetDNSState) - return; + if (value == _internetDNSState) + return; - _internetDNSState = value; - OnPropertyChanged(); - } + _internetDNSState = value; + OnPropertyChanged(); } - #endregion + } + #endregion - public bool CheckPublicIPAddress => SettingsManager.Current.Dashboard_CheckPublicIPAddress; - #endregion + public bool CheckPublicIPAddress => SettingsManager.Current.Dashboard_CheckPublicIPAddress; + #endregion - #region Constructor, load settings + #region Constructor, load settings - public NetworkConnectionViewModel() - { - // Detect if network address or status changed... - NetworkChange.NetworkAvailabilityChanged += (sender, args) => CheckConnection(); - NetworkChange.NetworkAddressChanged += (sender, args) => CheckConnection(); + public NetworkConnectionViewModel() + { + // Detect if network address or status changed... + NetworkChange.NetworkAvailabilityChanged += (sender, args) => CheckConnection(); + NetworkChange.NetworkAddressChanged += (sender, args) => CheckConnection(); - LoadSettings(); + LoadSettings(); - // Detect if settings have changed... - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + // Detect if settings have changed... + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + } + + private void LoadSettings() + { + + } + #endregion + + #region ICommands & Actions + public ICommand CheckConnectionViaHotkeyCommand => new RelayCommand(p => CheckConnectionViaHotkeyAction()); + + private void CheckConnectionViaHotkeyAction() + { + CheckConnection(); + } + #endregion + + #region Methods + public void CheckConnection() + { + CheckConnectionAsync().ConfigureAwait(false); + } + + CancellationTokenSource tokenSource; + CancellationToken ct; + + private async Task CheckConnectionAsync() + { + // Already in queue + if (tokenSource != null && tokenSource.IsCancellationRequested) + { + return; } - private void LoadSettings() + // Cancel if running + if (IsChecking) { + tokenSource.Cancel(); + while (IsChecking) + { + await Task.Delay(250); + } } - #endregion - #region ICommands & Actions - public ICommand CheckConnectionViaHotkeyCommand => new RelayCommand(p => CheckConnectionViaHotkeyAction()); + // Start check + IsChecking = true; - private void CheckConnectionViaHotkeyAction() + tokenSource = new CancellationTokenSource(); + ct = tokenSource.Token; + + try { - CheckConnection(); - } - #endregion + await Task.Run(async () => + { + List tasks = new() + { + CheckConnectionComputerAsync(ct), + CheckConnectionRouterAsync(ct), + CheckConnectionInternetAsync(ct) + }; - #region Methods - public void CheckConnection() + await Task.WhenAll(tasks); + }, tokenSource.Token); + } + catch (OperationCanceledException) { - CheckConnectionAsync().ConfigureAwait(false); + } + finally + { + tokenSource.Dispose(); + IsChecking = false; + } + } - CancellationTokenSource tokenSource; - CancellationToken ct; - - private async Task CheckConnectionAsync() + private Task CheckConnectionComputerAsync(CancellationToken ct) + { + return Task.Run(async () => { - // Already in queue - if (tokenSource != null && tokenSource.IsCancellationRequested) - { - return; - } + // Init variables + IsComputerIPv4Checking = true; + ComputerIPv4 = ""; + ComputerIPv4State = ConnectionState.None; + IsComputerIPv6Checking = true; + ComputerIPv6 = ""; + ComputerIPv6State = ConnectionState.None; + IsComputerDNSChecking = true; + ComputerDNS = ""; + ComputerDNSState = ConnectionState.None; - // Cancel if running - if (IsChecking) + // Detect local IPv4 address + var detectedLocalIPv4Address = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv4Address)); + + if (detectedLocalIPv4Address != null) + { + ComputerIPv4 = detectedLocalIPv4Address.ToString(); + ComputerIPv4State = string.IsNullOrEmpty(ComputerIPv4) ? ConnectionState.Critical : ConnectionState.OK; + } + else { - tokenSource.Cancel(); + ComputerIPv4 = "-/-"; + ComputerIPv4State = ConnectionState.Critical; + } - while (IsChecking) - { - await Task.Delay(250); - } + IsComputerIPv4Checking = false; + + if (ct.IsCancellationRequested) + ct.ThrowIfCancellationRequested(); + + // Detect local IPv6 address + var detectedLocalIPv6Address = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv6Address)); + + if (detectedLocalIPv6Address != null) + { + ComputerIPv6 = detectedLocalIPv6Address.ToString(); + ComputerIPv6State = string.IsNullOrEmpty(ComputerIPv6) ? ConnectionState.Critical : ConnectionState.OK; + } + else + { + ComputerIPv6 = "-/-"; + ComputerIPv6State = ConnectionState.Critical; } - // Start check - IsChecking = true; + IsComputerIPv6Checking = false; - tokenSource = new CancellationTokenSource(); - ct = tokenSource.Token; + if (ct.IsCancellationRequested) + ct.ThrowIfCancellationRequested(); - try + // Try to resolve local DNS based on IPv4 + if (ComputerIPv4State == ConnectionState.OK) { - await Task.Run(async () => - { - List tasks = new() - { - CheckConnectionComputerAsync(ct), - CheckConnectionRouterAsync(ct), - CheckConnectionInternetAsync(ct) - }; - - await Task.WhenAll(tasks); - }, tokenSource.Token); + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(ComputerIPv4)); + + if(!dnsResult.HasError) + { + ComputerDNS = dnsResult.Value; + ComputerDNSState = ConnectionState.OK; + } } - catch (OperationCanceledException) + + // Try to resolve local DNS based on IPv6 if IPv4 failed + if(string.IsNullOrEmpty(ComputerDNS) && ComputerIPv6State == ConnectionState.OK) { - + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(ComputerIPv6)); + + if (!dnsResult.HasError) + { + ComputerDNS = dnsResult.Value; + ComputerDNSState = ConnectionState.OK; + } } - finally + + if (string.IsNullOrEmpty(ComputerDNS)) { - tokenSource.Dispose(); - IsChecking = false; + ComputerDNS = "-/-"; + ComputerDNSState = ConnectionState.Critical; } - } - private Task CheckConnectionComputerAsync(CancellationToken ct) + IsComputerDNSChecking = false; + }, ct); + } + + private Task CheckConnectionRouterAsync(CancellationToken ct) + { + return Task.Run(async () => { - return Task.Run(async () => + // Init variables + IsRouterIPv4Checking = true; + RouterIPv4 = ""; + RouterIPv4State = ConnectionState.None; + IsRouterIPv6Checking = true; + RouterIPv6 = ""; + RouterIPv6State = ConnectionState.None; + IsRouterDNSChecking = true; + RouterDNS = ""; + RouterDNSState = ConnectionState.None; + + // Detect router IPv4 and if it is reachable + var detectedLocalIPv4Address = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv4Address)); + + if (detectedLocalIPv4Address != null) { - // Init variables - IsComputerIPv4Checking = true; - ComputerIPv4 = ""; - ComputerIPv4State = ConnectionState.None; - IsComputerIPv6Checking = true; - ComputerIPv6 = ""; - ComputerIPv6State = ConnectionState.None; - IsComputerDNSChecking = true; - ComputerDNS = ""; - ComputerDNSState = ConnectionState.None; - - // Detect local IPv4 address - var detectedLocalIPv4Address = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv4Address)); - - if (detectedLocalIPv4Address != null) + var detectedRouterIPv4 = Models.Network.NetworkInterface.DetectGatewayBasedOnLocalIPAddress(detectedLocalIPv4Address); + + if (detectedRouterIPv4 != null) { - ComputerIPv4 = detectedLocalIPv4Address.ToString(); - ComputerIPv4State = string.IsNullOrEmpty(ComputerIPv4) ? ConnectionState.Critical : ConnectionState.OK; + RouterIPv4 = detectedRouterIPv4.ToString(); + RouterIPv4State = string.IsNullOrEmpty(RouterIPv4) ? ConnectionState.Critical : ConnectionState.OK; } else { - ComputerIPv4 = "-/-"; - ComputerIPv4State = ConnectionState.Critical; + RouterIPv4 = "-/-"; + RouterIPv4State = ConnectionState.Critical; } + } + else + { + RouterIPv4 = "-/-"; + RouterIPv4State = ConnectionState.Critical; + } - IsComputerIPv4Checking = false; + IsRouterIPv4Checking = false; - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); + if (ct.IsCancellationRequested) + ct.ThrowIfCancellationRequested(); + + // Detect router IPv6 and if it is reachable + var detectedComputerIPv6 = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv6Address)); - // Detect local IPv6 address - var detectedLocalIPv6Address = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv6Address)); + if (detectedComputerIPv6 != null) + { + var detectedRouterIPv6 = Models.Network.NetworkInterface.DetectGatewayBasedOnLocalIPAddress(detectedComputerIPv6); - if (detectedLocalIPv6Address != null) + if (detectedRouterIPv6 != null) { - ComputerIPv6 = detectedLocalIPv6Address.ToString(); - ComputerIPv6State = string.IsNullOrEmpty(ComputerIPv6) ? ConnectionState.Critical : ConnectionState.OK; + RouterIPv6 = detectedRouterIPv6.ToString(); + RouterIPv6State = string.IsNullOrEmpty(RouterIPv6) ? ConnectionState.Critical : ConnectionState.OK; } else { - ComputerIPv6 = "-/-"; - ComputerIPv6State = ConnectionState.Critical; + RouterIPv6 = "-/-"; + RouterIPv6State = ConnectionState.Critical; } + } + else + { + RouterIPv6 = "-/-"; + RouterIPv6State = ConnectionState.Critical; + } - IsComputerIPv6Checking = false; + IsRouterIPv6Checking = false; - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); + if (ct.IsCancellationRequested) + ct.ThrowIfCancellationRequested(); + + // Try to resolve router DNS based on IPv4 + if (RouterIPv4State == ConnectionState.OK) + { + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(RouterIPv4)); - // Try to resolve local DNS based on IPv4 - if (ComputerIPv4State == ConnectionState.OK) + if (!dnsResult.HasError) { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(ComputerIPv4)); - - if(!dnsResult.HasError) - { - ComputerDNS = dnsResult.Value; - ComputerDNSState = ConnectionState.OK; - } + RouterDNS = dnsResult.Value; + RouterDNSState = ConnectionState.OK; } + } - // Try to resolve local DNS based on IPv6 if IPv4 failed - if(string.IsNullOrEmpty(ComputerDNS) && ComputerIPv6State == ConnectionState.OK) - { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(ComputerIPv6)); - - if (!dnsResult.HasError) - { - ComputerDNS = dnsResult.Value; - ComputerDNSState = ConnectionState.OK; - } - } + // Try to resolve router DNS based on IPv6 if IPv4 failed + if (string.IsNullOrEmpty(RouterDNS) && RouterIPv6State == ConnectionState.OK) + { + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(RouterIPv6)); - if (string.IsNullOrEmpty(ComputerDNS)) + if (!dnsResult.HasError) { - ComputerDNS = "-/-"; - ComputerDNSState = ConnectionState.Critical; + RouterDNS = dnsResult.Value; + RouterDNSState = ConnectionState.OK; } + } - IsComputerDNSChecking = false; - }, ct); - } + if (string.IsNullOrEmpty(RouterDNS)) + { + RouterDNS = "-/-"; + RouterDNSState = ConnectionState.Critical; + } - private Task CheckConnectionRouterAsync(CancellationToken ct) - { - return Task.Run(async () => + IsRouterDNSChecking = false; + }, ct); + } + + private Task CheckConnectionInternetAsync(CancellationToken ct) + { + return Task.Run(async () => { // Init variables - IsRouterIPv4Checking = true; - RouterIPv4 = ""; - RouterIPv4State = ConnectionState.None; - IsRouterIPv6Checking = true; - RouterIPv6 = ""; - RouterIPv6State = ConnectionState.None; - IsRouterDNSChecking = true; - RouterDNS = ""; - RouterDNSState = ConnectionState.None; - - // Detect router IPv4 and if it is reachable - var detectedLocalIPv4Address = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv4Address)); - - if (detectedLocalIPv4Address != null) + IsInternetIPv4Checking = true; + InternetIPv4 = ""; + InternetIPv4State = ConnectionState.None; + IsInternetIPv6Checking = true; + InternetIPv6 = ""; + InternetIPv6State = ConnectionState.None; + IsInternetDNSChecking = true; + InternetDNS = ""; + InternetDNSState = ConnectionState.None; + + // If public IP address check is disabled + if (!SettingsManager.Current.Dashboard_CheckPublicIPAddress) + { + InternetIPv4 = Strings.CheckIsDisabled; + InternetIPv4State = ConnectionState.Info; + IsInternetIPv4Checking = false; + + InternetIPv6 = Strings.CheckIsDisabled; + InternetIPv6State = ConnectionState.Info; + IsInternetIPv6Checking = false; + + InternetDNS = Strings.CheckIsDisabled; + InternetDNSState = ConnectionState.Info; + IsInternetDNSChecking = false; + + return; + } + + // Detect public IPv4 and if it is reachable + var publicIPv4AddressAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI ? SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI : GlobalStaticConfiguration.Dashboard_PublicIPv4AddressAPI; + + try { - var detectedRouterIPv4 = Models.Network.NetworkInterface.DetectGatewayBasedOnLocalIPAddress(detectedLocalIPv4Address); + HttpClient httpClient = new(); + var httpResponse = await httpClient.GetAsync(publicIPv4AddressAPI); - if (detectedRouterIPv4 != null) + var result = await httpResponse.Content.ReadAsStringAsync(); + + var match = Regex.Match(result, RegexHelper.IPv4AddressExctractRegex); + + if (match.Success) { - RouterIPv4 = detectedRouterIPv4.ToString(); - RouterIPv4State = string.IsNullOrEmpty(RouterIPv4) ? ConnectionState.Critical : ConnectionState.OK; + InternetIPv4 = match.Value; + InternetIPv4State = ConnectionState.OK; } else { - RouterIPv4 = "-/-"; - RouterIPv4State = ConnectionState.Critical; + InternetIPv4 = "-/-"; + InternetIPv4State = ConnectionState.Critical; } } - else + catch { - RouterIPv4 = "-/-"; - RouterIPv4State = ConnectionState.Critical; + InternetIPv4 = "-/-"; + InternetIPv4State = ConnectionState.Critical; } - IsRouterIPv4Checking = false; + IsInternetIPv4Checking = false; if (ct.IsCancellationRequested) ct.ThrowIfCancellationRequested(); - // Detect router IPv6 and if it is reachable - var detectedComputerIPv6 = Models.Network.NetworkInterface.DetectLocalIPAddressBasedOnRouting(IPAddress.Parse(SettingsManager.Current.Dashboard_PublicIPv6Address)); + // Detect public IPv6 and if it is reachable + var publicIPv6AddressAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI ? SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI : GlobalStaticConfiguration.Dashboard_PublicIPv6AddressAPI; - if (detectedComputerIPv6 != null) + try { - var detectedRouterIPv6 = Models.Network.NetworkInterface.DetectGatewayBasedOnLocalIPAddress(detectedComputerIPv6); + HttpClient httpClient = new(); + var httpResponse = await httpClient.GetAsync(publicIPv4AddressAPI); + + var result = await httpResponse.Content.ReadAsStringAsync(); + + var match = Regex.Match(result, RegexHelper.IPv6AddressRegex); - if (detectedRouterIPv6 != null) + if (match.Success) { - RouterIPv6 = detectedRouterIPv6.ToString(); - RouterIPv6State = string.IsNullOrEmpty(RouterIPv6) ? ConnectionState.Critical : ConnectionState.OK; + InternetIPv6 = match.Value; + InternetIPv6State = ConnectionState.OK; } else { - RouterIPv6 = "-/-"; - RouterIPv6State = ConnectionState.Critical; + InternetIPv6 = "-/-"; + InternetIPv6State = ConnectionState.Critical; } } - else + catch { - RouterIPv6 = "-/-"; - RouterIPv6State = ConnectionState.Critical; + InternetIPv6 = "-/-"; + InternetIPv6State = ConnectionState.Critical; } - IsRouterIPv6Checking = false; + IsInternetIPv6Checking = false; if (ct.IsCancellationRequested) ct.ThrowIfCancellationRequested(); - - // Try to resolve router DNS based on IPv4 - if (RouterIPv4State == ConnectionState.OK) + + // Try to resolve public DNS based on IPv4 + if (InternetIPv4State == ConnectionState.OK) { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(RouterIPv4)); + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(InternetIPv4)); if (!dnsResult.HasError) { - RouterDNS = dnsResult.Value; - RouterDNSState = ConnectionState.OK; + InternetDNS = dnsResult.Value; + InternetDNSState = ConnectionState.OK; } } // Try to resolve router DNS based on IPv6 if IPv4 failed - if (string.IsNullOrEmpty(RouterDNS) && RouterIPv6State == ConnectionState.OK) + if (string.IsNullOrEmpty(InternetDNS) && InternetIPv6State == ConnectionState.OK) { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(RouterIPv6)); + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(InternetIPv6)); if (!dnsResult.HasError) { - RouterDNS = dnsResult.Value; - RouterDNSState = ConnectionState.OK; + InternetDNS = dnsResult.Value; + InternetDNSState = ConnectionState.OK; } } - if (string.IsNullOrEmpty(RouterDNS)) + if (string.IsNullOrEmpty(InternetDNS)) { - RouterDNS = "-/-"; - RouterDNSState = ConnectionState.Critical; + InternetDNS = "-/-"; + InternetDNSState = ConnectionState.Critical; } - - IsRouterDNSChecking = false; + + IsInternetDNSChecking = false; }, ct); - } - - private Task CheckConnectionInternetAsync(CancellationToken ct) - { - return Task.Run(async () => - { - // Init variables - IsInternetIPv4Checking = true; - InternetIPv4 = ""; - InternetIPv4State = ConnectionState.None; - IsInternetIPv6Checking = true; - InternetIPv6 = ""; - InternetIPv6State = ConnectionState.None; - IsInternetDNSChecking = true; - InternetDNS = ""; - InternetDNSState = ConnectionState.None; - - // If public IP address check is disabled - if (!SettingsManager.Current.Dashboard_CheckPublicIPAddress) - { - InternetIPv4 = Strings.CheckIsDisabled; - InternetIPv4State = ConnectionState.Info; - IsInternetIPv4Checking = false; - - InternetIPv6 = Strings.CheckIsDisabled; - InternetIPv6State = ConnectionState.Info; - IsInternetIPv6Checking = false; - - InternetDNS = Strings.CheckIsDisabled; - InternetDNSState = ConnectionState.Info; - IsInternetDNSChecking = false; - - return; - } - - // Detect public IPv4 and if it is reachable - var publicIPv4AddressAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv4AddressAPI ? SettingsManager.Current.Dashboard_CustomPublicIPv4AddressAPI : GlobalStaticConfiguration.Dashboard_PublicIPv4AddressAPI; - - try - { - HttpClient httpClient = new(); - var httpResponse = await httpClient.GetAsync(publicIPv4AddressAPI); - - var result = await httpResponse.Content.ReadAsStringAsync(); - - var match = Regex.Match(result, RegexHelper.IPv4AddressExctractRegex); - - if (match.Success) - { - InternetIPv4 = match.Value; - InternetIPv4State = ConnectionState.OK; - } - else - { - InternetIPv4 = "-/-"; - InternetIPv4State = ConnectionState.Critical; - } - } - catch - { - InternetIPv4 = "-/-"; - InternetIPv4State = ConnectionState.Critical; - } - - IsInternetIPv4Checking = false; - - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); - - // Detect public IPv6 and if it is reachable - var publicIPv6AddressAPI = SettingsManager.Current.Dashboard_UseCustomPublicIPv6AddressAPI ? SettingsManager.Current.Dashboard_CustomPublicIPv6AddressAPI : GlobalStaticConfiguration.Dashboard_PublicIPv6AddressAPI; - - try - { - HttpClient httpClient = new(); - var httpResponse = await httpClient.GetAsync(publicIPv4AddressAPI); - - var result = await httpResponse.Content.ReadAsStringAsync(); - - var match = Regex.Match(result, RegexHelper.IPv6AddressRegex); - - if (match.Success) - { - InternetIPv6 = match.Value; - InternetIPv6State = ConnectionState.OK; - } - else - { - InternetIPv6 = "-/-"; - InternetIPv6State = ConnectionState.Critical; - } - } - catch - { - InternetIPv6 = "-/-"; - InternetIPv6State = ConnectionState.Critical; - } - - IsInternetIPv6Checking = false; - - if (ct.IsCancellationRequested) - ct.ThrowIfCancellationRequested(); - - // Try to resolve public DNS based on IPv4 - if (InternetIPv4State == ConnectionState.OK) - { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(InternetIPv4)); - - if (!dnsResult.HasError) - { - InternetDNS = dnsResult.Value; - InternetDNSState = ConnectionState.OK; - } - } - - // Try to resolve router DNS based on IPv6 if IPv4 failed - if (string.IsNullOrEmpty(InternetDNS) && InternetIPv6State == ConnectionState.OK) - { - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress.Parse(InternetIPv6)); - - if (!dnsResult.HasError) - { - InternetDNS = dnsResult.Value; - InternetDNSState = ConnectionState.OK; - } - } - - if (string.IsNullOrEmpty(InternetDNS)) - { - InternetDNS = "-/-"; - InternetDNSState = ConnectionState.Critical; - } - - IsInternetDNSChecking = false; - }, ct); - } - #endregion + } + #endregion - #region Events - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + #region Events + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) { - switch (e.PropertyName) - { - case nameof(SettingsInfo.Dashboard_CheckPublicIPAddress): - OnPropertyChanged(nameof(CheckPublicIPAddress)); - break; - } + case nameof(SettingsInfo.Dashboard_CheckPublicIPAddress): + OnPropertyChanged(nameof(CheckPublicIPAddress)); + break; } - #endregion } + #endregion } diff --git a/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs b/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs index f3858b0d39..678e953f0c 100644 --- a/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs +++ b/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs @@ -21,1244 +21,1243 @@ using System.Windows.Threading; using NETworkManager.Models; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class NetworkInterfaceViewModel : ViewModelBase, IProfileManager { - public class NetworkInterfaceViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - private BandwidthMeter _bandwidthMeter; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + private BandwidthMeter _bandwidthMeter; - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private bool _isNetworkInteraceLoading; - public bool IsNetworkInterfaceLoading + private bool _isNetworkInteraceLoading; + public bool IsNetworkInterfaceLoading + { + get => _isNetworkInteraceLoading; + set { - get => _isNetworkInteraceLoading; - set - { - if (value == _isNetworkInteraceLoading) - return; + if (value == _isNetworkInteraceLoading) + return; - _isNetworkInteraceLoading = value; - OnPropertyChanged(); - } + _isNetworkInteraceLoading = value; + OnPropertyChanged(); } + } - private bool _canConfigure; - public bool CanConfigure + private bool _canConfigure; + public bool CanConfigure + { + get => _canConfigure; + set { - get => _canConfigure; - set - { - if (value == _canConfigure) - return; + if (value == _canConfigure) + return; - _canConfigure = value; - OnPropertyChanged(); - } + _canConfigure = value; + OnPropertyChanged(); } + } - private bool _isConfigurationRunning; - public bool IsConfigurationRunning + private bool _isConfigurationRunning; + public bool IsConfigurationRunning + { + get => _isConfigurationRunning; + set { - get => _isConfigurationRunning; - set - { - if (value == _isConfigurationRunning) - return; + if (value == _isConfigurationRunning) + return; - _isConfigurationRunning = value; - OnPropertyChanged(); - } + _isConfigurationRunning = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } + } - #region NetworkInterfaces, SelectedNetworkInterface - private List _networkInterfaces; - public List NetworkInterfaces + #region NetworkInterfaces, SelectedNetworkInterface + private List _networkInterfaces; + public List NetworkInterfaces + { + get => _networkInterfaces; + set { - get => _networkInterfaces; - set - { - if (value == _networkInterfaces) - return; + if (value == _networkInterfaces) + return; - _networkInterfaces = value; - OnPropertyChanged(); - } + _networkInterfaces = value; + OnPropertyChanged(); } + } - private NetworkInterfaceInfo _selectedNetworkInterface; - public NetworkInterfaceInfo SelectedNetworkInterface + private NetworkInterfaceInfo _selectedNetworkInterface; + public NetworkInterfaceInfo SelectedNetworkInterface + { + get => _selectedNetworkInterface; + set { - get => _selectedNetworkInterface; - set + if (value == _selectedNetworkInterface) + return; + + if (value != null) { - if (value == _selectedNetworkInterface) - return; - - if (value != null) - { - if (!_isLoading) - SettingsManager.Current.NetworkInterface_InterfaceId = value.Id; - - // Bandwidth - StopBandwidthMeter(); - StartBandwidthMeter(value.Id); - - // Configuration - SetConfigurationDefaults(value); - - CanConfigure = value.IsOperational; - } - - _selectedNetworkInterface = value; - OnPropertyChanged(); + if (!_isLoading) + SettingsManager.Current.NetworkInterface_InterfaceId = value.Id; + + // Bandwidth + StopBandwidthMeter(); + StartBandwidthMeter(value.Id); + + // Configuration + SetConfigurationDefaults(value); + + CanConfigure = value.IsOperational; } + + _selectedNetworkInterface = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Bandwidth - private long _bandwidthTotalBytesSentTemp; + #region Bandwidth + private long _bandwidthTotalBytesSentTemp; - private long _bandwidthTotalBytesSent; - public long BandwidthTotalBytesSent + private long _bandwidthTotalBytesSent; + public long BandwidthTotalBytesSent + { + get => _bandwidthTotalBytesSent; + set { - get => _bandwidthTotalBytesSent; - set - { - if (value == _bandwidthTotalBytesSent) - return; + if (value == _bandwidthTotalBytesSent) + return; - _bandwidthTotalBytesSent = value; - OnPropertyChanged(); - } + _bandwidthTotalBytesSent = value; + OnPropertyChanged(); } + } - private long _bandwidthTotalBytesReceivedTemp; - private long _bandwidthTotalBytesReceived; - public long BandwidthTotalBytesReceived + private long _bandwidthTotalBytesReceivedTemp; + private long _bandwidthTotalBytesReceived; + public long BandwidthTotalBytesReceived + { + get => _bandwidthTotalBytesReceived; + set { - get => _bandwidthTotalBytesReceived; - set - { - if (value == _bandwidthTotalBytesReceived) - return; + if (value == _bandwidthTotalBytesReceived) + return; - _bandwidthTotalBytesReceived = value; - OnPropertyChanged(); - } + _bandwidthTotalBytesReceived = value; + OnPropertyChanged(); } + } - private long _bandwidthDiffBytesSent; - public long BandwidthDiffBytesSent + private long _bandwidthDiffBytesSent; + public long BandwidthDiffBytesSent + { + get => _bandwidthDiffBytesSent; + set { - get => _bandwidthDiffBytesSent; - set - { - if (value == _bandwidthDiffBytesSent) - return; + if (value == _bandwidthDiffBytesSent) + return; - _bandwidthDiffBytesSent = value; - OnPropertyChanged(); - } + _bandwidthDiffBytesSent = value; + OnPropertyChanged(); } + } - private long _bandwidthDiffBytesReceived; - public long BandwidthDiffBytesReceived + private long _bandwidthDiffBytesReceived; + public long BandwidthDiffBytesReceived + { + get => _bandwidthDiffBytesReceived; + set { - get => _bandwidthDiffBytesReceived; - set - { - if (value == _bandwidthDiffBytesReceived) - return; + if (value == _bandwidthDiffBytesReceived) + return; - _bandwidthDiffBytesReceived = value; - OnPropertyChanged(); - } + _bandwidthDiffBytesReceived = value; + OnPropertyChanged(); } + } - private long _bandwithBytesReceivedSpeed; - public long BandwidthBytesReceivedSpeed + private long _bandwithBytesReceivedSpeed; + public long BandwidthBytesReceivedSpeed + { + get => _bandwithBytesReceivedSpeed; + set { - get => _bandwithBytesReceivedSpeed; - set - { - if (value == _bandwithBytesReceivedSpeed) - return; + if (value == _bandwithBytesReceivedSpeed) + return; - _bandwithBytesReceivedSpeed = value; - OnPropertyChanged(); - } + _bandwithBytesReceivedSpeed = value; + OnPropertyChanged(); } + } - private long _bandwidthBytesSentSpeed; - public long BandwidthBytesSentSpeed + private long _bandwidthBytesSentSpeed; + public long BandwidthBytesSentSpeed + { + get => _bandwidthBytesSentSpeed; + set { - get => _bandwidthBytesSentSpeed; - set - { - if (value == _bandwidthBytesSentSpeed) - return; + if (value == _bandwidthBytesSentSpeed) + return; - _bandwidthBytesSentSpeed = value; - OnPropertyChanged(); - } + _bandwidthBytesSentSpeed = value; + OnPropertyChanged(); } + } - private DateTime _bandwidthStartTime; - public DateTime BandwidthStartTime + private DateTime _bandwidthStartTime; + public DateTime BandwidthStartTime + { + get => _bandwidthStartTime; + set { - get => _bandwidthStartTime; - set - { - if (value == _bandwidthStartTime) - return; + if (value == _bandwidthStartTime) + return; - _bandwidthStartTime = value; - OnPropertyChanged(); - } + _bandwidthStartTime = value; + OnPropertyChanged(); } + } - private TimeSpan _bandwidthMeasuredTime; - public TimeSpan BandwidthMeasuredTime + private TimeSpan _bandwidthMeasuredTime; + public TimeSpan BandwidthMeasuredTime + { + get => _bandwidthMeasuredTime; + set { - get => _bandwidthMeasuredTime; - set - { - if (value == _bandwidthMeasuredTime) - return; + if (value == _bandwidthMeasuredTime) + return; - _bandwidthMeasuredTime = value; - OnPropertyChanged(); - } + _bandwidthMeasuredTime = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Config - private bool _configEnableDynamicIPAddress = true; - public bool ConfigEnableDynamicIPAddress + #region Config + private bool _configEnableDynamicIPAddress = true; + public bool ConfigEnableDynamicIPAddress + { + get => _configEnableDynamicIPAddress; + set { - get => _configEnableDynamicIPAddress; - set - { - if (value == _configEnableDynamicIPAddress) - return; + if (value == _configEnableDynamicIPAddress) + return; - _configEnableDynamicIPAddress = value; - OnPropertyChanged(); - } + _configEnableDynamicIPAddress = value; + OnPropertyChanged(); } + } - private bool _configEnableStaticIPAddress; - public bool ConfigEnableStaticIPAddress + private bool _configEnableStaticIPAddress; + public bool ConfigEnableStaticIPAddress + { + get => _configEnableStaticIPAddress; + set { - get => _configEnableStaticIPAddress; - set - { - if (value == _configEnableStaticIPAddress) - return; + if (value == _configEnableStaticIPAddress) + return; - ConfigEnableStaticDNS = true; + ConfigEnableStaticDNS = true; - _configEnableStaticIPAddress = value; - OnPropertyChanged(); - } + _configEnableStaticIPAddress = value; + OnPropertyChanged(); } + } - private string _configIPAddress; - public string ConfigIPAddress + private string _configIPAddress; + public string ConfigIPAddress + { + get => _configIPAddress; + set { - get => _configIPAddress; - set - { - if (value == _configIPAddress) - return; + if (value == _configIPAddress) + return; - _configIPAddress = value; - OnPropertyChanged(); - } + _configIPAddress = value; + OnPropertyChanged(); } + } - private string _configSubnetmaskOrCidr; - public string ConfigSubnetmaskOrCidr + private string _configSubnetmaskOrCidr; + public string ConfigSubnetmaskOrCidr + { + get => _configSubnetmaskOrCidr; + set { - get => _configSubnetmaskOrCidr; - set - { - if (value == _configSubnetmaskOrCidr) - return; + if (value == _configSubnetmaskOrCidr) + return; - _configSubnetmaskOrCidr = value; - OnPropertyChanged(); - } + _configSubnetmaskOrCidr = value; + OnPropertyChanged(); } + } - private string _configGateway; - public string ConfigGateway + private string _configGateway; + public string ConfigGateway + { + get => _configGateway; + set { - get => _configGateway; - set - { - if (value == _configGateway) - return; + if (value == _configGateway) + return; - _configGateway = value; - OnPropertyChanged(); - } + _configGateway = value; + OnPropertyChanged(); } + } - private bool _configEnableDynamicDNS = true; - public bool ConfigEnableDynamicDNS + private bool _configEnableDynamicDNS = true; + public bool ConfigEnableDynamicDNS + { + get => _configEnableDynamicDNS; + set { - get => _configEnableDynamicDNS; - set - { - if (value == _configEnableDynamicDNS) - return; + if (value == _configEnableDynamicDNS) + return; - _configEnableDynamicDNS = value; - OnPropertyChanged(); - } + _configEnableDynamicDNS = value; + OnPropertyChanged(); } + } - private bool _configEnableStaticDNS; - public bool ConfigEnableStaticDNS + private bool _configEnableStaticDNS; + public bool ConfigEnableStaticDNS + { + get => _configEnableStaticDNS; + set { - get => _configEnableStaticDNS; - set - { - if (value == _configEnableStaticDNS) - return; + if (value == _configEnableStaticDNS) + return; - _configEnableStaticDNS = value; - OnPropertyChanged(); - } + _configEnableStaticDNS = value; + OnPropertyChanged(); } + } - private string _configPrimaryDNSServer; - public string ConfigPrimaryDNSServer + private string _configPrimaryDNSServer; + public string ConfigPrimaryDNSServer + { + get => _configPrimaryDNSServer; + set { - get => _configPrimaryDNSServer; - set - { - if (value == _configPrimaryDNSServer) - return; + if (value == _configPrimaryDNSServer) + return; - _configPrimaryDNSServer = value; - OnPropertyChanged(); - } + _configPrimaryDNSServer = value; + OnPropertyChanged(); } + } - private string _configSecondaryDNSServer; - public string ConfigSecondaryDNSServer + private string _configSecondaryDNSServer; + public string ConfigSecondaryDNSServer + { + get => _configSecondaryDNSServer; + set { - get => _configSecondaryDNSServer; - set - { - if (value == _configSecondaryDNSServer) - return; + if (value == _configSecondaryDNSServer) + return; - _configSecondaryDNSServer = value; - OnPropertyChanged(); - } + _configSecondaryDNSServer = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; - - if (value != null) - { - ConfigEnableDynamicIPAddress = !value.NetworkInterface_EnableStaticIPAddress; - ConfigEnableStaticIPAddress = value.NetworkInterface_EnableStaticIPAddress; - ConfigIPAddress = value.NetworkInterface_IPAddress; - ConfigGateway = value.NetworkInterface_Gateway; - ConfigSubnetmaskOrCidr = value.NetworkInterface_SubnetmaskOrCidr; - ConfigEnableDynamicDNS = !value.NetworkInterface_EnableStaticDNS; - ConfigEnableStaticDNS = value.NetworkInterface_EnableStaticDNS; - ConfigPrimaryDNSServer = value.NetworkInterface_PrimaryDNSServer; - ConfigSecondaryDNSServer = value.NetworkInterface_SecondaryDNSServer; - } - - _selectedProfile = value; - OnPropertyChanged(); + if (value == _selectedProfile) + return; + + if (value != null) + { + ConfigEnableDynamicIPAddress = !value.NetworkInterface_EnableStaticIPAddress; + ConfigEnableStaticIPAddress = value.NetworkInterface_EnableStaticIPAddress; + ConfigIPAddress = value.NetworkInterface_IPAddress; + ConfigGateway = value.NetworkInterface_Gateway; + ConfigSubnetmaskOrCidr = value.NetworkInterface_SubnetmaskOrCidr; + ConfigEnableDynamicDNS = !value.NetworkInterface_EnableStaticDNS; + ConfigEnableStaticDNS = value.NetworkInterface_EnableStaticDNS; + ConfigPrimaryDNSServer = value.NetworkInterface_PrimaryDNSServer; + ConfigSecondaryDNSServer = value.NetworkInterface_SecondaryDNSServer; } + + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.NetworkInterface_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.NetworkInterface_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.NetworkInterface_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.NetworkInterface_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(dueToChangedSize: true); + if (_canProfileWidthChange) + ResizeProfile(dueToChangedSize: true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, LoadSettings, OnShutdown - public NetworkInterfaceViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, LoadSettings, OnShutdown + public NetworkInterfaceViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - LoadNetworkInterfaces(); + LoadNetworkInterfaces(); - InitialBandwidthChart(); + InitialBandwidthChart(); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.NetworkInterface_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.NetworkInterface_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.NetworkInterface_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.NetworkInterface_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, IPScanner_IPRange - return info.NetworkInterface_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, IPScanner_IPRange + return info.NetworkInterface_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.NetworkInterface_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.NetworkInterface_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - // Detect if network address or status changed... - NetworkChange.NetworkAvailabilityChanged += (sender, args) => ReloadNetworkInterfaces(); - NetworkChange.NetworkAddressChanged += (sender, args) => ReloadNetworkInterfaces(); + // Detect if network address or status changed... + NetworkChange.NetworkAvailabilityChanged += (sender, args) => ReloadNetworkInterfaces(); + NetworkChange.NetworkAddressChanged += (sender, args) => ReloadNetworkInterfaces(); - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - private void InitialBandwidthChart() - { - var dayConfig = Mappers.Xy() - .X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromHours(1).Ticks) - .Y(dayModel => dayModel.Value); + private void InitialBandwidthChart() + { + var dayConfig = Mappers.Xy() + .X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromHours(1).Ticks) + .Y(dayModel => dayModel.Value); - Series = new SeriesCollection(dayConfig) + Series = new SeriesCollection(dayConfig) + { + new LineSeries { - new LineSeries - { - Title = "Download", - Values = new ChartValues(), - PointGeometry = null - }, - new LineSeries - { - Title = "Upload", - Values = new ChartValues(), - PointGeometry = null - } - }; - - FormatterDate = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("hh:mm:ss"); - FormatterSpeed = value => $"{FileSizeConverter.GetBytesReadable((long)value * 8)}it/s"; - } + Title = "Download", + Values = new ChartValues(), + PointGeometry = null + }, + new LineSeries + { + Title = "Upload", + Values = new ChartValues(), + PointGeometry = null + } + }; - public Func FormatterDate { get; set; } - public Func FormatterSpeed { get; set; } - public SeriesCollection Series { get; set; } + FormatterDate = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("hh:mm:ss"); + FormatterSpeed = value => $"{FileSizeConverter.GetBytesReadable((long)value * 8)}it/s"; + } - private async Task LoadNetworkInterfaces() - { - IsNetworkInterfaceLoading = true; + public Func FormatterDate { get; set; } + public Func FormatterSpeed { get; set; } + public SeriesCollection Series { get; set; } - NetworkInterfaces = await Models.Network.NetworkInterface.GetNetworkInterfacesAsync(); + private async Task LoadNetworkInterfaces() + { + IsNetworkInterfaceLoading = true; - // Get the last selected interface, if it is still available on this machine... - if (NetworkInterfaces.Count > 0) - { - var info = NetworkInterfaces.FirstOrDefault(s => s.Id == SettingsManager.Current.NetworkInterface_InterfaceId); + NetworkInterfaces = await Models.Network.NetworkInterface.GetNetworkInterfacesAsync(); - SelectedNetworkInterface = info ?? NetworkInterfaces[0]; - } + // Get the last selected interface, if it is still available on this machine... + if (NetworkInterfaces.Count > 0) + { + var info = NetworkInterfaces.FirstOrDefault(s => s.Id == SettingsManager.Current.NetworkInterface_InterfaceId); - IsNetworkInterfaceLoading = false; + SelectedNetworkInterface = info ?? NetworkInterfaces[0]; } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.NetworkInterface_ExpandProfileView; + IsNetworkInterfaceLoading = false; + } - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.NetworkInterface_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.NetworkInterface_ExpandProfileView; - _tempProfileWidth = SettingsManager.Current.NetworkInterface_ProfileWidth; - } - #endregion + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.NetworkInterface_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - #region ICommands & Actions - public ICommand ReloadNetworkInterfacesCommand => new RelayCommand(p => ReloadNetworkInterfacesAction(), ReloadNetworkInterfaces_CanExecute); + _tempProfileWidth = SettingsManager.Current.NetworkInterface_ProfileWidth; + } + #endregion - private bool ReloadNetworkInterfaces_CanExecute(object obj) => !IsNetworkInterfaceLoading && Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + #region ICommands & Actions + public ICommand ReloadNetworkInterfacesCommand => new RelayCommand(p => ReloadNetworkInterfacesAction(), ReloadNetworkInterfaces_CanExecute); - private void ReloadNetworkInterfacesAction() - { - ReloadNetworkInterfaces(); - } - - public ICommand ApplyConfigurationCommand => new RelayCommand(p => ApplyConfigurationAction(), ApplyConfiguration_CanExecute); + private bool ReloadNetworkInterfaces_CanExecute(object obj) => !IsNetworkInterfaceLoading && Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private bool ApplyConfiguration_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private void ReloadNetworkInterfacesAction() + { + ReloadNetworkInterfaces(); + } + + public ICommand ApplyConfigurationCommand => new RelayCommand(p => ApplyConfigurationAction(), ApplyConfiguration_CanExecute); - public void ApplyConfigurationAction() - { - ApplyConfiguration(); - } + private bool ApplyConfiguration_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - public ICommand ApplyProfileConfigCommand => new RelayCommand(p => ApplyProfileProfileAction()); + public void ApplyConfigurationAction() + { + ApplyConfiguration(); + } - private void ApplyProfileProfileAction() - { - ApplyConfigurationFromProfile(); - } + public ICommand ApplyProfileConfigCommand => new RelayCommand(p => ApplyProfileProfileAction()); - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + private void ApplyProfileProfileAction() + { + ApplyConfigurationFromProfile(); + } - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.NetworkInterface); - } + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.NetworkInterface); + } - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } - - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } + + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - #region Additional commands - private bool AdditionalCommands_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - - public ICommand OpenNetworkConnectionsCommand => new RelayCommand(p => OpenNetworkConnectionsAction(), AdditionalCommands_CanExecute); + private void ClearSearchAction() + { + Search = string.Empty; + } - public void OpenNetworkConnectionsAction() - { - OpenNetworkConnectionsAsync(); - } - - public ICommand FlushDNSCommand => new RelayCommand(p => FlushDNSAction(), AdditionalCommands_CanExecute); + #region Additional commands + private bool AdditionalCommands_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + + public ICommand OpenNetworkConnectionsCommand => new RelayCommand(p => OpenNetworkConnectionsAction(), AdditionalCommands_CanExecute); - private void FlushDNSAction() - { - FlushDNSAsync(); - } - - public ICommand ReleaseRenewCommand => new RelayCommand(p => ReleaseRenewAction(), AdditionalCommands_CanExecute); + public void OpenNetworkConnectionsAction() + { + OpenNetworkConnectionsAsync(); + } + + public ICommand FlushDNSCommand => new RelayCommand(p => FlushDNSAction(), AdditionalCommands_CanExecute); - private void ReleaseRenewAction() - { - ReleaseRenewAsync(IPConfigReleaseRenewMode.ReleaseRenew); - } - - public ICommand ReleaseCommand => new RelayCommand(p => ReleaseAction(), AdditionalCommands_CanExecute); + private void FlushDNSAction() + { + FlushDNSAsync(); + } + + public ICommand ReleaseRenewCommand => new RelayCommand(p => ReleaseRenewAction(), AdditionalCommands_CanExecute); - private void ReleaseAction() - { - ReleaseRenewAsync(IPConfigReleaseRenewMode.Release); - } + private void ReleaseRenewAction() + { + ReleaseRenewAsync(IPConfigReleaseRenewMode.ReleaseRenew); + } + + public ICommand ReleaseCommand => new RelayCommand(p => ReleaseAction(), AdditionalCommands_CanExecute); - public ICommand RenewCommand => new RelayCommand(p => RenewAction(), AdditionalCommands_CanExecute); + private void ReleaseAction() + { + ReleaseRenewAsync(IPConfigReleaseRenewMode.Release); + } - private void RenewAction() - { - ReleaseRenewAsync(IPConfigReleaseRenewMode.Renew); - } + public ICommand RenewCommand => new RelayCommand(p => RenewAction(), AdditionalCommands_CanExecute); - public ICommand ReleaseRenew6Command => new RelayCommand(p => ReleaseRenew6Action(), AdditionalCommands_CanExecute); + private void RenewAction() + { + ReleaseRenewAsync(IPConfigReleaseRenewMode.Renew); + } - private void ReleaseRenew6Action() - { - ReleaseRenewAsync(IPConfigReleaseRenewMode.ReleaseRenew6); - } + public ICommand ReleaseRenew6Command => new RelayCommand(p => ReleaseRenew6Action(), AdditionalCommands_CanExecute); - public ICommand Release6Command => new RelayCommand(p => Release6Action(), AdditionalCommands_CanExecute); + private void ReleaseRenew6Action() + { + ReleaseRenewAsync(IPConfigReleaseRenewMode.ReleaseRenew6); + } - private void Release6Action() - { - ReleaseRenewAsync(IPConfigReleaseRenewMode.Release6); - } + public ICommand Release6Command => new RelayCommand(p => Release6Action(), AdditionalCommands_CanExecute); + + private void Release6Action() + { + ReleaseRenewAsync(IPConfigReleaseRenewMode.Release6); + } - public ICommand Renew6Command => new RelayCommand(p => Renew6Action(), AdditionalCommands_CanExecute); + public ICommand Renew6Command => new RelayCommand(p => Renew6Action(), AdditionalCommands_CanExecute); - private void Renew6Action() - { - ReleaseRenewAsync(IPConfigReleaseRenewMode.Renew); - } + private void Renew6Action() + { + ReleaseRenewAsync(IPConfigReleaseRenewMode.Renew); + } - public ICommand AddIPv4AddressCommand => new RelayCommand(p => AddIPv4AddressAction(), AdditionalCommands_CanExecute); + public ICommand AddIPv4AddressCommand => new RelayCommand(p => AddIPv4AddressAction(), AdditionalCommands_CanExecute); - private async Task AddIPv4AddressAction() + private async Task AddIPv4AddressAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddIPv4Address - }; + Title = Localization.Resources.Strings.AddIPv4Address + }; - var IPAddressAndSubnetmaskViewModel = new IPAddressAndSubnetmaskViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var IPAddressAndSubnetmaskViewModel = new IPAddressAndSubnetmaskViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - AddIPv4Address(instance.IPAddress, instance.SubnetmaskOrCidr); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); + AddIPv4Address(instance.IPAddress, instance.SubnetmaskOrCidr); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - customDialog.Content = new IPAddressAndSubnetmaskDialog - { - DataContext = IPAddressAndSubnetmaskViewModel - }; + customDialog.Content = new IPAddressAndSubnetmaskDialog + { + DataContext = IPAddressAndSubnetmaskViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - public ICommand RemoveIPv4AddressCommand => new RelayCommand(p => RemoveIPv4AddressAction(), AdditionalCommands_CanExecute); + public ICommand RemoveIPv4AddressCommand => new RelayCommand(p => RemoveIPv4AddressAction(), AdditionalCommands_CanExecute); - private async Task RemoveIPv4AddressAction() + private async Task RemoveIPv4AddressAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.RemoveIPv4Address - }; + Title = Localization.Resources.Strings.RemoveIPv4Address + }; - var dropdownViewModel = new DropdownViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var dropdownViewModel = new DropdownViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - RemoveIPv4Address(instance.SelectedValue.Split("/")[0]); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, SelectedNetworkInterface.IPv4Address.Select(x => $"{x.Item1}/{Subnetmask.ConvertSubnetmaskToCidr(x.Item2)}").ToList(), Localization.Resources.Strings.IPv4Address); + RemoveIPv4Address(instance.SelectedValue.Split("/")[0]); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, SelectedNetworkInterface.IPv4Address.Select(x => $"{x.Item1}/{Subnetmask.ConvertSubnetmaskToCidr(x.Item2)}").ToList(), Localization.Resources.Strings.IPv4Address); - customDialog.Content = new DropdownDialog - { - DataContext = dropdownViewModel - }; + customDialog.Content = new DropdownDialog + { + DataContext = dropdownViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion + #endregion - #region Methods + #region Methods - private async void ReloadNetworkInterfaces() - { - IsNetworkInterfaceLoading = true; + private async void ReloadNetworkInterfaces() + { + IsNetworkInterfaceLoading = true; - await Task.Delay(2000); // Make the user happy, let him see a reload animation (and he cannot spam the reload command) + await Task.Delay(2000); // Make the user happy, let him see a reload animation (and he cannot spam the reload command) - var id = string.Empty; + var id = string.Empty; - if (SelectedNetworkInterface != null) - id = SelectedNetworkInterface.Id; + if (SelectedNetworkInterface != null) + id = SelectedNetworkInterface.Id; - NetworkInterfaces = await Models.Network.NetworkInterface.GetNetworkInterfacesAsync(); + NetworkInterfaces = await Models.Network.NetworkInterface.GetNetworkInterfacesAsync(); - // Change interface... - SelectedNetworkInterface = string.IsNullOrEmpty(id) ? NetworkInterfaces.FirstOrDefault() : NetworkInterfaces.FirstOrDefault(x => x.Id == id); + // Change interface... + SelectedNetworkInterface = string.IsNullOrEmpty(id) ? NetworkInterfaces.FirstOrDefault() : NetworkInterfaces.FirstOrDefault(x => x.Id == id); - IsNetworkInterfaceLoading = false; + IsNetworkInterfaceLoading = false; + } + + private void SetConfigurationDefaults(NetworkInterfaceInfo info) + { + if (info.DhcpEnabled) + { + ConfigEnableDynamicIPAddress = true; } - - private void SetConfigurationDefaults(NetworkInterfaceInfo info) + else { - if (info.DhcpEnabled) - { - ConfigEnableDynamicIPAddress = true; - } - else - { - ConfigEnableStaticIPAddress = true; - ConfigIPAddress = info.IPv4Address.FirstOrDefault()?.Item1.ToString(); - ConfigSubnetmaskOrCidr = info.IPv4Address.FirstOrDefault()?.Item2.ToString(); - ConfigGateway = info.IPv4Gateway?.Any() == true ? info.IPv4Gateway.FirstOrDefault()?.ToString() : string.Empty; - } - - if (info.DNSAutoconfigurationEnabled) - { - ConfigEnableDynamicDNS = true; - } - else - { - ConfigEnableStaticDNS = true; + ConfigEnableStaticIPAddress = true; + ConfigIPAddress = info.IPv4Address.FirstOrDefault()?.Item1.ToString(); + ConfigSubnetmaskOrCidr = info.IPv4Address.FirstOrDefault()?.Item2.ToString(); + ConfigGateway = info.IPv4Gateway?.Any() == true ? info.IPv4Gateway.FirstOrDefault()?.ToString() : string.Empty; + } - var dnsServers = info.DNSServer.Where(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToList(); - ConfigPrimaryDNSServer = dnsServers.Count > 0 ? dnsServers[0].ToString() : string.Empty; - ConfigSecondaryDNSServer = dnsServers.Count > 1 ? dnsServers[1].ToString() : string.Empty; - } + if (info.DNSAutoconfigurationEnabled) + { + ConfigEnableDynamicDNS = true; } - - public async Task ApplyConfiguration() + else { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + ConfigEnableStaticDNS = true; - var subnetmask = ConfigSubnetmaskOrCidr; + var dnsServers = info.DNSServer.Where(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToList(); + ConfigPrimaryDNSServer = dnsServers.Count > 0 ? dnsServers[0].ToString() : string.Empty; + ConfigSecondaryDNSServer = dnsServers.Count > 1 ? dnsServers[1].ToString() : string.Empty; + } + } + + public async Task ApplyConfiguration() + { + IsConfigurationRunning = true; + IsStatusMessageDisplayed = false; - // CIDR to subnetmask - if (ConfigEnableStaticIPAddress && subnetmask.StartsWith("/")) - subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; + var subnetmask = ConfigSubnetmaskOrCidr; - // If primary and secondary DNS are empty --> autoconfiguration - if (ConfigEnableStaticDNS && string.IsNullOrEmpty(ConfigPrimaryDNSServer) && string.IsNullOrEmpty(ConfigSecondaryDNSServer)) - ConfigEnableDynamicDNS = true; + // CIDR to subnetmask + if (ConfigEnableStaticIPAddress && subnetmask.StartsWith("/")) + subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; - // When primary DNS is empty, swap it with secondary (if not empty) - if (ConfigEnableStaticDNS && string.IsNullOrEmpty(ConfigPrimaryDNSServer) && !string.IsNullOrEmpty(ConfigSecondaryDNSServer)) - { - ConfigPrimaryDNSServer = ConfigSecondaryDNSServer; - ConfigSecondaryDNSServer = string.Empty; - } + // If primary and secondary DNS are empty --> autoconfiguration + if (ConfigEnableStaticDNS && string.IsNullOrEmpty(ConfigPrimaryDNSServer) && string.IsNullOrEmpty(ConfigSecondaryDNSServer)) + ConfigEnableDynamicDNS = true; - var config = new NetworkInterfaceConfig - { - Name = SelectedNetworkInterface.Name, - EnableStaticIPAddress = ConfigEnableStaticIPAddress, - IPAddress = ConfigIPAddress, - Subnetmask = subnetmask, - Gateway = ConfigGateway, - EnableStaticDNS = ConfigEnableStaticDNS, - PrimaryDNSServer = ConfigPrimaryDNSServer, - SecondaryDNSServer = ConfigSecondaryDNSServer - }; + // When primary DNS is empty, swap it with secondary (if not empty) + if (ConfigEnableStaticDNS && string.IsNullOrEmpty(ConfigPrimaryDNSServer) && !string.IsNullOrEmpty(ConfigSecondaryDNSServer)) + { + ConfigPrimaryDNSServer = ConfigSecondaryDNSServer; + ConfigSecondaryDNSServer = string.Empty; + } - try - { - var networkInterface = new Models.Network.NetworkInterface(); + var config = new NetworkInterfaceConfig + { + Name = SelectedNetworkInterface.Name, + EnableStaticIPAddress = ConfigEnableStaticIPAddress, + IPAddress = ConfigIPAddress, + Subnetmask = subnetmask, + Gateway = ConfigGateway, + EnableStaticDNS = ConfigEnableStaticDNS, + PrimaryDNSServer = ConfigPrimaryDNSServer, + SecondaryDNSServer = ConfigSecondaryDNSServer + }; - networkInterface.UserHasCanceled += NetworkInterface_UserHasCanceled; + try + { + var networkInterface = new Models.Network.NetworkInterface(); - await networkInterface.ConfigureNetworkInterfaceAsync(config); + networkInterface.UserHasCanceled += NetworkInterface_UserHasCanceled; - ReloadNetworkInterfaces(); - } - catch (Exception ex) - { - StatusMessage = ex.Message; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } - } + await networkInterface.ConfigureNetworkInterfaceAsync(config); - public async Task ApplyConfigurationFromProfile() + ReloadNetworkInterfaces(); + } + catch (Exception ex) { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; + } + finally + { + IsConfigurationRunning = false; + } + } - var subnetmask = SelectedProfile.NetworkInterface_SubnetmaskOrCidr; + public async Task ApplyConfigurationFromProfile() + { + IsConfigurationRunning = true; + IsStatusMessageDisplayed = false; - // CIDR to subnetmask - if (SelectedProfile.NetworkInterface_EnableStaticIPAddress && subnetmask.StartsWith("/")) - subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; + var subnetmask = SelectedProfile.NetworkInterface_SubnetmaskOrCidr; - var enableStaticDNS = SelectedProfile.NetworkInterface_EnableStaticDNS; + // CIDR to subnetmask + if (SelectedProfile.NetworkInterface_EnableStaticIPAddress && subnetmask.StartsWith("/")) + subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; - var primaryDNSServer = SelectedProfile.NetworkInterface_PrimaryDNSServer; - var secondaryDNSServer = SelectedProfile.NetworkInterface_SecondaryDNSServer; + var enableStaticDNS = SelectedProfile.NetworkInterface_EnableStaticDNS; - // If primary and secondary DNS are empty --> autoconfiguration - if (enableStaticDNS && string.IsNullOrEmpty(primaryDNSServer) && string.IsNullOrEmpty(secondaryDNSServer)) - enableStaticDNS = false; + var primaryDNSServer = SelectedProfile.NetworkInterface_PrimaryDNSServer; + var secondaryDNSServer = SelectedProfile.NetworkInterface_SecondaryDNSServer; - // When primary DNS is empty, swap it with secondary (if not empty) - if (SelectedProfile.NetworkInterface_EnableStaticDNS && string.IsNullOrEmpty(primaryDNSServer) && !string.IsNullOrEmpty(secondaryDNSServer)) - { - primaryDNSServer = secondaryDNSServer; - secondaryDNSServer = string.Empty; - } + // If primary and secondary DNS are empty --> autoconfiguration + if (enableStaticDNS && string.IsNullOrEmpty(primaryDNSServer) && string.IsNullOrEmpty(secondaryDNSServer)) + enableStaticDNS = false; - var config = new NetworkInterfaceConfig - { - Name = SelectedNetworkInterface.Name, - EnableStaticIPAddress = SelectedProfile.NetworkInterface_EnableStaticIPAddress, - IPAddress = SelectedProfile.NetworkInterface_IPAddress, - Subnetmask = subnetmask, - Gateway = SelectedProfile.NetworkInterface_Gateway, - EnableStaticDNS = enableStaticDNS, - PrimaryDNSServer = primaryDNSServer, - SecondaryDNSServer = secondaryDNSServer - }; + // When primary DNS is empty, swap it with secondary (if not empty) + if (SelectedProfile.NetworkInterface_EnableStaticDNS && string.IsNullOrEmpty(primaryDNSServer) && !string.IsNullOrEmpty(secondaryDNSServer)) + { + primaryDNSServer = secondaryDNSServer; + secondaryDNSServer = string.Empty; + } - try - { - var networkInterface = new Models.Network.NetworkInterface(); + var config = new NetworkInterfaceConfig + { + Name = SelectedNetworkInterface.Name, + EnableStaticIPAddress = SelectedProfile.NetworkInterface_EnableStaticIPAddress, + IPAddress = SelectedProfile.NetworkInterface_IPAddress, + Subnetmask = subnetmask, + Gateway = SelectedProfile.NetworkInterface_Gateway, + EnableStaticDNS = enableStaticDNS, + PrimaryDNSServer = primaryDNSServer, + SecondaryDNSServer = secondaryDNSServer + }; - networkInterface.UserHasCanceled += NetworkInterface_UserHasCanceled; + try + { + var networkInterface = new Models.Network.NetworkInterface(); - await networkInterface.ConfigureNetworkInterfaceAsync(config); + networkInterface.UserHasCanceled += NetworkInterface_UserHasCanceled; - ReloadNetworkInterfaces(); - } - catch (Exception ex) - { - StatusMessage = ex.Message; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } + await networkInterface.ConfigureNetworkInterfaceAsync(config); + + ReloadNetworkInterfaces(); + } + catch (Exception ex) + { + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; + } + finally + { + IsConfigurationRunning = false; } + } - private async Task OpenNetworkConnectionsAsync() + private async Task OpenNetworkConnectionsAsync() + { + try { - try + ProcessStartInfo info = new() { - ProcessStartInfo info = new() - { - FileName = "NCPA.cpl", - UseShellExecute = true - }; + FileName = "NCPA.cpl", + UseShellExecute = true + }; - Process.Start(info); - } - catch (Exception ex) - { - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); - } + Process.Start(info); } - - private async Task FlushDNSAsync() + catch (Exception ex) { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); + } + } + + private async Task FlushDNSAsync() + { + IsConfigurationRunning = true; + IsStatusMessageDisplayed = false; - await Models.Network.NetworkInterface.FlushDnsAsync(); + await Models.Network.NetworkInterface.FlushDnsAsync(); - IsConfigurationRunning = false; - } + IsConfigurationRunning = false; + } - private async Task ReleaseRenewAsync(IPConfigReleaseRenewMode releaseRenewMode) - { - IsConfigurationRunning = true; + private async Task ReleaseRenewAsync(IPConfigReleaseRenewMode releaseRenewMode) + { + IsConfigurationRunning = true; - await Models.Network.NetworkInterface.ReleaseRenewAsync(releaseRenewMode, SelectedNetworkInterface.Name); + await Models.Network.NetworkInterface.ReleaseRenewAsync(releaseRenewMode, SelectedNetworkInterface.Name); - ReloadNetworkInterfaces(); + ReloadNetworkInterfaces(); - IsConfigurationRunning = false; - } - - public async Task AddIPv4Address(string ipAddress, string subnetmaskOrCidr) - { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + IsConfigurationRunning = false; + } + + public async Task AddIPv4Address(string ipAddress, string subnetmaskOrCidr) + { + IsConfigurationRunning = true; + IsStatusMessageDisplayed = false; - var subnetmask = subnetmaskOrCidr; + var subnetmask = subnetmaskOrCidr; - // CIDR to subnetmask - if (subnetmask.StartsWith("/")) - subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; + // CIDR to subnetmask + if (subnetmask.StartsWith("/")) + subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; - var config = new NetworkInterfaceConfig - { - Name = SelectedNetworkInterface.Name, - IPAddress = ipAddress, - Subnetmask = subnetmask - }; + var config = new NetworkInterfaceConfig + { + Name = SelectedNetworkInterface.Name, + IPAddress = ipAddress, + Subnetmask = subnetmask + }; - try - { - await Models.Network.NetworkInterface.AddIPAddressToNetworkInterfaceAsync(config); + try + { + await Models.Network.NetworkInterface.AddIPAddressToNetworkInterfaceAsync(config); - ReloadNetworkInterfaces(); - } - catch (Exception ex) - { - StatusMessage = ex.Message; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } + ReloadNetworkInterfaces(); } - - public async Task RemoveIPv4Address(string ipAddress) + catch (Exception ex) { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; + } + finally + { + IsConfigurationRunning = false; + } + } - var config = new NetworkInterfaceConfig - { - Name = SelectedNetworkInterface.Name, - IPAddress = ipAddress - }; + public async Task RemoveIPv4Address(string ipAddress) + { + IsConfigurationRunning = true; + IsStatusMessageDisplayed = false; - try - { - await Models.Network.NetworkInterface.RemoveIPAddressFromNetworkInterfaceAsync(config); + var config = new NetworkInterfaceConfig + { + Name = SelectedNetworkInterface.Name, + IPAddress = ipAddress + }; - ReloadNetworkInterfaces(); - } - catch (Exception ex) - { - StatusMessage = ex.Message; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } + try + { + await Models.Network.NetworkInterface.RemoveIPAddressFromNetworkInterfaceAsync(config); + + ReloadNetworkInterfaces(); + } + catch (Exception ex) + { + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; + } + finally + { + IsConfigurationRunning = false; } + } - private void StartDelayedSearch() + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void ResetBandwidthChart() - { - if (Series == null) - return; + _canProfileWidthChange = true; + } - Series[0].Values.Clear(); - Series[1].Values.Clear(); + public void ResetBandwidthChart() + { + if (Series == null) + return; - var currentDateTime = DateTime.Now; + Series[0].Values.Clear(); + Series[1].Values.Clear(); - for (var i = 60; i > 0; i--) - { - var bandwidthInfo = new LvlChartsDefaultInfo(currentDateTime.AddSeconds(-i), double.NaN); + var currentDateTime = DateTime.Now; - Series[0].Values.Add(bandwidthInfo); - Series[1].Values.Add(bandwidthInfo); - } + for (var i = 60; i > 0; i--) + { + var bandwidthInfo = new LvlChartsDefaultInfo(currentDateTime.AddSeconds(-i), double.NaN); + + Series[0].Values.Add(bandwidthInfo); + Series[1].Values.Add(bandwidthInfo); } - - private bool _resetBandwidthStatisticOnNextUpdate; + } + + private bool _resetBandwidthStatisticOnNextUpdate; + + private void StartBandwidthMeter(string networkInterfaceId) + { + // Reset chart + ResetBandwidthChart(); + + // Reset statistic + _resetBandwidthStatisticOnNextUpdate = true; - private void StartBandwidthMeter(string networkInterfaceId) + _bandwidthMeter = new BandwidthMeter(networkInterfaceId); + _bandwidthMeter.UpdateSpeed += BandwidthMeter_UpdateSpeed; + _bandwidthMeter.Start(); + } + + private void ResumeBandwidthMeter() + { + if (_bandwidthMeter != null && !_bandwidthMeter.IsRunning) { - // Reset chart ResetBandwidthChart(); - // Reset statistic _resetBandwidthStatisticOnNextUpdate = true; - _bandwidthMeter = new BandwidthMeter(networkInterfaceId); - _bandwidthMeter.UpdateSpeed += BandwidthMeter_UpdateSpeed; _bandwidthMeter.Start(); } + } - private void ResumeBandwidthMeter() - { - if (_bandwidthMeter != null && !_bandwidthMeter.IsRunning) - { - ResetBandwidthChart(); + private void StopBandwidthMeter() + { + if (_bandwidthMeter != null && _bandwidthMeter.IsRunning) + _bandwidthMeter.Stop(); + } - _resetBandwidthStatisticOnNextUpdate = true; + public void OnViewVisible() + { + _isViewActive = true; - _bandwidthMeter.Start(); - } - } + RefreshProfiles(); - private void StopBandwidthMeter() - { - if (_bandwidthMeter != null && _bandwidthMeter.IsRunning) - _bandwidthMeter.Stop(); - } + ResumeBandwidthMeter(); + } - public void OnViewVisible() - { - _isViewActive = true; + public void OnViewHide() + { + StopBandwidthMeter(); - RefreshProfiles(); + _isViewActive = false; + } - ResumeBandwidthMeter(); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnViewHide() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - StopBandwidthMeter(); - - _isViewActive = false; - } + Profiles.Refresh(); + })); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnProfileDialogOpen() + { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + } - public void OnProfileDialogOpen() - { + public void OnProfileDialogClose() + { - } + } + #endregion - public void OnProfileDialogClose() - { + #region Events + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } - } - #endregion + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); + } - #region Events - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + private void BandwidthMeter_UpdateSpeed(object sender, BandwidthMeterSpeedArgs e) + { + // Reset statistics + if(_resetBandwidthStatisticOnNextUpdate) { - RefreshProfiles(); - } + BandwidthStartTime = DateTime.Now; + _bandwidthTotalBytesReceivedTemp = e.TotalBytesReceived; + _bandwidthTotalBytesSentTemp = e.TotalBytesSent; - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); + _resetBandwidthStatisticOnNextUpdate = false; } - private void BandwidthMeter_UpdateSpeed(object sender, BandwidthMeterSpeedArgs e) - { - // Reset statistics - if(_resetBandwidthStatisticOnNextUpdate) - { - BandwidthStartTime = DateTime.Now; - _bandwidthTotalBytesReceivedTemp = e.TotalBytesReceived; - _bandwidthTotalBytesSentTemp = e.TotalBytesSent; - - _resetBandwidthStatisticOnNextUpdate = false; - } + // Measured time + BandwidthMeasuredTime = DateTime.Now - BandwidthStartTime; - // Measured time - BandwidthMeasuredTime = DateTime.Now - BandwidthStartTime; + // Current download/upload + BandwidthTotalBytesReceived = e.TotalBytesReceived; + BandwidthTotalBytesSent = e.TotalBytesSent; + BandwidthBytesReceivedSpeed = e.ByteReceivedSpeed; + BandwidthBytesSentSpeed = e.ByteSentSpeed; - // Current download/upload - BandwidthTotalBytesReceived = e.TotalBytesReceived; - BandwidthTotalBytesSent = e.TotalBytesSent; - BandwidthBytesReceivedSpeed = e.ByteReceivedSpeed; - BandwidthBytesSentSpeed = e.ByteSentSpeed; + // Total download/upload + BandwidthDiffBytesReceived = BandwidthTotalBytesReceived - _bandwidthTotalBytesReceivedTemp; + BandwidthDiffBytesSent = BandwidthTotalBytesSent - _bandwidthTotalBytesSentTemp; - // Total download/upload - BandwidthDiffBytesReceived = BandwidthTotalBytesReceived - _bandwidthTotalBytesReceivedTemp; - BandwidthDiffBytesSent = BandwidthTotalBytesSent - _bandwidthTotalBytesSentTemp; + // Add chart entry + Series[0].Values.Add(new LvlChartsDefaultInfo(e.DateTime, e.ByteReceivedSpeed)); + Series[1].Values.Add(new LvlChartsDefaultInfo(e.DateTime, e.ByteSentSpeed)); - // Add chart entry - Series[0].Values.Add(new LvlChartsDefaultInfo(e.DateTime, e.ByteReceivedSpeed)); - Series[1].Values.Add(new LvlChartsDefaultInfo(e.DateTime, e.ByteSentSpeed)); + // Remove data older than 60 seconds + if (Series[0].Values.Count > 59) + Series[0].Values.RemoveAt(0); - // Remove data older than 60 seconds - if (Series[0].Values.Count > 59) - Series[0].Values.RemoveAt(0); - - if (Series[1].Values.Count > 59) - Series[1].Values.RemoveAt(0); - } + if (Series[1].Values.Count > 59) + Series[1].Values.RemoveAt(0); + } - private void NetworkInterface_UserHasCanceled(object sender, EventArgs e) - { - StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; - IsStatusMessageDisplayed = true; - } + private void NetworkInterface_UserHasCanceled(object sender, EventArgs e) + { + StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; + IsStatusMessageDisplayed = true; + } - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - } - #endregion + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { } + #endregion } diff --git a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs index 9cf04a68c2..5b4d499c8d 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs @@ -17,539 +17,538 @@ using System.Collections.Generic; using NETworkManager.Models; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PingMonitorHostViewModel : ViewModelBase, IProfileManager { - public class PingMonitorHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; + if (value == _host) + return; - _host = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } + } - public ICollectionView HostHistoryView { get; } + public ICollectionView HostHistoryView { get; } - private bool _isRunning; - public bool IsRunning + private bool _isRunning; + public bool IsRunning + { + get => _isRunning; + set { - get => _isRunning; - set - { - if (value == _isRunning) - return; + if (value == _isRunning) + return; - _isRunning = value; - OnPropertyChanged(); - } + _isRunning = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } + } - private ObservableCollection _hosts = new(); - public ObservableCollection Hosts + private ObservableCollection _hosts = new(); + public ObservableCollection Hosts + { + get => _hosts; + set { - get => _hosts; - set - { - if (value != null && value == _hosts) - return; + if (value != null && value == _hosts) + return; - _hosts = value; - } + _hosts = value; } + } - public ICollectionView HostsView { get; } + public ICollectionView HostsView { get; } - private PingMonitorView _selectedHost; - public PingMonitorView SelectedHost + private PingMonitorView _selectedHost; + public PingMonitorView SelectedHost + { + get => _selectedHost; + set { - get => _selectedHost; - set - { - if (value == _selectedHost) - return; + if (value == _selectedHost) + return; - _selectedHost = value; - OnPropertyChanged(); - } + _selectedHost = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile; - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile; + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.PingMonitor_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.PingMonitor_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.PingMonitor_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.PingMonitor_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public PingMonitorHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public PingMonitorHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - // Host history - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PingMonitor_HostHistory); + // Host history + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PingMonitor_HostHistory); - // Hosts - HostsView = CollectionViewSource.GetDefaultView(Hosts); + // Hosts + HostsView = CollectionViewSource.GetDefaultView(Hosts); - // Profiles - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + // Profiles + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.PingMonitor_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.PingMonitor_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.PingMonitor_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.PingMonitor_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, Ping_Host - return info.PingMonitor_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PingMonitor_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, Ping_Host + return info.PingMonitor_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PingMonitor_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PingMonitor_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PingMonitor_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.PingMonitor_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.PingMonitor_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PingMonitor_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PingMonitor_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.PingMonitor_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.PingMonitor_ProfileWidth; + } + #endregion - #region ICommands & Actions - public ICommand AddHostCommand => new RelayCommand(p => AddHostAction()); + #region ICommands & Actions + public ICommand AddHostCommand => new RelayCommand(p => AddHostAction()); - private void AddHostAction() - { - AddHost(Host); + private void AddHostAction() + { + AddHost(Host); - // Add the hostname or ip address to the history - AddHostToHistory(Host); + // Add the hostname or ip address to the history + AddHostToHistory(Host); - Host = ""; - } + Host = ""; + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private void ExportAction() - { - if (SelectedHost != null) - SelectedHost.Export(); - } + private void ExportAction() + { + if (SelectedHost != null) + SelectedHost.Export(); + } - public ICommand AddHostProfileCommand => new RelayCommand(p => AddHostProfileAction(), AddHostProfile_CanExecute); + public ICommand AddHostProfileCommand => new RelayCommand(p => AddHostProfileAction(), AddHostProfile_CanExecute); - private bool AddHostProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool AddHostProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void AddHostProfileAction() - { - AddHost(SelectedProfile.PingMonitor_Host); - } + private void AddHostProfileAction() + { + AddHost(SelectedProfile.PingMonitor_Host); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PingMonitor); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PingMonitor); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } - #endregion + private void ClearSearchAction() + { + Search = string.Empty; + } + #endregion - #region Methods - public void AddHost(string hosts) - { - IsStatusMessageDisplayed = false; - StatusMessage = string.Empty; + #region Methods + public void AddHost(string hosts) + { + IsStatusMessageDisplayed = false; + StatusMessage = string.Empty; - IsRunning = true; + IsRunning = true; - Task.Run(() => + Task.Run(() => + { + Parallel.ForEach(hosts.Split(';'), currentHost => { - Parallel.ForEach(hosts.Split(';'), currentHost => - { - var host = currentHost.Trim(); - string hostname = string.Empty; - - // Resolve ip address from hostname - if (!IPAddress.TryParse(host, out var ipAddress)) - { - hostname = host; + var host = currentHost.Trim(); + string hostname = string.Empty; - using var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(host, SettingsManager.Current.Network_ResolveHostnamePreferIPv4); + // Resolve ip address from hostname + if (!IPAddress.TryParse(host, out var ipAddress)) + { + hostname = host; - // Wait for task inside a Parallel.Foreach - dnsResolverTask.Wait(); + using var dnsResolverTask = DNSClientHelper.ResolveAorAaaaAsync(host, SettingsManager.Current.Network_ResolveHostnamePreferIPv4); - if (dnsResolverTask.Result.HasError) - { - StatusMessageShowOrAdd(host, dnsResolverTask.Result); - return; - } + // Wait for task inside a Parallel.Foreach + dnsResolverTask.Wait(); - ipAddress = dnsResolverTask.Result.Value; + if (dnsResolverTask.Result.HasError) + { + StatusMessageShowOrAdd(host, dnsResolverTask.Result); + return; } - // Resolve hostname from ip address - else - { - using var dnsResolverTask = DNSClient.GetInstance().ResolvePtrAsync(ipAddress); + ipAddress = dnsResolverTask.Result.Value; + } - // Wait for task inside a Parallel.Foreach - dnsResolverTask.Wait(); + // Resolve hostname from ip address + else + { + using var dnsResolverTask = DNSClient.GetInstance().ResolvePtrAsync(ipAddress); - // Hostname is not necessary for ping. Don't show an error message in the UI. - if (!dnsResolverTask.Result.HasError) - hostname = dnsResolverTask.Result.Value; - } + // Wait for task inside a Parallel.Foreach + dnsResolverTask.Wait(); - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Hosts.Add(new PingMonitorView(Guid.NewGuid(), RemoveHost, new PingMonitorOptions(hostname, ipAddress))); - })); - }); + // Hostname is not necessary for ping. Don't show an error message in the UI. + if (!dnsResolverTask.Result.HasError) + hostname = dnsResolverTask.Result.Value; + } - IsRunning = false; + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate + { + Hosts.Add(new PingMonitorView(Guid.NewGuid(), RemoveHost, new PingMonitorOptions(hostname, ipAddress))); + })); }); - } - private void RemoveHost(Guid hostId) - { - var index = -1; + IsRunning = false; + }); + } - foreach (var host in Hosts) - { - if (host.HostId.Equals(hostId)) - index = Hosts.IndexOf(host); - } + private void RemoveHost(Guid hostId) + { + var index = -1; - if (index != -1) - { - Hosts[index].CloseView(); - Hosts.RemoveAt(index); - } + foreach (var host in Hosts) + { + if (host.HostId.Equals(hostId)) + index = Hosts.IndexOf(host); } - private void AddHostToHistory(string host) + if (index != -1) { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.PingMonitor_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); + Hosts[index].CloseView(); + Hosts.RemoveAt(index); + } + } + + private void AddHostToHistory(string host) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.PingMonitor_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.PingMonitor_HostHistory.Clear(); - OnPropertyChanged(nameof(Host)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.PingMonitor_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.PingMonitor_HostHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.PingMonitor_HostHistory.Add(x)); + } - private void StartDelayedSearch() + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void OnViewVisible() - { - _isViewActive = true; + _canProfileWidthChange = true; + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Profiles.Refresh(); + })); + } - } + public void OnProfileDialogOpen() + { - public void OnProfileDialogClose() - { + } - } + public void OnProfileDialogClose() + { + + } - /// - /// Method to display the status message and append messages related to . - /// - /// Host which should be resolved. - /// Information about the error that occurred in the query. - private void StatusMessageShowOrAdd(string host, DNSClientResult result) + /// + /// Method to display the status message and append messages related to . + /// + /// Host which should be resolved. + /// Information about the error that occurred in the query. + private void StatusMessageShowOrAdd(string host, DNSClientResult result) + { + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate + // Show the message + if (!IsStatusMessageDisplayed) { - // Show the message - if (!IsStatusMessageDisplayed) - { - StatusMessage = DNSClientHelper.FormatDNSClientResultError(host, result); - IsStatusMessageDisplayed = true; + StatusMessage = DNSClientHelper.FormatDNSClientResultError(host, result); + IsStatusMessageDisplayed = true; - return; - } + return; + } - // Append the message - StatusMessage += Environment.NewLine + DNSClientHelper.FormatDNSClientResultError(host, result); - })); - } - #endregion + // Append the message + StatusMessage += Environment.NewLine + DNSClientHelper.FormatDNSClientResultError(host, result); + })); + } + #endregion - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } diff --git a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs index ed2f32da6b..7042128564 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs @@ -1,116 +1,115 @@ using NETworkManager.Settings; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PingMonitorSettingsViewModel : ViewModelBase { - public class PingMonitorSettingsViewModel : ViewModelBase + #region Variables + private readonly bool _isLoading; + + private int _timeout; + public int Timeout { - #region Variables - private readonly bool _isLoading; - - private int _timeout; - public int Timeout + get => _timeout; + set { - get => _timeout; - set - { - if (value == _timeout) - return; - - if (!_isLoading) - SettingsManager.Current.PingMonitor_Timeout = value; - - _timeout = value; - OnPropertyChanged(); - } - } + if (value == _timeout) + return; - private int _buffer; - public int Buffer - { - get => _buffer; - set - { - if (value == _buffer) - return; - - if (!_isLoading) - SettingsManager.Current.PingMonitor_Buffer = value; - - _buffer = value; - OnPropertyChanged(); - } + if (!_isLoading) + SettingsManager.Current.PingMonitor_Timeout = value; + + _timeout = value; + OnPropertyChanged(); } + } - private int _ttl; - public int TTL + private int _buffer; + public int Buffer + { + get => _buffer; + set { - get => _ttl; - set - { - if (value == _ttl) - return; - - if (!_isLoading) - SettingsManager.Current.PingMonitor_TTL = value; - - _ttl = value; - OnPropertyChanged(); - } + if (value == _buffer) + return; + + if (!_isLoading) + SettingsManager.Current.PingMonitor_Buffer = value; + + _buffer = value; + OnPropertyChanged(); } + } - private bool _dontFragment; - public bool DontFragment + private int _ttl; + public int TTL + { + get => _ttl; + set { - get => _dontFragment; - set - { - if (value == _dontFragment) - return; - - if (!_isLoading) - SettingsManager.Current.PingMonitor_DontFragment = value; - - _dontFragment = value; - OnPropertyChanged(); - } + if (value == _ttl) + return; + + if (!_isLoading) + SettingsManager.Current.PingMonitor_TTL = value; + + _ttl = value; + OnPropertyChanged(); } + } - private int _waitTime; - public int WaitTime + private bool _dontFragment; + public bool DontFragment + { + get => _dontFragment; + set { - get => _waitTime; - set - { - if (value == _waitTime) - return; - - if (!_isLoading) - SettingsManager.Current.PingMonitor_WaitTime = value; - - _waitTime = value; - OnPropertyChanged(); - } + if (value == _dontFragment) + return; + + if (!_isLoading) + SettingsManager.Current.PingMonitor_DontFragment = value; + + _dontFragment = value; + OnPropertyChanged(); } - #endregion + } - #region Contructor, load settings - public PingMonitorSettingsViewModel() + private int _waitTime; + public int WaitTime + { + get => _waitTime; + set { - _isLoading = true; + if (value == _waitTime) + return; - LoadSettings(); + if (!_isLoading) + SettingsManager.Current.PingMonitor_WaitTime = value; - _isLoading = false; + _waitTime = value; + OnPropertyChanged(); } + } + #endregion - private void LoadSettings() - { - Timeout = SettingsManager.Current.PingMonitor_Timeout; - Buffer = SettingsManager.Current.PingMonitor_Buffer; - TTL = SettingsManager.Current.PingMonitor_TTL; - DontFragment = SettingsManager.Current.PingMonitor_DontFragment; - WaitTime = SettingsManager.Current.PingMonitor_WaitTime; - } - #endregion + #region Contructor, load settings + public PingMonitorSettingsViewModel() + { + _isLoading = true; + + LoadSettings(); + + _isLoading = false; + } + + private void LoadSettings() + { + Timeout = SettingsManager.Current.PingMonitor_Timeout; + Buffer = SettingsManager.Current.PingMonitor_Buffer; + TTL = SettingsManager.Current.PingMonitor_TTL; + DontFragment = SettingsManager.Current.PingMonitor_DontFragment; + WaitTime = SettingsManager.Current.PingMonitor_WaitTime; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs index 95a31c4a8d..4385620a45 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs @@ -17,397 +17,396 @@ using System.Collections.ObjectModel; using System.Threading.Tasks; -namespace NETworkManager.ViewModels -{ - public class PingMonitorViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private CancellationTokenSource _cancellationTokenSource; +namespace NETworkManager.ViewModels; - public readonly Guid HostId; - private readonly Action _closeCallback; - private readonly PingMonitorOptions _pingMonitorOptions; - private bool _firstLoad = true; +public class PingMonitorViewModel : ViewModelBase +{ + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private CancellationTokenSource _cancellationTokenSource; - private List _pingInfoList; + public readonly Guid HostId; + private readonly Action _closeCallback; + private readonly PingMonitorOptions _pingMonitorOptions; + private bool _firstLoad = true; - private string _host; - public string Host - { - get => _host; - set - { - if (value == _host) - return; + private List _pingInfoList; - _host = value; - OnPropertyChanged(); - } - } - - private IPAddress _ipAddress; - public IPAddress IPAddress + private string _host; + public string Host + { + get => _host; + set { - get => _ipAddress; - set - { - if (value == _ipAddress) - return; + if (value == _host) + return; - _ipAddress = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } + } - private bool _isRunning; - public bool IsRunning + private IPAddress _ipAddress; + public IPAddress IPAddress + { + get => _ipAddress; + set { - get => _isRunning; - set - { - if (value == _isRunning) - return; + if (value == _ipAddress) + return; - _isRunning = value; - OnPropertyChanged(); - } + _ipAddress = value; + OnPropertyChanged(); } + } - private bool _isReachable; - public bool IsReachable + private bool _isRunning; + public bool IsRunning + { + get => _isRunning; + set { - get => _isReachable; - set - { - if (value == _isReachable) - return; + if (value == _isRunning) + return; - _isReachable = value; - OnPropertyChanged(); - } + _isRunning = value; + OnPropertyChanged(); } + } - private DateTime _statusTime; - public DateTime StatusTime + private bool _isReachable; + public bool IsReachable + { + get => _isReachable; + set { - get => _statusTime; - set - { - if (value == _statusTime) - return; + if (value == _isReachable) + return; - _statusTime = value; - OnPropertyChanged(); - } + _isReachable = value; + OnPropertyChanged(); } + } - private int _transmitted; - public int Transmitted + private DateTime _statusTime; + public DateTime StatusTime + { + get => _statusTime; + set { - get => _transmitted; - set - { - if (value == _transmitted) - return; + if (value == _statusTime) + return; - _transmitted = value; - OnPropertyChanged(); - } + _statusTime = value; + OnPropertyChanged(); } + } - private int _received; - public int Received + private int _transmitted; + public int Transmitted + { + get => _transmitted; + set { - get => _received; - set - { - if (value == _received) - return; + if (value == _transmitted) + return; - _received = value; - OnPropertyChanged(); - } + _transmitted = value; + OnPropertyChanged(); } + } - private int _lost; - public int Lost + private int _received; + public int Received + { + get => _received; + set { - get => _lost; - set - { - if (value == _lost) - return; + if (value == _received) + return; - _lost = value; - OnPropertyChanged(); - } + _received = value; + OnPropertyChanged(); } + } - private void InitialTimeChart() + private int _lost; + public int Lost + { + get => _lost; + set { - var dayConfig = Mappers.Xy() - .X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromHours(1).Ticks) - .Y(dayModel => dayModel.Value); + if (value == _lost) + return; - Series = new SeriesCollection(dayConfig) - { - new LineSeries - { - Title = "Time", - Values = new ChartValues(), - PointGeometry = null - } - }; - - FormatterDate = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("hh:mm:ss"); - FormatterPingTime = value => $"{value} ms"; + _lost = value; + OnPropertyChanged(); } + } - public Func FormatterDate { get; set; } - public Func FormatterPingTime { get; set; } - public SeriesCollection Series { get; set; } + private void InitialTimeChart() + { + var dayConfig = Mappers.Xy() + .X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromHours(1).Ticks) + .Y(dayModel => dayModel.Value); - private string _errorMessage; - public string ErrorMessage + Series = new SeriesCollection(dayConfig) { - get => _errorMessage; - set + new LineSeries { - if (value == _errorMessage) - return; - - _errorMessage = value; - OnPropertyChanged(); + Title = "Time", + Values = new ChartValues(), + PointGeometry = null } - } + }; - private bool _isErrorMessageDisplayed; - public bool IsErrorMessageDisplayed - { - get => _isErrorMessageDisplayed; - set - { - if (value == _isErrorMessageDisplayed) - return; + FormatterDate = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("hh:mm:ss"); + FormatterPingTime = value => $"{value} ms"; + } - _isErrorMessageDisplayed = value; - OnPropertyChanged(); - } - } - #endregion + public Func FormatterDate { get; set; } + public Func FormatterPingTime { get; set; } + public SeriesCollection Series { get; set; } - #region Contructor, load settings - public PingMonitorViewModel(IDialogCoordinator instance, Guid hostId, Action closeCallback, PingMonitorOptions options) + private string _errorMessage; + public string ErrorMessage + { + get => _errorMessage; + set { - _dialogCoordinator = instance; - - HostId = hostId; - _closeCallback = closeCallback; - _pingMonitorOptions = options; - - Host = _pingMonitorOptions.Host; - IPAddress = _pingMonitorOptions.IPAddress; + if (value == _errorMessage) + return; - InitialTimeChart(); + _errorMessage = value; + OnPropertyChanged(); } + } - public void OnLoaded() + private bool _isErrorMessageDisplayed; + public bool IsErrorMessageDisplayed + { + get => _isErrorMessageDisplayed; + set { - if (!_firstLoad) + if (value == _isErrorMessageDisplayed) return; - StartPing(); - - _firstLoad = false; + _isErrorMessageDisplayed = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region ICommands & Actions - public ICommand PingCommand => new RelayCommand(p => PingAction()); + #region Contructor, load settings + public PingMonitorViewModel(IDialogCoordinator instance, Guid hostId, Action closeCallback, PingMonitorOptions options) + { + _dialogCoordinator = instance; - private void PingAction() - { - Ping(); - } + HostId = hostId; + _closeCallback = closeCallback; + _pingMonitorOptions = options; - public ICommand CloseCommand => new RelayCommand(p => CloseAction()); + Host = _pingMonitorOptions.Host; + IPAddress = _pingMonitorOptions.IPAddress; - private void CloseAction() - { - _closeCallback(HostId); - } - #endregion + InitialTimeChart(); + } - #region Methods - private void Ping() - { - if (IsRunning) - StopPing(); - else - StartPing(); - } + public void OnLoaded() + { + if (!_firstLoad) + return; - private void StartPing() - { - IsErrorMessageDisplayed = false; - IsRunning = true; + StartPing(); - // Reset history - _pingInfoList = new List(); + _firstLoad = false; + } + #endregion - // Reset the latest results - StatusTime = DateTime.Now; - Transmitted = 0; - Received = 0; - Lost = 0; + #region ICommands & Actions + public ICommand PingCommand => new RelayCommand(p => PingAction()); - // Reset chart - ResetTimeChart(); + private void PingAction() + { + Ping(); + } - _cancellationTokenSource = new CancellationTokenSource(); + public ICommand CloseCommand => new RelayCommand(p => CloseAction()); - var ping = new Ping - { - Timeout = SettingsManager.Current.PingMonitor_Timeout, - Buffer = new byte[SettingsManager.Current.PingMonitor_Buffer], - TTL = SettingsManager.Current.PingMonitor_TTL, - DontFragment = SettingsManager.Current.PingMonitor_DontFragment, - WaitTime = SettingsManager.Current.PingMonitor_WaitTime, - Hostname = Host - }; - - ping.PingReceived += Ping_PingReceived; - ping.PingException += Ping_PingException; - ping.UserHasCanceled += Ping_UserHasCanceled; - - ping.SendAsync(IPAddress, _cancellationTokenSource.Token); - } + private void CloseAction() + { + _closeCallback(HostId); + } + #endregion - private void StopPing() - { - _cancellationTokenSource?.Cancel(); - } + #region Methods + private void Ping() + { + if (IsRunning) + StopPing(); + else + StartPing(); + } - public void ResetTimeChart() - { - if (Series == null) - return; + private void StartPing() + { + IsErrorMessageDisplayed = false; + IsRunning = true; - Series[0].Values.Clear(); + // Reset history + _pingInfoList = new List(); - var currentDateTime = DateTime.Now; + // Reset the latest results + StatusTime = DateTime.Now; + Transmitted = 0; + Received = 0; + Lost = 0; - for (var i = 30; i > 0; i--) - { - var bandwidthInfo = new LvlChartsDefaultInfo(currentDateTime.AddSeconds(-i), double.NaN); + // Reset chart + ResetTimeChart(); - Series[0].Values.Add(bandwidthInfo); - } - } + _cancellationTokenSource = new CancellationTokenSource(); - public async Task Export() + var ping = new Ping { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + Timeout = SettingsManager.Current.PingMonitor_Timeout, + Buffer = new byte[SettingsManager.Current.PingMonitor_Buffer], + TTL = SettingsManager.Current.PingMonitor_TTL, + DontFragment = SettingsManager.Current.PingMonitor_DontFragment, + WaitTime = SettingsManager.Current.PingMonitor_WaitTime, + Hostname = Host + }; + + ping.PingReceived += Ping_PingReceived; + ping.PingException += Ping_PingException; + ping.UserHasCanceled += Ping_UserHasCanceled; + + ping.SendAsync(IPAddress, _cancellationTokenSource.Token); + } - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + private void StopPing() + { + _cancellationTokenSource?.Cancel(); + } - try - { - ExportManager.Export(instance.FilePath, instance.FileType, new ObservableCollection(_pingInfoList)); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + public void ResetTimeChart() + { + if (Series == null) + return; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + Series[0].Values.Clear(); - SettingsManager.Current.PingMonitor_ExportFileType = instance.FileType; - SettingsManager.Current.PingMonitor_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, false, SettingsManager.Current.PingMonitor_ExportFileType, SettingsManager.Current.PingMonitor_ExportFilePath); + var currentDateTime = DateTime.Now; - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + for (var i = 30; i > 0; i--) + { + var bandwidthInfo = new LvlChartsDefaultInfo(currentDateTime.AddSeconds(-i), double.NaN); - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + Series[0].Values.Add(bandwidthInfo); } + } - public void OnClose() + public async Task Export() + { + var customDialog = new CustomDialog { - // Stop the ping - if (IsRunning) - StopPing(); - } - #endregion + Title = Localization.Resources.Strings.Export + }; - #region Events - private void Ping_PingReceived(object sender, PingReceivedArgs e) + var exportViewModel = new ExportViewModel(async instance => { - var pingInfo = PingInfo.Parse(e); + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - // Calculate statistics - Transmitted++; + try + { + ExportManager.Export(instance.FilePath, instance.FileType, new ObservableCollection(_pingInfoList)); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - LvlChartsDefaultInfo timeInfo; + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - if (pingInfo.Status == System.Net.NetworkInformation.IPStatus.Success) - { - if (!IsReachable) - { - StatusTime = DateTime.Now; - IsReachable = true; - } + SettingsManager.Current.PingMonitor_ExportFileType = instance.FileType; + SettingsManager.Current.PingMonitor_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, false, SettingsManager.Current.PingMonitor_ExportFileType, SettingsManager.Current.PingMonitor_ExportFilePath); - Received++; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - timeInfo = new LvlChartsDefaultInfo(pingInfo.Timestamp, pingInfo.Time); - } - else - { - if (IsReachable) - { - StatusTime = DateTime.Now; - IsReachable = false; - } + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - Lost++; + public void OnClose() + { + // Stop the ping + if (IsRunning) + StopPing(); + } + #endregion + + #region Events + private void Ping_PingReceived(object sender, PingReceivedArgs e) + { + var pingInfo = PingInfo.Parse(e); - timeInfo = new LvlChartsDefaultInfo(pingInfo.Timestamp, double.NaN); + // Calculate statistics + Transmitted++; + + LvlChartsDefaultInfo timeInfo; + + if (pingInfo.Status == System.Net.NetworkInformation.IPStatus.Success) + { + if (!IsReachable) + { + StatusTime = DateTime.Now; + IsReachable = true; } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate + Received++; + + timeInfo = new LvlChartsDefaultInfo(pingInfo.Timestamp, pingInfo.Time); + } + else + { + if (IsReachable) { - Series[0].Values.Add(timeInfo); + StatusTime = DateTime.Now; + IsReachable = false; + } - if (Series[0].Values.Count > 59) - Series[0].Values.RemoveAt(0); - })); + Lost++; - // Add to history - _pingInfoList.Add(pingInfo); + timeInfo = new LvlChartsDefaultInfo(pingInfo.Timestamp, double.NaN); } - private void Ping_UserHasCanceled(object sender, EventArgs e) + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - IsRunning = false; - } + Series[0].Values.Add(timeInfo); - private void Ping_PingException(object sender, PingExceptionArgs e) - { - IsRunning = false; + if (Series[0].Values.Count > 59) + Series[0].Values.RemoveAt(0); + })); - ErrorMessage = e.Message; - IsErrorMessageDisplayed = true; - } - #endregion + // Add to history + _pingInfoList.Add(pingInfo); + } + + private void Ping_UserHasCanceled(object sender, EventArgs e) + { + IsRunning = false; + } + + private void Ping_PingException(object sender, PingExceptionArgs e) + { + IsRunning = false; + + ErrorMessage = e.Message; + IsErrorMessageDisplayed = true; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PortProfileViewModel.cs b/Source/NETworkManager/ViewModels/PortProfileViewModel.cs index 0e680e9575..6319147ed5 100644 --- a/Source/NETworkManager/ViewModels/PortProfileViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortProfileViewModel.cs @@ -3,109 +3,108 @@ using System.Windows.Input; using NETworkManager.Models.Network; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PortProfileViewModel : ViewModelBase { - public class PortProfileViewModel : ViewModelBase - { - private readonly bool _isLoading; + private readonly bool _isLoading; - public ICommand SaveCommand { get; } + public ICommand SaveCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _name; - public string Name + private string _name; + public string Name + { + get => _name; + set { - get => _name; - set - { - if (_name == value) - return; + if (_name == value) + return; - _name = value; + _name = value; - if (!_isLoading) - Validate(); + if (!_isLoading) + Validate(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private string _ports; - public string Ports + private string _ports; + public string Ports + { + get => _ports; + set { - get => _ports; - set - { - if (_ports == value) - return; + if (_ports == value) + return; - _ports = value; + _ports = value; - if (!_isLoading) - Validate(); + if (!_isLoading) + Validate(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private readonly PortProfileInfo _info; + private readonly PortProfileInfo _info; - private string _previousPortAsString; + private string _previousPortAsString; - private bool _infoChanged; - public bool InfoChanged + private bool _infoChanged; + public bool InfoChanged + { + get => _infoChanged; + set { - get => _infoChanged; - set - { - if (value == _infoChanged) - return; - - _infoChanged = value; - OnPropertyChanged(); - } + if (value == _infoChanged) + return; + + _infoChanged = value; + OnPropertyChanged(); } + } - private bool _isEdited; - public bool IsEdited + private bool _isEdited; + public bool IsEdited + { + get => _isEdited; + set { - get => _isEdited; - set - { - if (value == _isEdited) - return; - - _isEdited = value; - OnPropertyChanged(); - } + if (value == _isEdited) + return; + + _isEdited = value; + OnPropertyChanged(); } + } - public PortProfileViewModel(Action saveCommand, Action cancelHandler, bool isEdited = false, PortProfileInfo info = null) - { - _isLoading = true; + public PortProfileViewModel(Action saveCommand, Action cancelHandler, bool isEdited = false, PortProfileInfo info = null) + { + _isLoading = true; - SaveCommand = new RelayCommand(p => saveCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + SaveCommand = new RelayCommand(p => saveCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - IsEdited = isEdited; + IsEdited = isEdited; - _info = info ?? new PortProfileInfo(); + _info = info ?? new PortProfileInfo(); - Name = _info.Name; + Name = _info.Name; - // List to string - if (_info.Ports != null) - Ports = _info.Ports; + // List to string + if (_info.Ports != null) + Ports = _info.Ports; - _previousPortAsString = Ports; + _previousPortAsString = Ports; - _isLoading = false; - } + _isLoading = false; + } - public void Validate() - { - InfoChanged = _info.Name != Name || _previousPortAsString != Ports; - } + public void Validate() + { + InfoChanged = _info.Name != Name || _previousPortAsString != Ports; } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PortProfilesViewModel.cs b/Source/NETworkManager/ViewModels/PortProfilesViewModel.cs index 0aa0ea8664..70e65fecfa 100644 --- a/Source/NETworkManager/ViewModels/PortProfilesViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortProfilesViewModel.cs @@ -9,79 +9,78 @@ using System.Collections.Generic; using System.Linq; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PortProfilesViewModel : ViewModelBase { - public class PortProfilesViewModel : ViewModelBase - { - private readonly bool _isLoading; + private readonly bool _isLoading; - public ICommand OKCommand { get; } + public ICommand OKCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - PortProfiles.Refresh(); + PortProfiles.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - public ICollectionView PortProfiles { get; } + public ICollectionView PortProfiles { get; } - private IList _selectedPortProfiles = new ArrayList(); - public IList SelectedPortProfiles + private IList _selectedPortProfiles = new ArrayList(); + public IList SelectedPortProfiles + { + get => _selectedPortProfiles; + set { - get => _selectedPortProfiles; - set - { - if (Equals(value, _selectedPortProfiles)) - return; - - _selectedPortProfiles = value; - OnPropertyChanged(); - } + if (Equals(value, _selectedPortProfiles)) + return; + + _selectedPortProfiles = value; + OnPropertyChanged(); } + } - public PortProfilesViewModel(Action okCommand, Action cancelHandler) - { - _isLoading = true; + public PortProfilesViewModel(Action okCommand, Action cancelHandler) + { + _isLoading = true; - OKCommand = new RelayCommand(p => okCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + OKCommand = new RelayCommand(p => okCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - PortProfiles = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_PortProfiles); - PortProfiles.SortDescriptions.Add(new SortDescription(nameof(PortProfileInfo.Name), ListSortDirection.Ascending)); - PortProfiles.Filter = o => - { - if (string.IsNullOrEmpty(Search)) - return true; + PortProfiles = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_PortProfiles); + PortProfiles.SortDescriptions.Add(new SortDescription(nameof(PortProfileInfo.Name), ListSortDirection.Ascending)); + PortProfiles.Filter = o => + { + if (string.IsNullOrEmpty(Search)) + return true; - if (o is not PortProfileInfo info) - return false; + if (o is not PortProfileInfo info) + return false; - var search = Search.Trim(); + var search = Search.Trim(); - // Search: Name, Ports - return info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.Ports.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1; - }; + // Search: Name, Ports + return info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.Ports.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1; + }; - _isLoading = false; - } + _isLoading = false; + } - public List GetSelectedPortProfiles() - { - return new List(SelectedPortProfiles.Cast()); - } + public List GetSelectedPortProfiles() + { + return new List(SelectedPortProfiles.Cast()); } } diff --git a/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs b/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs index df8a8a9928..f4c167bd5f 100644 --- a/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortScannerHostViewModel.cs @@ -16,363 +16,362 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PortScannerHostViewModel : ViewModelBase, IProfileManager { - public class PortScannerHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private int _tabId; + private int _tabId; - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.PortScanner_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.PortScanner_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.PortScanner_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.PortScanner_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public PortScannerHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public PortScannerHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - InterTabClient = new DragablzInterTabClient(ApplicationName.PortScanner); + InterTabClient = new DragablzInterTabClient(ApplicationName.PortScanner); - TabItems = new ObservableCollection() - { - new DragablzTabItem(Localization.Resources.Strings.NewTab, new PortScannerView(_tabId), _tabId) - }; - - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + TabItems = new ObservableCollection() + { + new DragablzTabItem(Localization.Resources.Strings.NewTab, new PortScannerView(_tabId), _tabId) + }; + + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.PortScanner_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.PortScanner_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Name, PortScanner_Host - return info.PortScanner_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PortScanner_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PortScanner_Ports.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, PortScanner_Host + return info.PortScanner_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PortScanner_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PortScanner_Ports.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PortScanner_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PortScanner_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.PortScanner_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.PortScanner_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PortScanner_ProfileWidth) : new GridLength(40); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PortScanner_ProfileWidth) : new GridLength(40); - _tempProfileWidth = SettingsManager.Current.PortScanner_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.PortScanner_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); + #region ICommand & Actions + public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); - private void AddTabAction() - { - AddTab(); - } + private void AddTabAction() + { + AddTab(); + } - public ICommand ScanProfileCommand => new RelayCommand(p => ScanProfileAction(), ScanProfile_CanExecute); + public ICommand ScanProfileCommand => new RelayCommand(p => ScanProfileAction(), ScanProfile_CanExecute); - private bool ScanProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool ScanProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ScanProfileAction() - { - AddTab(SelectedProfile); - } + private void ScanProfileAction() + { + AddTab(SelectedProfile); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PortScanner); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PortScanner); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ItemActionCallback CloseItemCommand => CloseItemAction; + public ItemActionCallback CloseItemCommand => CloseItemAction; - private static void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as PortScannerView)?.CloseTab(); - } - #endregion + private static void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as PortScannerView)?.CloseTab(); + } + #endregion - #region Methods - private void StartDelayedSearch() + #region Methods + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } - if (dueToChangedSize) + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; + + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void AddTab(string host = null, string ports = null) - { - _tabId++; + _canProfileWidthChange = true; + } - TabItems.Add(new DragablzTabItem(string.IsNullOrEmpty(host) ? Localization.Resources.Strings.NewTab : host, new PortScannerView(_tabId, host, ports), _tabId)); + public void AddTab(string host = null, string ports = null) + { + _tabId++; - SelectedTabIndex = TabItems.Count - 1; - } + TabItems.Add(new DragablzTabItem(string.IsNullOrEmpty(host) ? Localization.Resources.Strings.NewTab : host, new PortScannerView(_tabId, host, ports), _tabId)); - public void AddTab(ProfileInfo profile) - { - AddTab(profile.PortScanner_Host, profile.PortScanner_Ports); - } + SelectedTabIndex = TabItems.Count - 1; + } - public void OnViewVisible() - { - _isViewActive = true; + public void AddTab(ProfileInfo profile) + { + AddTab(profile.PortScanner_Host, profile.PortScanner_Ports); + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Profiles.Refresh(); + })); + } - } + public void OnProfileDialogOpen() + { - public void OnProfileDialogClose() - { + } - } - #endregion + public void OnProfileDialogClose() + { - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PortScannerSettingsViewModel.cs b/Source/NETworkManager/ViewModels/PortScannerSettingsViewModel.cs index 5c105f98d8..d17e80114f 100644 --- a/Source/NETworkManager/ViewModels/PortScannerSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortScannerSettingsViewModel.cs @@ -8,242 +8,241 @@ using NETworkManager.Views; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PortScannerSettingsViewModel : ViewModelBase { - public class PortScannerSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - public ICollectionView PortProfiles { get; } + public ICollectionView PortProfiles { get; } - private PortProfileInfo _selectedPortProfile = new PortProfileInfo(); - public PortProfileInfo SelectedPortProfile + private PortProfileInfo _selectedPortProfile = new PortProfileInfo(); + public PortProfileInfo SelectedPortProfile + { + get => _selectedPortProfile; + set { - get => _selectedPortProfile; - set - { - if (value == _selectedPortProfile) - return; - - _selectedPortProfile = value; - OnPropertyChanged(); - } + if (value == _selectedPortProfile) + return; + _selectedPortProfile = value; + OnPropertyChanged(); } - private int _hostThreads; - public int HostThreads + } + + private int _hostThreads; + public int HostThreads + { + get => _hostThreads; + set { - get => _hostThreads; - set - { - if (value == _hostThreads) - return; + if (value == _hostThreads) + return; - if (!_isLoading) - SettingsManager.Current.PortScanner_HostThreads = value; + if (!_isLoading) + SettingsManager.Current.PortScanner_HostThreads = value; - _hostThreads = value; - OnPropertyChanged(); - } + _hostThreads = value; + OnPropertyChanged(); } + } - private int _portThreads; - public int PortThreads + private int _portThreads; + public int PortThreads + { + get => _portThreads; + set { - get => _portThreads; - set - { - if (value == _portThreads) - return; + if (value == _portThreads) + return; - if (!_isLoading) - SettingsManager.Current.PortScanner_PortThreads = value; + if (!_isLoading) + SettingsManager.Current.PortScanner_PortThreads = value; - _portThreads = value; - OnPropertyChanged(); - } + _portThreads = value; + OnPropertyChanged(); } + } - private bool _showClosed; - public bool ShowClosed + private bool _showClosed; + public bool ShowClosed + { + get => _showClosed; + set { - get => _showClosed; - set - { - if (value == _showClosed) - return; + if (value == _showClosed) + return; - if (!_isLoading) - SettingsManager.Current.PortScanner_ShowClosed = value; + if (!_isLoading) + SettingsManager.Current.PortScanner_ShowClosed = value; - _showClosed = value; - OnPropertyChanged(); - } + _showClosed = value; + OnPropertyChanged(); } + } - private int _timeout; - public int Timeout + private int _timeout; + public int Timeout + { + get => _timeout; + set { - get => _timeout; - set - { - if (value == _timeout) - return; + if (value == _timeout) + return; - if (!_isLoading) - SettingsManager.Current.PortScanner_Timeout = value; + if (!_isLoading) + SettingsManager.Current.PortScanner_Timeout = value; - _timeout = value; - OnPropertyChanged(); - } + _timeout = value; + OnPropertyChanged(); } + } - private bool _resolveHostname; - public bool ResolveHostname + private bool _resolveHostname; + public bool ResolveHostname + { + get => _resolveHostname; + set { - get => _resolveHostname; - set - { - if (value == _resolveHostname) - return; + if (value == _resolveHostname) + return; - if (!_isLoading) - SettingsManager.Current.PortScanner_ResolveHostname = value; + if (!_isLoading) + SettingsManager.Current.PortScanner_ResolveHostname = value; - _resolveHostname = value; - OnPropertyChanged(); - } + _resolveHostname = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public PortScannerSettingsViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Constructor, load settings + public PortScannerSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - PortProfiles = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_PortProfiles); - PortProfiles.SortDescriptions.Add(new SortDescription(nameof(PortProfileInfo.Name), ListSortDirection.Ascending)); + PortProfiles = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_PortProfiles); + PortProfiles.SortDescriptions.Add(new SortDescription(nameof(PortProfileInfo.Name), ListSortDirection.Ascending)); - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - HostThreads = SettingsManager.Current.PortScanner_HostThreads; - PortThreads = SettingsManager.Current.PortScanner_PortThreads; - ShowClosed = SettingsManager.Current.PortScanner_ShowClosed; - Timeout = SettingsManager.Current.PortScanner_Timeout; - ResolveHostname = SettingsManager.Current.PortScanner_ResolveHostname; - } - #endregion + private void LoadSettings() + { + HostThreads = SettingsManager.Current.PortScanner_HostThreads; + PortThreads = SettingsManager.Current.PortScanner_PortThreads; + ShowClosed = SettingsManager.Current.PortScanner_ShowClosed; + Timeout = SettingsManager.Current.PortScanner_Timeout; + ResolveHostname = SettingsManager.Current.PortScanner_ResolveHostname; + } + #endregion - #region ICommand & Actions - public ICommand AddPortProfileCommand => new RelayCommand(p => AddPortProfileAction()); + #region ICommand & Actions + public ICommand AddPortProfileCommand => new RelayCommand(p => AddPortProfileAction()); - private void AddPortProfileAction() - { - AddPortProfile(); - } + private void AddPortProfileAction() + { + AddPortProfile(); + } - public ICommand EditPortProfileCommand => new RelayCommand(p => EditPortProfileAction()); + public ICommand EditPortProfileCommand => new RelayCommand(p => EditPortProfileAction()); - private void EditPortProfileAction() - { - EditPortProfile(); - } + private void EditPortProfileAction() + { + EditPortProfile(); + } - public ICommand DeletePortProfileCommand => new RelayCommand(p => DeletePortProfileAction()); + public ICommand DeletePortProfileCommand => new RelayCommand(p => DeletePortProfileAction()); - private void DeletePortProfileAction() - { - DeletePortProfile(); - } - #endregion + private void DeletePortProfileAction() + { + DeletePortProfile(); + } + #endregion - #region Methods - public async Task AddPortProfile() + #region Methods + public async Task AddPortProfile() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddPortProfile - }; + Title = Localization.Resources.Strings.AddPortProfile + }; - var viewModel = new PortProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var viewModel = new PortProfileViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - SettingsManager.Current.PortScanner_PortProfiles.Add(new PortProfileInfo(instance.Name, instance.Ports)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); + SettingsManager.Current.PortScanner_PortProfiles.Add(new PortProfileInfo(instance.Name, instance.Ports)); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - customDialog.Content = new PortProfileDialog - { - DataContext = viewModel - }; + customDialog.Content = new PortProfileDialog + { + DataContext = viewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - public async Task EditPortProfile() + public async Task EditPortProfile() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.EditPortProfile - }; + Title = Localization.Resources.Strings.EditPortProfile + }; - var viewModel = new PortProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var viewModel = new PortProfileViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - SettingsManager.Current.PortScanner_PortProfiles.Remove(SelectedPortProfile); - SettingsManager.Current.PortScanner_PortProfiles.Add(new PortProfileInfo(instance.Name, instance.Ports)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, true, SelectedPortProfile); + SettingsManager.Current.PortScanner_PortProfiles.Remove(SelectedPortProfile); + SettingsManager.Current.PortScanner_PortProfiles.Add(new PortProfileInfo(instance.Name, instance.Ports)); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, true, SelectedPortProfile); - customDialog.Content = new PortProfileDialog - { - DataContext = viewModel - }; + customDialog.Content = new PortProfileDialog + { + DataContext = viewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - public async Task DeletePortProfile() + public async Task DeletePortProfile() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.DeletePortProfile - }; + Title = Localization.Resources.Strings.DeletePortProfile + }; - var confirmDeleteViewModel = new ConfirmDeleteViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var confirmDeleteViewModel = new ConfirmDeleteViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - SettingsManager.Current.PortScanner_PortProfiles.Remove(SelectedPortProfile); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, Localization.Resources.Strings.DeletePortProfileMessage); + SettingsManager.Current.PortScanner_PortProfiles.Remove(SelectedPortProfile); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, Localization.Resources.Strings.DeletePortProfileMessage); - customDialog.Content = new ConfirmDeleteDialog - { - DataContext = confirmDeleteViewModel - }; + customDialog.Content = new ConfirmDeleteDialog + { + DataContext = confirmDeleteViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs index c4ed507fb0..00e1db8494 100644 --- a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs @@ -22,584 +22,583 @@ using NETworkManager.Localization.Translators; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PortScannerViewModel : ViewModelBase { - public class PortScannerViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private CancellationTokenSource _cancellationTokenSource; + private CancellationTokenSource _cancellationTokenSource; - public readonly int TabId; - private bool _firstLoad = true; + public readonly int TabId; + private bool _firstLoad = true; - private string _lastSortDescriptionAscending = string.Empty; + private string _lastSortDescriptionAscending = string.Empty; - private bool _isLoading; + private bool _isLoading; - private string _hosts; - public string Hosts + private string _hosts; + public string Hosts + { + get => _hosts; + set { - get => _hosts; - set - { - if (value == _hosts) - return; + if (value == _hosts) + return; - _hosts = value; - OnPropertyChanged(); - } + _hosts = value; + OnPropertyChanged(); } + } - public ICollectionView HostsHistoryView { get; } + public ICollectionView HostsHistoryView { get; } - private string _ports; - public string Ports + private string _ports; + public string Ports + { + get => _ports; + set { - get => _ports; - set - { - if (value == _ports) - return; + if (value == _ports) + return; - _ports = value; - OnPropertyChanged(); - } + _ports = value; + OnPropertyChanged(); } + } - public ICollectionView PortsHistoryView { get; } + public ICollectionView PortsHistoryView { get; } - private bool _isScanRunning; - public bool IsScanRunning + private bool _isScanRunning; + public bool IsScanRunning + { + get => _isScanRunning; + set { - get => _isScanRunning; - set - { - if (value == _isScanRunning) - return; + if (value == _isScanRunning) + return; - _isScanRunning = value; + _isScanRunning = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _cancelScan; - public bool CancelScan + private bool _cancelScan; + public bool CancelScan + { + get => _cancelScan; + set { - get => _cancelScan; - set - { - if (value == _cancelScan) - return; + if (value == _cancelScan) + return; - _cancelScan = value; - OnPropertyChanged(); - } + _cancelScan = value; + OnPropertyChanged(); } + } - private ObservableCollection _results = new(); - public ObservableCollection Results + private ObservableCollection _results = new(); + public ObservableCollection Results + { + get => _results; + set { - get => _results; - set - { - if (_results != null && value == _results) - return; + if (_results != null && value == _results) + return; - _results = value; - } + _results = value; } + } - public ICollectionView ResultsView { get; } + public ICollectionView ResultsView { get; } - private PortInfo _selectedResult; - public PortInfo SelectedResult + private PortInfo _selectedResult; + public PortInfo SelectedResult + { + get => _selectedResult; + set { - get => _selectedResult; - set - { - if (value == _selectedResult) - return; + if (value == _selectedResult) + return; - _selectedResult = value; - OnPropertyChanged(); - } + _selectedResult = value; + OnPropertyChanged(); } + } - private IList _selectedResults = new ArrayList(); - public IList SelectedResults + private IList _selectedResults = new ArrayList(); + public IList SelectedResults + { + get => _selectedResults; + set { - get => _selectedResults; - set - { - if (Equals(value, _selectedResults)) - return; + if (Equals(value, _selectedResults)) + return; - _selectedResults = value; - OnPropertyChanged(); - } + _selectedResults = value; + OnPropertyChanged(); } + } - public bool ResolveHostname => SettingsManager.Current.PortScanner_ResolveHostname; + public bool ResolveHostname => SettingsManager.Current.PortScanner_ResolveHostname; - private int _portsToScan; - public int PortsToScan + private int _portsToScan; + public int PortsToScan + { + get => _portsToScan; + set { - get => _portsToScan; - set - { - if (value == _portsToScan) - return; + if (value == _portsToScan) + return; - _portsToScan = value; - OnPropertyChanged(); - } + _portsToScan = value; + OnPropertyChanged(); } + } - private int _portsScanned; - public int PortsScanned + private int _portsScanned; + public int PortsScanned + { + get => _portsScanned; + set { - get => _portsScanned; - set - { - if (value == _portsScanned) - return; + if (value == _portsScanned) + return; - _portsScanned = value; - OnPropertyChanged(); - } + _portsScanned = value; + OnPropertyChanged(); } + } - private bool _preparingScan; - public bool PreparingScan + private bool _preparingScan; + public bool PreparingScan + { + get => _preparingScan; + set { - get => _preparingScan; - set - { - if (value == _preparingScan) - return; + if (value == _preparingScan) + return; - _preparingScan = value; - OnPropertyChanged(); - } + _preparingScan = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings, shutdown - public PortScannerViewModel(IDialogCoordinator instance, int tabId, string host, string port) - { - _isLoading = true; + #region Constructor, load settings, shutdown + public PortScannerViewModel(IDialogCoordinator instance, int tabId, string host, string port) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - TabId = tabId; - Hosts = host; - Ports = port; + TabId = tabId; + Hosts = host; + Ports = port; - // Set collection view - HostsHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_HostsHistory); - PortsHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_PortsHistory); + // Set collection view + HostsHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_HostsHistory); + PortsHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PortScanner_PortsHistory); - // Result view - ResultsView = CollectionViewSource.GetDefaultView(Results); - ResultsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(PortInfo.IPAddress))); - ResultsView.SortDescriptions.Add(new SortDescription(nameof(PortInfo.IPAddressInt32), ListSortDirection.Descending)); + // Result view + ResultsView = CollectionViewSource.GetDefaultView(Results); + ResultsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(PortInfo.IPAddress))); + ResultsView.SortDescriptions.Add(new SortDescription(nameof(PortInfo.IPAddressInt32), ListSortDirection.Descending)); - LoadSettings(); + LoadSettings(); - // Detect if settings have changed... - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + // Detect if settings have changed... + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { + private void LoadSettings() + { - } + } - public void OnLoaded() - { - if (!_firstLoad) - return; + public void OnLoaded() + { + if (!_firstLoad) + return; - if (!string.IsNullOrEmpty(Hosts) && !string.IsNullOrEmpty(Ports)) - StartScan(); + if (!string.IsNullOrEmpty(Hosts) && !string.IsNullOrEmpty(Ports)) + StartScan(); - _firstLoad = false; - } + _firstLoad = false; + } - public void OnClose() - { - // Stop scan - if (IsScanRunning) - StopScan(); - } - #endregion + public void OnClose() + { + // Stop scan + if (IsScanRunning) + StopScan(); + } + #endregion - #region ICommands & Actions - public ICommand OpenPortProfileSelectionCommand => new RelayCommand(p => OpenPortProfileSelectionAction(), OpenPortProfileSelection_CanExecute); + #region ICommands & Actions + public ICommand OpenPortProfileSelectionCommand => new RelayCommand(p => OpenPortProfileSelectionAction(), OpenPortProfileSelection_CanExecute); - private bool OpenPortProfileSelection_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool OpenPortProfileSelection_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void OpenPortProfileSelectionAction() - { - OpenPortProfileSelection(); - } + private void OpenPortProfileSelectionAction() + { + OpenPortProfileSelection(); + } - public ICommand ScanCommand => new RelayCommand(p => ScanAction(), Scan_CanExecute); + public ICommand ScanCommand => new RelayCommand(p => ScanAction(), Scan_CanExecute); - private bool Scan_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Scan_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void ScanAction() - { - if (IsScanRunning) - StopScan(); - else - StartScan(); - } + private void ScanAction() + { + if (IsScanRunning) + StopScan(); + else + StartScan(); + } - public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); + public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); - private void CopySelectedIPAddressAction() - { - ClipboardHelper.SetClipboard(SelectedResult.IPAddress.ToString()); - } + private void CopySelectedIPAddressAction() + { + ClipboardHelper.SetClipboard(SelectedResult.IPAddress.ToString()); + } - public ICommand CopySelectedHostnameCommand => new RelayCommand(p => CopySelectedHostnameAction()); + public ICommand CopySelectedHostnameCommand => new RelayCommand(p => CopySelectedHostnameAction()); - private void CopySelectedHostnameAction() - { - ClipboardHelper.SetClipboard(SelectedResult.Hostname); - } + private void CopySelectedHostnameAction() + { + ClipboardHelper.SetClipboard(SelectedResult.Hostname); + } - public ICommand CopySelectedPortCommand => new RelayCommand(p => CopySelectedPortAction()); + public ICommand CopySelectedPortCommand => new RelayCommand(p => CopySelectedPortAction()); - private void CopySelectedPortAction() - { - ClipboardHelper.SetClipboard(SelectedResult.Port.ToString()); - } + private void CopySelectedPortAction() + { + ClipboardHelper.SetClipboard(SelectedResult.Port.ToString()); + } - public ICommand CopySelectedStatusCommand => new RelayCommand(p => CopySelectedStatusAction()); + public ICommand CopySelectedStatusCommand => new RelayCommand(p => CopySelectedStatusAction()); - private void CopySelectedStatusAction() - { - ClipboardHelper.SetClipboard(PortStateTranslator.GetInstance().Translate(SelectedResult.State)); - } + private void CopySelectedStatusAction() + { + ClipboardHelper.SetClipboard(PortStateTranslator.GetInstance().Translate(SelectedResult.State)); + } - public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); + public ICommand CopySelectedProtocolCommand => new RelayCommand(p => CopySelectedProtocolAction()); - private void CopySelectedProtocolAction() - { - ClipboardHelper.SetClipboard(SelectedResult.LookupInfo.Protocol.ToString()); - } + private void CopySelectedProtocolAction() + { + ClipboardHelper.SetClipboard(SelectedResult.LookupInfo.Protocol.ToString()); + } - public ICommand CopySelectedServiceCommand => new RelayCommand(p => CopySelectedServiceAction()); + public ICommand CopySelectedServiceCommand => new RelayCommand(p => CopySelectedServiceAction()); - private void CopySelectedServiceAction() - { - ClipboardHelper.SetClipboard(SelectedResult.LookupInfo.Service); - } + private void CopySelectedServiceAction() + { + ClipboardHelper.SetClipboard(SelectedResult.LookupInfo.Service); + } - public ICommand CopySelectedDescriptionCommand => new RelayCommand(p => CopySelectedDescriptionAction()); + public ICommand CopySelectedDescriptionCommand => new RelayCommand(p => CopySelectedDescriptionAction()); - private void CopySelectedDescriptionAction() - { - ClipboardHelper.SetClipboard(SelectedResult.LookupInfo.Description); - } + private void CopySelectedDescriptionAction() + { + ClipboardHelper.SetClipboard(SelectedResult.LookupInfo.Description); + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private void ExportAction() - { - Export(); - } - #endregion + private void ExportAction() + { + Export(); + } + #endregion - #region Methods - private async Task OpenPortProfileSelection() + #region Methods + private async Task OpenPortProfileSelection() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.SelectPortProfile - }; - - var viewModel = new PortProfilesViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - Ports = string.Join("; ", instance.GetSelectedPortProfiles().Select(x => x.Ports)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); - - customDialog.Content = new PortProfilesDialog - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + Title = Localization.Resources.Strings.SelectPortProfile + }; - private async Task StartScan() + var viewModel = new PortProfilesViewModel(instance => { - _isLoading = true; - - IsStatusMessageDisplayed = false; - StatusMessage = string.Empty; + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - IsScanRunning = true; - PreparingScan = true; + Ports = string.Join("; ", instance.GetSelectedPortProfiles().Select(x => x.Ports)); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - Results.Clear(); + customDialog.Content = new PortProfilesDialog + { + DataContext = viewModel + }; - // Change the tab title (not nice, but it works) - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - if (window != null) - { - foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) - { - tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Hosts; - } - } + private async Task StartScan() + { + _isLoading = true; - _cancellationTokenSource = new CancellationTokenSource(); + IsStatusMessageDisplayed = false; + StatusMessage = string.Empty; - // Resolve hostnames - List ipRanges; + IsScanRunning = true; + PreparingScan = true; - try - { - ipRanges = await HostRangeHelper.ResolveHostnamesInIPRangesAsync(Hosts.Replace(" ", "").Split(';'), SettingsManager.Current.Network_ResolveHostnamePreferIPv4, _cancellationTokenSource.Token); - } - catch (OperationCanceledException) - { - UserHasCanceled(this, EventArgs.Empty); - return; - } - catch (AggregateException exceptions) // DNS error (could not resolve hostname...) - { - DnsResolveFailed(exceptions); - return; - } + Results.Clear(); - // Create ip addresses - IPAddress[] ipAddresses; + // Change the tab title (not nice, but it works) + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); - try - { - // Create a list of all ip addresses - ipAddresses = await HostRangeHelper.CreateIPAddressesFromIPRangesAsync(ipRanges.ToArray(), _cancellationTokenSource.Token); - } - catch (OperationCanceledException) + if (window != null) + { + foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) { - UserHasCanceled(this, EventArgs.Empty); - return; + tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Hosts; } + } - var ports = await PortRangeHelper.ConvertPortRangeToIntArrayAsync(Ports); - - PortsToScan = ports.Length * ipAddresses.Length; - PortsScanned = 0; - - PreparingScan = false; - - // Add host(s) to the history - AddHostToHistory(Hosts); - AddPortToHistory(Ports); + _cancellationTokenSource = new CancellationTokenSource(); - var portScanner = new PortScanner - { - ResolveHostname = SettingsManager.Current.PortScanner_ResolveHostname, - HostThreads = SettingsManager.Current.PortScanner_HostThreads, - PortThreads = SettingsManager.Current.PortScanner_PortThreads, - ShowClosed = SettingsManager.Current.PortScanner_ShowClosed, - Timeout = SettingsManager.Current.PortScanner_Timeout - }; - - portScanner.PortScanned += PortScanned; - portScanner.ScanComplete += ScanComplete; - portScanner.ProgressChanged += ProgressChanged; - portScanner.UserHasCanceled += UserHasCanceled; - - portScanner.ScanAsync(ipAddresses, ports, _cancellationTokenSource.Token); - } + // Resolve hostnames + List ipRanges; - private void StopScan() + try { - CancelScan = true; - _cancellationTokenSource.Cancel(); + ipRanges = await HostRangeHelper.ResolveHostnamesInIPRangesAsync(Hosts.Replace(" ", "").Split(';'), SettingsManager.Current.Network_ResolveHostnamePreferIPv4, _cancellationTokenSource.Token); } - - private void ScanFinished() + catch (OperationCanceledException) { - CancelScan = false; - IsScanRunning = false; + UserHasCanceled(this, EventArgs.Empty); + return; } - - private async Task Export() + catch (AggregateException exceptions) // DNS error (could not resolve hostname...) { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + DnsResolveFailed(exceptions); + return; + } - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + // Create ip addresses + IPAddress[] ipAddresses; - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? Results : new ObservableCollection(SelectedResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + try + { + // Create a list of all ip addresses + ipAddresses = await HostRangeHelper.CreateIPAddressesFromIPRangesAsync(ipRanges.ToArray(), _cancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + UserHasCanceled(this, EventArgs.Empty); + return; + } - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + var ports = await PortRangeHelper.ConvertPortRangeToIntArrayAsync(Ports); - SettingsManager.Current.PortScanner_ExportFileType = instance.FileType; - SettingsManager.Current.PortScanner_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.PortScanner_ExportFileType, SettingsManager.Current.PortScanner_ExportFilePath); + PortsToScan = ports.Length * ipAddresses.Length; + PortsScanned = 0; - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + PreparingScan = false; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + // Add host(s) to the history + AddHostToHistory(Hosts); + AddPortToHistory(Ports); - private void AddHostToHistory(string host) + var portScanner = new PortScanner { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.PortScanner_HostsHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); + ResolveHostname = SettingsManager.Current.PortScanner_ResolveHostname, + HostThreads = SettingsManager.Current.PortScanner_HostThreads, + PortThreads = SettingsManager.Current.PortScanner_PortThreads, + ShowClosed = SettingsManager.Current.PortScanner_ShowClosed, + Timeout = SettingsManager.Current.PortScanner_Timeout + }; - // Clear the old items - SettingsManager.Current.PortScanner_HostsHistory.Clear(); - OnPropertyChanged(nameof(Hosts)); // Raise property changed again, after the collection has been cleared + portScanner.PortScanned += PortScanned; + portScanner.ScanComplete += ScanComplete; + portScanner.ProgressChanged += ProgressChanged; + portScanner.UserHasCanceled += UserHasCanceled; - // Fill with the new items - list.ForEach(x => SettingsManager.Current.PortScanner_HostsHistory.Add(x)); - } + portScanner.ScanAsync(ipAddresses, ports, _cancellationTokenSource.Token); + } - private void AddPortToHistory(string port) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.PortScanner_PortsHistory.ToList(), port, SettingsManager.Current.General_HistoryListEntries); + private void StopScan() + { + CancelScan = true; + _cancellationTokenSource.Cancel(); + } - // Clear the old items - SettingsManager.Current.PortScanner_PortsHistory.Clear(); - OnPropertyChanged(nameof(Ports)); // Raise property changed again, after the collection has been cleared + private void ScanFinished() + { + CancelScan = false; + IsScanRunning = false; + } - // Fill with the new items - list.ForEach(x => SettingsManager.Current.PortScanner_PortsHistory.Add(x)); - } + private async Task Export() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.Export + }; - public void SortResultByPropertyName(string sortDescription) + var exportViewModel = new ExportViewModel(async instance => { - ResultsView.SortDescriptions.Clear(); - ResultsView.SortDescriptions.Add(new SortDescription(nameof(PortInfo.IPAddressInt32), ListSortDirection.Descending)); + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - if (_lastSortDescriptionAscending.Equals(sortDescription)) + try { - ResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Descending)); - _lastSortDescriptionAscending = string.Empty; + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? Results : new ObservableCollection(SelectedResults.Cast().ToArray())); } - else + catch (Exception ex) { - ResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Ascending)); - _lastSortDescriptionAscending = sortDescription; + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); } - } - #endregion - #region Events - private void UserHasCanceled(object sender, EventArgs e) + SettingsManager.Current.PortScanner_ExportFileType = instance.FileType; + SettingsManager.Current.PortScanner_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.PortScanner_ExportFileType, SettingsManager.Current.PortScanner_ExportFilePath); + + customDialog.Content = new ExportDialog { - StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; - IsStatusMessageDisplayed = true; + DataContext = exportViewModel + }; - ScanFinished(); - } + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - private void ProgressChanged(object sender, ProgressChangedArgs e) - { - PortsScanned = e.Value; - } + private void AddHostToHistory(string host) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.PortScanner_HostsHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); - private void DnsResolveFailed(AggregateException e) - { - StatusMessage = $"{Localization.Resources.Strings.TheFollowingHostnamesCouldNotBeResolved} {string.Join(", ", e.Flatten().InnerExceptions.Select(x => x.Message))}"; - IsStatusMessageDisplayed = true; + // Clear the old items + SettingsManager.Current.PortScanner_HostsHistory.Clear(); + OnPropertyChanged(nameof(Hosts)); // Raise property changed again, after the collection has been cleared - ScanFinished(); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.PortScanner_HostsHistory.Add(x)); + } + + private void AddPortToHistory(string port) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.PortScanner_PortsHistory.ToList(), port, SettingsManager.Current.General_HistoryListEntries); + + // Clear the old items + SettingsManager.Current.PortScanner_PortsHistory.Clear(); + OnPropertyChanged(nameof(Ports)); // Raise property changed again, after the collection has been cleared + + // Fill with the new items + list.ForEach(x => SettingsManager.Current.PortScanner_PortsHistory.Add(x)); + } + + public void SortResultByPropertyName(string sortDescription) + { + ResultsView.SortDescriptions.Clear(); + ResultsView.SortDescriptions.Add(new SortDescription(nameof(PortInfo.IPAddressInt32), ListSortDirection.Descending)); - private void ScanComplete(object sender, EventArgs e) + if (_lastSortDescriptionAscending.Equals(sortDescription)) { - ScanFinished(); + ResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Descending)); + _lastSortDescriptionAscending = string.Empty; } - - private void PortScanned(object sender, PortScannedArgs e) + else { - var portInfo = PortInfo.Parse(e); - - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate () - { - //lock (PortScanResult) - Results.Add(portInfo); - })); + ResultsView.SortDescriptions.Add(new SortDescription(sortDescription, ListSortDirection.Ascending)); + _lastSortDescriptionAscending = sortDescription; } + } + #endregion + + #region Events + private void UserHasCanceled(object sender, EventArgs e) + { + StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; + IsStatusMessageDisplayed = true; + + ScanFinished(); + } + + private void ProgressChanged(object sender, ProgressChangedArgs e) + { + PortsScanned = e.Value; + } + + private void DnsResolveFailed(AggregateException e) + { + StatusMessage = $"{Localization.Resources.Strings.TheFollowingHostnamesCouldNotBeResolved} {string.Join(", ", e.Flatten().InnerExceptions.Select(x => x.Message))}"; + IsStatusMessageDisplayed = true; + + ScanFinished(); + } + + private void ScanComplete(object sender, EventArgs e) + { + ScanFinished(); + } - private void DispatcherTimer_Tick(object sender, EventArgs e) + private void PortScanned(object sender, PortScannedArgs e) + { + var portInfo = PortInfo.Parse(e); + + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate () { + //lock (PortScanResult) + Results.Add(portInfo); + })); + } - } + private void DispatcherTimer_Tick(object sender, EventArgs e) + { + + } - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) { - switch (e.PropertyName) - { - case nameof(SettingsInfo.PortScanner_ResolveHostname): - OnPropertyChanged(nameof(ResolveHostname)); - break; - } + case nameof(SettingsInfo.PortScanner_ResolveHostname): + OnPropertyChanged(nameof(ResolveHostname)); + break; } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PowerShellConnectViewModel.cs b/Source/NETworkManager/ViewModels/PowerShellConnectViewModel.cs index 5c0153394a..680fea9acd 100644 --- a/Source/NETworkManager/ViewModels/PowerShellConnectViewModel.cs +++ b/Source/NETworkManager/ViewModels/PowerShellConnectViewModel.cs @@ -8,122 +8,121 @@ using System.Windows.Input; using NETworkManager.Models.PowerShell; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PowerShellConnectViewModel : ViewModelBase { - public class PowerShellConnectViewModel : ViewModelBase - { - public ICommand ConnectCommand { get; } - public ICommand CancelCommand { get; } + public ICommand ConnectCommand { get; } + public ICommand CancelCommand { get; } - private bool _enableRemoteConsole; - public bool EnableRemoteConsole + private bool _enableRemoteConsole; + public bool EnableRemoteConsole + { + get => _enableRemoteConsole; + set { - get => _enableRemoteConsole; - set - { - if (value == _enableRemoteConsole) - return; - - _enableRemoteConsole = value; - OnPropertyChanged(); - } + if (value == _enableRemoteConsole) + return; + + _enableRemoteConsole = value; + OnPropertyChanged(); } + } - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; - - _host = value; - OnPropertyChanged(); - } + if (value == _host) + return; + + _host = value; + OnPropertyChanged(); } + } - public ICollectionView HostHistoryView { get; } + public ICollectionView HostHistoryView { get; } - private string _command; - public string Command + private string _command; + public string Command + { + get => _command; + set { - get => _command; - set - { - if (value == _command) - return; - - _command = value; - OnPropertyChanged(); - } - } + if (value == _command) + return; - private string _additionalCommandLine; - public string AdditionalCommandLine - { - get => _additionalCommandLine; - set - { - if (value == _additionalCommandLine) - return; - - _additionalCommandLine = value; - OnPropertyChanged(); - } + _command = value; + OnPropertyChanged(); } + } - private List _executionPolicies = new List(); - public List ExecutionPolicies + private string _additionalCommandLine; + public string AdditionalCommandLine + { + get => _additionalCommandLine; + set { - get => _executionPolicies; - set - { - if (value == _executionPolicies) - return; - - _executionPolicies = value; - OnPropertyChanged(); - } - } + if (value == _additionalCommandLine) + return; - private PowerShell.ExecutionPolicy _executionPolicy; - public PowerShell.ExecutionPolicy ExecutionPolicy - { - get => _executionPolicy; - set - { - if (value == _executionPolicy) - return; - - _executionPolicy = value; - OnPropertyChanged(); - } + _additionalCommandLine = value; + OnPropertyChanged(); } + } - public PowerShellConnectViewModel(Action connectCommand, Action cancelHandler, string host = null) + private List _executionPolicies = new List(); + public List ExecutionPolicies + { + get => _executionPolicies; + set { - ConnectCommand = new RelayCommand(p => connectCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + if (value == _executionPolicies) + return; - if (!string.IsNullOrEmpty(host)) - { - Host = host; - EnableRemoteConsole = true; - } + _executionPolicies = value; + OnPropertyChanged(); + } + } - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PowerShell_HostHistory); + private PowerShell.ExecutionPolicy _executionPolicy; + public PowerShell.ExecutionPolicy ExecutionPolicy + { + get => _executionPolicy; + set + { + if (value == _executionPolicy) + return; - LoadSettings(); + _executionPolicy = value; + OnPropertyChanged(); } + } - private void LoadSettings() + public PowerShellConnectViewModel(Action connectCommand, Action cancelHandler, string host = null) + { + ConnectCommand = new RelayCommand(p => connectCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + + if (!string.IsNullOrEmpty(host)) { - Command = SettingsManager.Current.PowerShell_Command; - AdditionalCommandLine = SettingsManager.Current.PowerShell_AdditionalCommandLine; - - ExecutionPolicies = Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); - ExecutionPolicy = ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); + Host = host; + EnableRemoteConsole = true; } + + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PowerShell_HostHistory); + + LoadSettings(); + } + + private void LoadSettings() + { + Command = SettingsManager.Current.PowerShell_Command; + AdditionalCommandLine = SettingsManager.Current.PowerShell_AdditionalCommandLine; + + ExecutionPolicies = Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); + ExecutionPolicy = ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); } } diff --git a/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs b/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs index 9a63937de8..72f4f776dc 100644 --- a/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PowerShellHostViewModel.cs @@ -21,591 +21,590 @@ using System.Threading.Tasks; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PowerShellHostViewModel : ViewModelBase, IProfileManager { - public class PowerShellHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private bool _isConfigured; - public bool IsConfigured + private bool _isConfigured; + public bool IsConfigured + { + get => _isConfigured; + set { - get => _isConfigured; - set - { - if (value == _isConfigured) - return; + if (value == _isConfigured) + return; - _isConfigured = value; - OnPropertyChanged(); - } + _isConfigured = value; + OnPropertyChanged(); } + } - private bool _disableFocusEmbeddedWindow; + private bool _disableFocusEmbeddedWindow; - private DragablzTabItem _selectedTabItem; - public DragablzTabItem SelectedTabItem + private DragablzTabItem _selectedTabItem; + public DragablzTabItem SelectedTabItem + { + get => _selectedTabItem; + set { - get => _selectedTabItem; - set - { - if (value == _selectedTabItem) - return; + if (value == _selectedTabItem) + return; - _selectedTabItem = value; + _selectedTabItem = value; - // Focus embedded window on switching tab - if (!_disableFocusEmbeddedWindow) - FocusEmbeddedWindow(); + // Focus embedded window on switching tab + if (!_disableFocusEmbeddedWindow) + FocusEmbeddedWindow(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _headerContextMenuIsOpen; - public bool HeaderContextMenuIsOpen + private bool _headerContextMenuIsOpen; + public bool HeaderContextMenuIsOpen + { + get => _headerContextMenuIsOpen; + set { - get => _headerContextMenuIsOpen; - set - { - if (value == _headerContextMenuIsOpen) - return; + if (value == _headerContextMenuIsOpen) + return; - _headerContextMenuIsOpen = value; - OnPropertyChanged(); - } + _headerContextMenuIsOpen = value; + OnPropertyChanged(); } - #region Profiles + } + #region Profiles - public ICollectionView Profiles { get; } + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _textBoxSearchIsFocused; - public bool TextBoxSearchIsFocused + private bool _textBoxSearchIsFocused; + public bool TextBoxSearchIsFocused + { + get => _textBoxSearchIsFocused; + set { - get => _textBoxSearchIsFocused; - set - { - if (value == _textBoxSearchIsFocused) - return; + if (value == _textBoxSearchIsFocused) + return; - _textBoxSearchIsFocused = value; - OnPropertyChanged(); - } + _textBoxSearchIsFocused = value; + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.PowerShell_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.PowerShell_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.PowerShell_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.PowerShell_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _profileContextMenuIsOpen; - public bool ProfileContextMenuIsOpen + private bool _profileContextMenuIsOpen; + public bool ProfileContextMenuIsOpen + { + get => _profileContextMenuIsOpen; + set { - get => _profileContextMenuIsOpen; - set - { - if (value == _profileContextMenuIsOpen) - return; + if (value == _profileContextMenuIsOpen) + return; - _profileContextMenuIsOpen = value; - OnPropertyChanged(); - } + _profileContextMenuIsOpen = value; + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public PowerShellHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; - - CheckSettings(); + #region Constructor, load settings + public PowerShellHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; + + CheckSettings(); - InterTabClient = new DragablzInterTabClient(ApplicationName.PowerShell); + InterTabClient = new DragablzInterTabClient(ApplicationName.PowerShell); - TabItems = new ObservableCollection(); + TabItems = new ObservableCollection(); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (o is not ProfileInfo info) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (o is not ProfileInfo info) + return false; - if (string.IsNullOrEmpty(Search)) - return info.PowerShell_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.PowerShell_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.PowerShell_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.PowerShell_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, PowerShell_Host - return info.PowerShell_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PowerShell_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, PowerShell_Host + return info.PowerShell_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PowerShell_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PowerShell_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PowerShell_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += Current_PropertyChanged; + SettingsManager.Current.PropertyChanged += Current_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - if (e.PropertyName == nameof(SettingsInfo.PowerShell_ApplicationFilePath)) - CheckSettings(); - } + private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(SettingsInfo.PowerShell_ApplicationFilePath)) + CheckSettings(); + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.PowerShell_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.PowerShell_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PowerShell_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PowerShell_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.PowerShell_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.PowerShell_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ItemActionCallback CloseItemCommand => CloseItemAction; + #region ICommand & Actions + public ItemActionCallback CloseItemCommand => CloseItemAction; - private void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as PowerShellControl)?.CloseTab(); - } + private void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as PowerShellControl)?.CloseTab(); + } - private bool PowerShell_Connected_CanExecute(object view) - { - if (view is PowerShellControl control) - return control.IsConnected; + private bool PowerShell_Connected_CanExecute(object view) + { + if (view is PowerShellControl control) + return control.IsConnected; - return false; - } + return false; + } - public ICommand PowerShell_ReconnectCommand => new RelayCommand(PowerShell_ReconnectAction); + public ICommand PowerShell_ReconnectCommand => new RelayCommand(PowerShell_ReconnectAction); - private void PowerShell_ReconnectAction(object view) + private void PowerShell_ReconnectAction(object view) + { + if (view is PowerShellControl control) { - if (view is PowerShellControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } + } - public ICommand PowerShell_ResizeWindowCommand => new RelayCommand(PowerShell_ResizeWindowAction, PowerShell_Connected_CanExecute); + public ICommand PowerShell_ResizeWindowCommand => new RelayCommand(PowerShell_ResizeWindowAction, PowerShell_Connected_CanExecute); - private void PowerShell_ResizeWindowAction(object view) - { - if (view is PowerShellControl control) - control.ResizeEmbeddedWindow(); - } + private void PowerShell_ResizeWindowAction(object view) + { + if (view is PowerShellControl control) + control.ResizeEmbeddedWindow(); + } - public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); + public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); - private bool Connect_CanExecute(object obj) => IsConfigured; + private bool Connect_CanExecute(object obj) => IsConfigured; - private void ConnectAction() - { - Connect(); - } + private void ConnectAction() + { + Connect(); + } - public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); + public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); - private bool ConnectProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool ConnectProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ConnectProfileAction() - { - ConnectProfile(); - } + private void ConnectProfileAction() + { + ConnectProfile(); + } - public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); + public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); - private void ConnectProfileExternalAction() - { - ConnectProfileExternal(); - } + private void ConnectProfileExternalAction() + { + ConnectProfileExternal(); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PowerShell); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PowerShell); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand TextBoxSearchGotFocusCommand - { - get { return new RelayCommand(p => TextBoxSearchGotFocusAction()); } - } + public ICommand TextBoxSearchGotFocusCommand + { + get { return new RelayCommand(p => TextBoxSearchGotFocusAction()); } + } - private void TextBoxSearchGotFocusAction() - { - TextBoxSearchIsFocused = true; - } + private void TextBoxSearchGotFocusAction() + { + TextBoxSearchIsFocused = true; + } - public ICommand TextBoxSearchLostFocusCommand - { - get { return new RelayCommand(p => TextBoxSearchLostFocusAction()); } - } + public ICommand TextBoxSearchLostFocusCommand + { + get { return new RelayCommand(p => TextBoxSearchLostFocusAction()); } + } - private void TextBoxSearchLostFocusAction() - { - TextBoxSearchIsFocused = false; - } + private void TextBoxSearchLostFocusAction() + { + TextBoxSearchIsFocused = false; + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); + public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); - private static void OpenSettingsAction() - { - EventSystem.RedirectToSettings(); - } - #endregion + private static void OpenSettingsAction() + { + EventSystem.RedirectToSettings(); + } + #endregion - #region Methods - private void CheckSettings() - { - IsConfigured = !string.IsNullOrEmpty(SettingsManager.Current.PowerShell_ApplicationFilePath) && File.Exists(SettingsManager.Current.PowerShell_ApplicationFilePath); - } + #region Methods + private void CheckSettings() + { + IsConfigured = !string.IsNullOrEmpty(SettingsManager.Current.PowerShell_ApplicationFilePath) && File.Exists(SettingsManager.Current.PowerShell_ApplicationFilePath); + } - private async Task Connect(string host = null) + private async Task Connect(string host = null) + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Connect - }; + Title = Localization.Resources.Strings.Connect + }; - var connectViewModel = new PowerShellConnectViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - - // Create profile info - var info = new PowerShellSessionInfo - { - EnableRemoteConsole = instance.EnableRemoteConsole, - Host = instance.Host, - Command = instance.Command, - AdditionalCommandLine = instance.AdditionalCommandLine, - ExecutionPolicy = instance.ExecutionPolicy - }; - - // Add to history - // Note: The history can only be updated after the values have been read. - // Otherwise, in some cases, incorrect values are taken over. - AddHostToHistory(instance.Host); - - // Connect - Connect(info); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - }, host); + var connectViewModel = new PowerShellConnectViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - customDialog.Content = new PowerShellConnectDialog + // Create profile info + var info = new PowerShellSessionInfo { - DataContext = connectViewModel + EnableRemoteConsole = instance.EnableRemoteConsole, + Host = instance.Host, + Command = instance.Command, + AdditionalCommandLine = instance.AdditionalCommandLine, + ExecutionPolicy = instance.ExecutionPolicy }; - ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + // Add to history + // Note: The history can only be updated after the values have been read. + // Otherwise, in some cases, incorrect values are taken over. + AddHostToHistory(instance.Host); - private void ConnectProfile() + // Connect + Connect(info); + }, async instance => { - Connect(NETworkManager.Profiles.Application.PowerShell.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); - } + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; + }, host); - private void ConnectProfileExternal() + customDialog.Content = new PowerShellConnectDialog { - Process.Start(new ProcessStartInfo() - { - FileName = SettingsManager.Current.PowerShell_ApplicationFilePath, - Arguments = PowerShell.BuildCommandLine(NETworkManager.Profiles.Application.PowerShell.CreateSessionInfo(SelectedProfile)) - }); - } + DataContext = connectViewModel + }; + + ConfigurationManager.Current.IsDialogOpen = true; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + private void ConnectProfile() + { + Connect(NETworkManager.Profiles.Application.PowerShell.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); + } - private void Connect(PowerShellSessionInfo sessionInfo, string header = null) + private void ConnectProfileExternal() + { + Process.Start(new ProcessStartInfo() { - sessionInfo.ApplicationFilePath = SettingsManager.Current.PowerShell_ApplicationFilePath; + FileName = SettingsManager.Current.PowerShell_ApplicationFilePath, + Arguments = PowerShell.BuildCommandLine(NETworkManager.Profiles.Application.PowerShell.CreateSessionInfo(SelectedProfile)) + }); + } - TabItems.Add(new DragablzTabItem(header ?? (sessionInfo.EnableRemoteConsole ? sessionInfo.Host : Localization.Resources.Strings.PowerShell), new PowerShellControl(sessionInfo))); + private void Connect(PowerShellSessionInfo sessionInfo, string header = null) + { + sessionInfo.ApplicationFilePath = SettingsManager.Current.PowerShell_ApplicationFilePath; - // Select the added tab - _disableFocusEmbeddedWindow = true; - SelectedTabItem = TabItems.Last(); - _disableFocusEmbeddedWindow = false; - } + TabItems.Add(new DragablzTabItem(header ?? (sessionInfo.EnableRemoteConsole ? sessionInfo.Host : Localization.Resources.Strings.PowerShell), new PowerShellControl(sessionInfo))); - public void AddTab(string host) - { - Connect(host); - } + // Select the added tab + _disableFocusEmbeddedWindow = true; + SelectedTabItem = TabItems.Last(); + _disableFocusEmbeddedWindow = false; + } - // Modify history list - private static void AddHostToHistory(string host) - { - if (string.IsNullOrEmpty(host)) - return; + public void AddTab(string host) + { + Connect(host); + } - SettingsManager.Current.PowerShell_HostHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PowerShell_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); - } + // Modify history list + private static void AddHostToHistory(string host) + { + if (string.IsNullOrEmpty(host)) + return; - private void StartDelayedSearch() + SettingsManager.Current.PowerShell_HostHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PowerShell_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); + } + + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } - if (dueToChangedSize) + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; + + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void FocusEmbeddedWindow() - { - /* Don't continue if - - Search TextBox is focused - - Header ContextMenu is opened - - Profile ContextMenu is opened - */ - if (TextBoxSearchIsFocused || HeaderContextMenuIsOpen || ProfileContextMenuIsOpen) - return; - - (SelectedTabItem?.View as PowerShellControl)?.FocusEmbeddedWindow(); - } + _canProfileWidthChange = true; + } - public void OnViewVisible() - { - _isViewActive = true; + public void FocusEmbeddedWindow() + { + /* Don't continue if + - Search TextBox is focused + - Header ContextMenu is opened + - Profile ContextMenu is opened + */ + if (TextBoxSearchIsFocused || HeaderContextMenuIsOpen || ProfileContextMenuIsOpen) + return; + + (SelectedTabItem?.View as PowerShellControl)?.FocusEmbeddedWindow(); + } - RefreshProfiles(); + public void OnViewVisible() + { + _isViewActive = true; - FocusEmbeddedWindow(); - } + RefreshProfiles(); - public void OnViewHide() - { - _isViewActive = false; - } + FocusEmbeddedWindow(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - ConfigurationManager.Current.IsDialogOpen = true; - } + Profiles.Refresh(); + })); + } - public void OnProfileDialogClose() - { - ConfigurationManager.Current.IsDialogOpen = false; - } - #endregion + public void OnProfileDialogOpen() + { + ConfigurationManager.Current.IsDialogOpen = true; + } - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + public void OnProfileDialogClose() + { + ConfigurationManager.Current.IsDialogOpen = false; + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PowerShellSettingsViewModel.cs b/Source/NETworkManager/ViewModels/PowerShellSettingsViewModel.cs index c0e85dd261..cfd29008df 100644 --- a/Source/NETworkManager/ViewModels/PowerShellSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/PowerShellSettingsViewModel.cs @@ -10,188 +10,187 @@ using NETworkManager.Models.PowerShell; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PowerShellSettingsViewModel : ViewModelBase { - public class PowerShellSettingsViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading; + private readonly bool _isLoading; - private string _applicationFilePath; - public string ApplicationFilePath + private string _applicationFilePath; + public string ApplicationFilePath + { + get => _applicationFilePath; + set { - get => _applicationFilePath; - set - { - if (value == _applicationFilePath) - return; + if (value == _applicationFilePath) + return; - if (!_isLoading) - SettingsManager.Current.PowerShell_ApplicationFilePath = value; + if (!_isLoading) + SettingsManager.Current.PowerShell_ApplicationFilePath = value; - IsConfigured = !string.IsNullOrEmpty(value); + IsConfigured = !string.IsNullOrEmpty(value); - _applicationFilePath = value; - OnPropertyChanged(); - } + _applicationFilePath = value; + OnPropertyChanged(); } + } - private string _command; - public string Command + private string _command; + public string Command + { + get => _command; + set { - get => _command; - set - { - if (value == _command) - return; - - if (!_isLoading) - SettingsManager.Current.PowerShell_Command = value; - - _command = value; - OnPropertyChanged(); - } + if (value == _command) + return; + + if (!_isLoading) + SettingsManager.Current.PowerShell_Command = value; + + _command = value; + OnPropertyChanged(); } + } - private string _additionalCommandLine; - public string AdditionalCommandLine + private string _additionalCommandLine; + public string AdditionalCommandLine + { + get => _additionalCommandLine; + set { - get => _additionalCommandLine; - set - { - if(value == _additionalCommandLine) - return; - - if (!_isLoading) - SettingsManager.Current.PowerShell_AdditionalCommandLine = value; - - _additionalCommandLine = value; - OnPropertyChanged(); - } + if(value == _additionalCommandLine) + return; + + if (!_isLoading) + SettingsManager.Current.PowerShell_AdditionalCommandLine = value; + + _additionalCommandLine = value; + OnPropertyChanged(); } + } - private List _executionPolicies = new List(); - public List ExecutionPolicies + private List _executionPolicies = new List(); + public List ExecutionPolicies + { + get => _executionPolicies; + set { - get => _executionPolicies; - set - { - if (value == _executionPolicies) - return; - - _executionPolicies = value; - OnPropertyChanged(); - } + if (value == _executionPolicies) + return; + + _executionPolicies = value; + OnPropertyChanged(); } + } - private PowerShell.ExecutionPolicy _executionPolicy; - public PowerShell.ExecutionPolicy ExecutionPolicy + private PowerShell.ExecutionPolicy _executionPolicy; + public PowerShell.ExecutionPolicy ExecutionPolicy + { + get => _executionPolicy; + set { - get => _executionPolicy; - set - { - if (value == _executionPolicy) - return; - - if (!_isLoading) - SettingsManager.Current.PowerShell_ExecutionPolicy = value; - - _executionPolicy = value; - OnPropertyChanged(); - } + if (value == _executionPolicy) + return; + + if (!_isLoading) + SettingsManager.Current.PowerShell_ExecutionPolicy = value; + + _executionPolicy = value; + OnPropertyChanged(); } + } - private bool _isConfigured; - public bool IsConfigured + private bool _isConfigured; + public bool IsConfigured + { + get => _isConfigured; + set { - get => _isConfigured; - set - { - if (value == _isConfigured) - return; - - _isConfigured = value; - OnPropertyChanged(); - } + if (value == _isConfigured) + return; + + _isConfigured = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public PowerShellSettingsViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Contructor, load settings + public PowerShellSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ApplicationFilePath = SettingsManager.Current.PowerShell_ApplicationFilePath; - IsConfigured = File.Exists(ApplicationFilePath); - Command = SettingsManager.Current.PowerShell_Command; - AdditionalCommandLine = SettingsManager.Current.PowerShell_AdditionalCommandLine; + private void LoadSettings() + { + ApplicationFilePath = SettingsManager.Current.PowerShell_ApplicationFilePath; + IsConfigured = File.Exists(ApplicationFilePath); + Command = SettingsManager.Current.PowerShell_Command; + AdditionalCommandLine = SettingsManager.Current.PowerShell_AdditionalCommandLine; - LoadExecutionPolicies(); - } + LoadExecutionPolicies(); + } - private void LoadExecutionPolicies() - { - ExecutionPolicies = System.Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); - ExecutionPolicy = ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); - } - #endregion + private void LoadExecutionPolicies() + { + ExecutionPolicies = System.Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); + ExecutionPolicy = ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); + } + #endregion - #region ICommands & Actions - public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); + #region ICommands & Actions + public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); - private void BrowseFileAction() + private void BrowseFileAction() + { + var openFileDialog = new System.Windows.Forms.OpenFileDialog { - var openFileDialog = new System.Windows.Forms.OpenFileDialog - { - Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter - }; + Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter + }; - if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - ApplicationFilePath = openFileDialog.FileName; - } + if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + ApplicationFilePath = openFileDialog.FileName; + } - public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); + public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); - private void ConfigureAction() - { - Configure(); - } - #endregion + private void ConfigureAction() + { + Configure(); + } + #endregion - #region Methods - private async Task Configure() + #region Methods + private async Task Configure() + { + try { - try - { - Process.Start(SettingsManager.Current.PowerShell_ApplicationFilePath); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); - } + Process.Start(SettingsManager.Current.PowerShell_ApplicationFilePath); } - - public void SetFilePathFromDragDrop(string filePath) + catch (Exception ex) { - ApplicationFilePath = filePath; + var settings = AppearanceManager.MetroDialog; + + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - OnPropertyChanged(nameof(ApplicationFilePath)); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); } - #endregion } + + public void SetFilePathFromDragDrop(string filePath) + { + ApplicationFilePath = filePath; + + OnPropertyChanged(nameof(ApplicationFilePath)); + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ProfileFileViewModel.cs b/Source/NETworkManager/ViewModels/ProfileFileViewModel.cs index 05a325d349..cbb8b9bfb7 100644 --- a/Source/NETworkManager/ViewModels/ProfileFileViewModel.cs +++ b/Source/NETworkManager/ViewModels/ProfileFileViewModel.cs @@ -3,53 +3,52 @@ using System; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ProfileFileViewModel : ViewModelBase { - public class ProfileFileViewModel : ViewModelBase - { - public ICommand AcceptCommand { get; } + public ICommand AcceptCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private string _name; - public string Name + private string _name; + public string Name + { + get => _name; + set { - get => _name; - set - { - if (value == _name) - return; - - _name = value; - OnPropertyChanged(); - } + if (value == _name) + return; + + _name = value; + OnPropertyChanged(); } - - private bool _isEdit; - public bool IsEdit + } + + private bool _isEdit; + public bool IsEdit + { + get => _isEdit; + set { - get => _isEdit; - set - { - if (value == _isEdit) - return; - - _isEdit = value; - OnPropertyChanged(); - } + if (value == _isEdit) + return; + + _isEdit = value; + OnPropertyChanged(); } + } - public ProfileFileViewModel(Action addCommand, Action cancelHandler, ProfileFileInfo info = null) + public ProfileFileViewModel(Action addCommand, Action cancelHandler, ProfileFileInfo info = null) + { + AcceptCommand = new RelayCommand(p => addCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + + if (info != null) { - AcceptCommand = new RelayCommand(p => addCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - - if (info != null) - { - Name = info.Name; - - IsEdit = true; - } + Name = info.Name; + + IsEdit = true; } } } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ProfileViewModel.cs b/Source/NETworkManager/ViewModels/ProfileViewModel.cs index be71b2bb5e..102b5d36b3 100644 --- a/Source/NETworkManager/ViewModels/ProfileViewModel.cs +++ b/Source/NETworkManager/ViewModels/ProfileViewModel.cs @@ -15,2488 +15,2487 @@ using System.Security; using NETworkManager.Models; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ProfileViewModel : ViewModelBase { - public class ProfileViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading = true; + #region Variables + private readonly bool _isLoading = true; - public bool IsProfileFileEncrypted => ProfileManager.LoadedProfileFile.IsEncrypted; + public bool IsProfileFileEncrypted => ProfileManager.LoadedProfileFile.IsEncrypted; - public ICollectionView ProfileViews { get; } + public ICollectionView ProfileViews { get; } - #region General - private string _name; - public string Name + #region General + private string _name; + public string Name + { + get => _name; + set { - get => _name; - set - { - if (value == _name) - return; + if (value == _name) + return; - _name = value; - OnPropertyChanged(); - } + _name = value; + OnPropertyChanged(); } + } - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; + if (value == _host) + return; - // Reset, if string has changed - if (!IsResolveHostnameRunning) - ShowCouldNotResolveHostnameWarning = false; + // Reset, if string has changed + if (!IsResolveHostnameRunning) + ShowCouldNotResolveHostnameWarning = false; - _host = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } + } - private bool _isResolveHostnameRunning; - public bool IsResolveHostnameRunning + private bool _isResolveHostnameRunning; + public bool IsResolveHostnameRunning + { + get => _isResolveHostnameRunning; + set { - get => _isResolveHostnameRunning; - set - { - if (value == _isResolveHostnameRunning) - return; + if (value == _isResolveHostnameRunning) + return; - _isResolveHostnameRunning = value; - OnPropertyChanged(); - } + _isResolveHostnameRunning = value; + OnPropertyChanged(); } + } - private bool _showCouldNotResolveHostnameWarning; - public bool ShowCouldNotResolveHostnameWarning + private bool _showCouldNotResolveHostnameWarning; + public bool ShowCouldNotResolveHostnameWarning + { + get => _showCouldNotResolveHostnameWarning; + set { - get => _showCouldNotResolveHostnameWarning; - set - { - if (value == _showCouldNotResolveHostnameWarning) - return; + if (value == _showCouldNotResolveHostnameWarning) + return; - _showCouldNotResolveHostnameWarning = value; - OnPropertyChanged(); - } + _showCouldNotResolveHostnameWarning = value; + OnPropertyChanged(); } + } - private string _group; - public string Group + private string _group; + public string Group + { + get => _group; + set { - get => _group; - set - { - if (value == _group) - return; + if (value == _group) + return; - _group = value; - OnPropertyChanged(); - } + _group = value; + OnPropertyChanged(); } + } - public ICollectionView Groups { get; } + public ICollectionView Groups { get; } - private string _tags; - public string Tags + private string _tags; + public string Tags + { + get => _tags; + set { - get => _tags; - set - { - if (value == _tags) - return; + if (value == _tags) + return; - _tags = value; - OnPropertyChanged(); - } + _tags = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Network Interface - private bool _networkInterface_Enabled; - public bool NetworkInterface_Enabled + #region Network Interface + private bool _networkInterface_Enabled; + public bool NetworkInterface_Enabled + { + get => _networkInterface_Enabled; + set { - get => _networkInterface_Enabled; - set - { - if (value == _networkInterface_Enabled) - return; + if (value == _networkInterface_Enabled) + return; - _networkInterface_Enabled = value; + _networkInterface_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _networkInterface_EnableDynamicIPAddress = true; - public bool NetworkInterface_EnableDynamicIPAddress + private bool _networkInterface_EnableDynamicIPAddress = true; + public bool NetworkInterface_EnableDynamicIPAddress + { + get => _networkInterface_EnableDynamicIPAddress; + set { - get => _networkInterface_EnableDynamicIPAddress; - set - { - if (value == _networkInterface_EnableDynamicIPAddress) - return; + if (value == _networkInterface_EnableDynamicIPAddress) + return; - _networkInterface_EnableDynamicIPAddress = value; - OnPropertyChanged(); - } + _networkInterface_EnableDynamicIPAddress = value; + OnPropertyChanged(); } + } - private bool _networkInterface_EnableStaticIPAddress; - public bool NetworkInterface_EnableStaticIPAddress + private bool _networkInterface_EnableStaticIPAddress; + public bool NetworkInterface_EnableStaticIPAddress + { + get => _networkInterface_EnableStaticIPAddress; + set { - get => _networkInterface_EnableStaticIPAddress; - set - { - if (value == _networkInterface_EnableStaticIPAddress) - return; + if (value == _networkInterface_EnableStaticIPAddress) + return; - if (value) - NetworkInterface_EnableStaticDNS = true; + if (value) + NetworkInterface_EnableStaticDNS = true; - _networkInterface_EnableStaticIPAddress = value; - OnPropertyChanged(); - } + _networkInterface_EnableStaticIPAddress = value; + OnPropertyChanged(); } + } - private string _networkInterface_IPAddress; - public string NetworkInterface_IPAddress + private string _networkInterface_IPAddress; + public string NetworkInterface_IPAddress + { + get => _networkInterface_IPAddress; + set { - get => _networkInterface_IPAddress; - set - { - if (value == _networkInterface_IPAddress) - return; + if (value == _networkInterface_IPAddress) + return; - _networkInterface_IPAddress = value; - OnPropertyChanged(); - } + _networkInterface_IPAddress = value; + OnPropertyChanged(); } + } - private string _networkInterface_SubnetmaskOrCidr; - public string NetworkInterface_SubnetmaskOrCidr + private string _networkInterface_SubnetmaskOrCidr; + public string NetworkInterface_SubnetmaskOrCidr + { + get => _networkInterface_SubnetmaskOrCidr; + set { - get => _networkInterface_SubnetmaskOrCidr; - set - { - if (value == _networkInterface_SubnetmaskOrCidr) - return; + if (value == _networkInterface_SubnetmaskOrCidr) + return; - _networkInterface_SubnetmaskOrCidr = value; - OnPropertyChanged(); - } + _networkInterface_SubnetmaskOrCidr = value; + OnPropertyChanged(); } + } - private string _networkInterface_Gateway; - public string NetworkInterface_Gateway + private string _networkInterface_Gateway; + public string NetworkInterface_Gateway + { + get => _networkInterface_Gateway; + set { - get => _networkInterface_Gateway; - set - { - if (value == _networkInterface_Gateway) - return; + if (value == _networkInterface_Gateway) + return; - _networkInterface_Gateway = value; - OnPropertyChanged(); - } + _networkInterface_Gateway = value; + OnPropertyChanged(); } + } - private bool _networkInterface_EnableDynamicDNS = true; - public bool NetworkInterface_EnableDynamicDNS + private bool _networkInterface_EnableDynamicDNS = true; + public bool NetworkInterface_EnableDynamicDNS + { + get => _networkInterface_EnableDynamicDNS; + set { - get => _networkInterface_EnableDynamicDNS; - set - { - if (value == _networkInterface_EnableDynamicDNS) - return; + if (value == _networkInterface_EnableDynamicDNS) + return; - _networkInterface_EnableDynamicDNS = value; - OnPropertyChanged(); - } + _networkInterface_EnableDynamicDNS = value; + OnPropertyChanged(); } + } - private bool _networkInterface_EnableStaticDNS; - public bool NetworkInterface_EnableStaticDNS + private bool _networkInterface_EnableStaticDNS; + public bool NetworkInterface_EnableStaticDNS + { + get => _networkInterface_EnableStaticDNS; + set { - get => _networkInterface_EnableStaticDNS; - set - { - if (value == _networkInterface_EnableStaticDNS) - return; + if (value == _networkInterface_EnableStaticDNS) + return; - _networkInterface_EnableStaticDNS = value; - OnPropertyChanged(); - } + _networkInterface_EnableStaticDNS = value; + OnPropertyChanged(); } + } - private string _networkInterface_PrimaryDNSServer; - public string NetworkInterface_PrimaryDNSServer + private string _networkInterface_PrimaryDNSServer; + public string NetworkInterface_PrimaryDNSServer + { + get => _networkInterface_PrimaryDNSServer; + set { - get => _networkInterface_PrimaryDNSServer; - set - { - if (value == _networkInterface_PrimaryDNSServer) - return; + if (value == _networkInterface_PrimaryDNSServer) + return; - _networkInterface_PrimaryDNSServer = value; - OnPropertyChanged(); - } + _networkInterface_PrimaryDNSServer = value; + OnPropertyChanged(); } + } - private string _networkInterface_SecondaryDNSServer; - public string NetworkInterface_SecondaryDNSServer + private string _networkInterface_SecondaryDNSServer; + public string NetworkInterface_SecondaryDNSServer + { + get => _networkInterface_SecondaryDNSServer; + set { - get => _networkInterface_SecondaryDNSServer; - set - { - if (value == _networkInterface_SecondaryDNSServer) - return; + if (value == _networkInterface_SecondaryDNSServer) + return; - _networkInterface_SecondaryDNSServer = value; - OnPropertyChanged(); - } + _networkInterface_SecondaryDNSServer = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region IP Scanner - private bool _ipScanner_Enabled; - public bool IPScanner_Enabled + #region IP Scanner + private bool _ipScanner_Enabled; + public bool IPScanner_Enabled + { + get => _ipScanner_Enabled; + set { - get => _ipScanner_Enabled; - set - { - if (value == _ipScanner_Enabled) - return; + if (value == _ipScanner_Enabled) + return; - _ipScanner_Enabled = value; + _ipScanner_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _ipScanner_InheritHost; - public bool IPScanner_InheritHost + private bool _ipScanner_InheritHost; + public bool IPScanner_InheritHost + { + get => _ipScanner_InheritHost; + set { - get => _ipScanner_InheritHost; - set - { - if (value == _ipScanner_InheritHost) - return; + if (value == _ipScanner_InheritHost) + return; - _ipScanner_InheritHost = value; - OnPropertyChanged(); - } + _ipScanner_InheritHost = value; + OnPropertyChanged(); } + } - private string _ipScanner_HostOrIPRange; - public string IPScanner_HostOrIPRange + private string _ipScanner_HostOrIPRange; + public string IPScanner_HostOrIPRange + { + get => _ipScanner_HostOrIPRange; + set { - get => _ipScanner_HostOrIPRange; - set - { - if (value == _ipScanner_HostOrIPRange) - return; + if (value == _ipScanner_HostOrIPRange) + return; - _ipScanner_HostOrIPRange = value; - OnPropertyChanged(); - } + _ipScanner_HostOrIPRange = value; + OnPropertyChanged(); } + } - #endregion + #endregion - #region Port Scanner - private bool _portScanner_Enabled; - public bool PortScanner_Enabled + #region Port Scanner + private bool _portScanner_Enabled; + public bool PortScanner_Enabled + { + get => _portScanner_Enabled; + set { - get => _portScanner_Enabled; - set - { - if (value == _portScanner_Enabled) - return; + if (value == _portScanner_Enabled) + return; - _portScanner_Enabled = value; + _portScanner_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _portScanner_InheritHost; - public bool PortScanner_InheritHost + private bool _portScanner_InheritHost; + public bool PortScanner_InheritHost + { + get => _portScanner_InheritHost; + set { - get => _portScanner_InheritHost; - set - { - if (value == _portScanner_InheritHost) - return; + if (value == _portScanner_InheritHost) + return; - _portScanner_InheritHost = value; - OnPropertyChanged(); - } + _portScanner_InheritHost = value; + OnPropertyChanged(); } + } - private string _portScanner_Host; - public string PortScanner_Host + private string _portScanner_Host; + public string PortScanner_Host + { + get => _portScanner_Host; + set { - get => _portScanner_Host; - set - { - if (value == _portScanner_Host) - return; + if (value == _portScanner_Host) + return; - _portScanner_Host = value; - OnPropertyChanged(); - } + _portScanner_Host = value; + OnPropertyChanged(); } + } - private string _portScanner_Ports; - public string PortScanner_Ports + private string _portScanner_Ports; + public string PortScanner_Ports + { + get => _portScanner_Ports; + set { - get => _portScanner_Ports; - set - { - if (value == _portScanner_Ports) - return; + if (value == _portScanner_Ports) + return; - _portScanner_Ports = value; - OnPropertyChanged(); - } + _portScanner_Ports = value; + OnPropertyChanged(); } + } - #endregion + #endregion - #region Ping Monitor - private bool _pingMonitor_Enabled; - public bool PingMonitor_Enabled + #region Ping Monitor + private bool _pingMonitor_Enabled; + public bool PingMonitor_Enabled + { + get => _pingMonitor_Enabled; + set { - get => _pingMonitor_Enabled; - set - { - if (value == _pingMonitor_Enabled) - return; + if (value == _pingMonitor_Enabled) + return; - _pingMonitor_Enabled = value; + _pingMonitor_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _pingMonitor_InheritHost; - public bool PingMonitor_InheritHost + private bool _pingMonitor_InheritHost; + public bool PingMonitor_InheritHost + { + get => _pingMonitor_InheritHost; + set { - get => _pingMonitor_InheritHost; - set - { - if (value == _pingMonitor_InheritHost) - return; + if (value == _pingMonitor_InheritHost) + return; - _pingMonitor_InheritHost = value; - OnPropertyChanged(); - } + _pingMonitor_InheritHost = value; + OnPropertyChanged(); } + } - private string _pingMonitor_Host; - public string PingMonitor_Host + private string _pingMonitor_Host; + public string PingMonitor_Host + { + get => _pingMonitor_Host; + set { - get => _pingMonitor_Host; - set - { - if (value == _pingMonitor_Host) - return; + if (value == _pingMonitor_Host) + return; - _pingMonitor_Host = value; - OnPropertyChanged(); - } + _pingMonitor_Host = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Traceroute - private bool _traceroute_Enabled; - public bool Traceroute_Enabled + #region Traceroute + private bool _traceroute_Enabled; + public bool Traceroute_Enabled + { + get => _traceroute_Enabled; + set { - get => _traceroute_Enabled; - set - { - if (value == _traceroute_Enabled) - return; + if (value == _traceroute_Enabled) + return; - _traceroute_Enabled = value; + _traceroute_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _traceroute_InheritHost; - public bool Traceroute_InheritHost + private bool _traceroute_InheritHost; + public bool Traceroute_InheritHost + { + get => _traceroute_InheritHost; + set { - get => _traceroute_InheritHost; - set - { - if (value == _traceroute_InheritHost) - return; + if (value == _traceroute_InheritHost) + return; - _traceroute_InheritHost = value; - OnPropertyChanged(); - } + _traceroute_InheritHost = value; + OnPropertyChanged(); } + } - private string _traceroute_Host; - public string Traceroute_Host + private string _traceroute_Host; + public string Traceroute_Host + { + get => _traceroute_Host; + set { - get => _traceroute_Host; - set - { - if (value == _traceroute_Host) - return; + if (value == _traceroute_Host) + return; - _traceroute_Host = value; - OnPropertyChanged(); - } + _traceroute_Host = value; + OnPropertyChanged(); } + } - #endregion + #endregion - #region DNS Lookup - private bool _dnsLookup_Enabled; - public bool DNSLookup_Enabled + #region DNS Lookup + private bool _dnsLookup_Enabled; + public bool DNSLookup_Enabled + { + get => _dnsLookup_Enabled; + set { - get => _dnsLookup_Enabled; - set - { - if (value == _dnsLookup_Enabled) - return; + if (value == _dnsLookup_Enabled) + return; - _dnsLookup_Enabled = value; + _dnsLookup_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _dnsLookup_InheritHost; - public bool DNSLookup_InheritHost + private bool _dnsLookup_InheritHost; + public bool DNSLookup_InheritHost + { + get => _dnsLookup_InheritHost; + set { - get => _dnsLookup_InheritHost; - set - { - if (value == _dnsLookup_InheritHost) - return; + if (value == _dnsLookup_InheritHost) + return; - _dnsLookup_InheritHost = value; - OnPropertyChanged(); - } + _dnsLookup_InheritHost = value; + OnPropertyChanged(); } + } - private string _dnsLookup_Host; - public string DNSLookup_Host + private string _dnsLookup_Host; + public string DNSLookup_Host + { + get => _dnsLookup_Host; + set { - get => _dnsLookup_Host; - set - { - if (value == _dnsLookup_Host) - return; + if (value == _dnsLookup_Host) + return; - _dnsLookup_Host = value; - OnPropertyChanged(); - } + _dnsLookup_Host = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Remote Desktop - private bool _remoteDesktop_Enabled; - public bool RemoteDesktop_Enabled + #region Remote Desktop + private bool _remoteDesktop_Enabled; + public bool RemoteDesktop_Enabled + { + get => _remoteDesktop_Enabled; + set { - get => _remoteDesktop_Enabled; - set - { - if (value == _remoteDesktop_Enabled) - return; + if (value == _remoteDesktop_Enabled) + return; - _remoteDesktop_Enabled = value; + _remoteDesktop_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _remoteDesktop_InheritHost; - public bool RemoteDesktop_InheritHost + private bool _remoteDesktop_InheritHost; + public bool RemoteDesktop_InheritHost + { + get => _remoteDesktop_InheritHost; + set { - get => _remoteDesktop_InheritHost; - set - { - if (value == _remoteDesktop_InheritHost) - return; + if (value == _remoteDesktop_InheritHost) + return; - _remoteDesktop_InheritHost = value; - OnPropertyChanged(); - } + _remoteDesktop_InheritHost = value; + OnPropertyChanged(); } + } - private string _remoteDesktop_Host; - public string RemoteDesktop_Host + private string _remoteDesktop_Host; + public string RemoteDesktop_Host + { + get => _remoteDesktop_Host; + set { - get => _remoteDesktop_Host; - set - { - if (value == _remoteDesktop_Host) - return; + if (value == _remoteDesktop_Host) + return; - _remoteDesktop_Host = value; - OnPropertyChanged(); - } + _remoteDesktop_Host = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_UseCredentials; - public bool RemoteDesktop_UseCredentials + private bool _remoteDesktop_UseCredentials; + public bool RemoteDesktop_UseCredentials + { + get => _remoteDesktop_UseCredentials; + set { - get => _remoteDesktop_UseCredentials; - set - { - if (value == _remoteDesktop_UseCredentials) - return; + if (value == _remoteDesktop_UseCredentials) + return; - _remoteDesktop_UseCredentials = value; - OnPropertyChanged(); - } + _remoteDesktop_UseCredentials = value; + OnPropertyChanged(); } + } - private string _remoteDesktop_Username; - public string RemoteDesktop_Username + private string _remoteDesktop_Username; + public string RemoteDesktop_Username + { + get => _remoteDesktop_Username; + set { - get => _remoteDesktop_Username; - set - { - if (value == _remoteDesktop_Username) - return; + if (value == _remoteDesktop_Username) + return; - _remoteDesktop_Username = value; - OnPropertyChanged(); - } + _remoteDesktop_Username = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_IsPasswordEmpty = true; // Initial it's empty - public bool RemoteDesktop_IsPasswordEmpty + private bool _remoteDesktop_IsPasswordEmpty = true; // Initial it's empty + public bool RemoteDesktop_IsPasswordEmpty + { + get => _remoteDesktop_IsPasswordEmpty; + set { - get => _remoteDesktop_IsPasswordEmpty; - set - { - if (value == _remoteDesktop_IsPasswordEmpty) - return; + if (value == _remoteDesktop_IsPasswordEmpty) + return; - _remoteDesktop_IsPasswordEmpty = value; - OnPropertyChanged(); - } + _remoteDesktop_IsPasswordEmpty = value; + OnPropertyChanged(); } + } - private SecureString _remoteDesktop_Password; + private SecureString _remoteDesktop_Password; - /// - /// RemoteDesktop password as secure string. - /// - public SecureString RemoteDesktop_Password + /// + /// RemoteDesktop password as secure string. + /// + public SecureString RemoteDesktop_Password + { + get => _remoteDesktop_Password; + set { - get => _remoteDesktop_Password; - set - { - if (value == _remoteDesktop_Password) - return; + if (value == _remoteDesktop_Password) + return; - // Validate the password string - RemoteDesktop_IsPasswordEmpty = value == null || string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); + // Validate the password string + RemoteDesktop_IsPasswordEmpty = value == null || string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); - _remoteDesktop_Password = value; - OnPropertyChanged(); - } + _remoteDesktop_Password = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_PasswordChanged; - public bool RemoteDesktop_PasswordChanged + private bool _remoteDesktop_PasswordChanged; + public bool RemoteDesktop_PasswordChanged + { + get => _remoteDesktop_PasswordChanged; + set { - get => _remoteDesktop_PasswordChanged; - set - { - if (value == _remoteDesktop_PasswordChanged) - return; + if (value == _remoteDesktop_PasswordChanged) + return; - _remoteDesktop_PasswordChanged = value; - OnPropertyChanged(); - } + _remoteDesktop_PasswordChanged = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideDisplay; - public bool RemoteDesktop_OverrideDisplay + private bool _remoteDesktop_OverrideDisplay; + public bool RemoteDesktop_OverrideDisplay + { + get => _remoteDesktop_OverrideDisplay; + set { - get => _remoteDesktop_OverrideDisplay; - set - { - if (value == _remoteDesktop_OverrideDisplay) - return; + if (value == _remoteDesktop_OverrideDisplay) + return; - _remoteDesktop_OverrideDisplay = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideDisplay = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_AdjustScreenAutomatically; - public bool RemoteDesktop_AdjustScreenAutomatically + private bool _remoteDesktop_AdjustScreenAutomatically; + public bool RemoteDesktop_AdjustScreenAutomatically + { + get => _remoteDesktop_AdjustScreenAutomatically; + set { - get => _remoteDesktop_AdjustScreenAutomatically; - set - { - if (value == _remoteDesktop_AdjustScreenAutomatically) - return; + if (value == _remoteDesktop_AdjustScreenAutomatically) + return; - _remoteDesktop_AdjustScreenAutomatically = value; - OnPropertyChanged(); - } + _remoteDesktop_AdjustScreenAutomatically = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_UseCurrentViewSize; - public bool RemoteDesktop_UseCurrentViewSize + private bool _remoteDesktop_UseCurrentViewSize; + public bool RemoteDesktop_UseCurrentViewSize + { + get => _remoteDesktop_UseCurrentViewSize; + set { - get => _remoteDesktop_UseCurrentViewSize; - set - { - if (value == _remoteDesktop_UseCurrentViewSize) - return; + if (value == _remoteDesktop_UseCurrentViewSize) + return; - _remoteDesktop_UseCurrentViewSize = value; - OnPropertyChanged(); - } + _remoteDesktop_UseCurrentViewSize = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_UseFixedScreenSize; - public bool RemoteDesktop_UseFixedScreenSize + private bool _remoteDesktop_UseFixedScreenSize; + public bool RemoteDesktop_UseFixedScreenSize + { + get => _remoteDesktop_UseFixedScreenSize; + set { - get => _remoteDesktop_UseFixedScreenSize; - set - { - if (value == _remoteDesktop_UseFixedScreenSize) - return; + if (value == _remoteDesktop_UseFixedScreenSize) + return; - _remoteDesktop_UseFixedScreenSize = value; - OnPropertyChanged(); - } + _remoteDesktop_UseFixedScreenSize = value; + OnPropertyChanged(); } + } - public List RemoteDesktop_ScreenResolutions => RemoteDesktop.ScreenResolutions; + public List RemoteDesktop_ScreenResolutions => RemoteDesktop.ScreenResolutions; - public int RemoteDesktop_ScreenWidth; - public int RemoteDesktop_ScreenHeight; + public int RemoteDesktop_ScreenWidth; + public int RemoteDesktop_ScreenHeight; - private string _remoteDesktop_SelectedScreenResolution; - public string RemoteDesktop_SelectedScreenResolution + private string _remoteDesktop_SelectedScreenResolution; + public string RemoteDesktop_SelectedScreenResolution + { + get => _remoteDesktop_SelectedScreenResolution; + set { - get => _remoteDesktop_SelectedScreenResolution; - set - { - if (value == _remoteDesktop_SelectedScreenResolution) - return; + if (value == _remoteDesktop_SelectedScreenResolution) + return; - var resolution = value.Split('x'); + var resolution = value.Split('x'); - RemoteDesktop_ScreenWidth = int.Parse(resolution[0]); - RemoteDesktop_ScreenHeight = int.Parse(resolution[1]); + RemoteDesktop_ScreenWidth = int.Parse(resolution[0]); + RemoteDesktop_ScreenHeight = int.Parse(resolution[1]); - _remoteDesktop_SelectedScreenResolution = value; - OnPropertyChanged(); - } + _remoteDesktop_SelectedScreenResolution = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_UseCustomScreenSize; - public bool RemoteDesktop_UseCustomScreenSize + private bool _remoteDesktop_UseCustomScreenSize; + public bool RemoteDesktop_UseCustomScreenSize + { + get => _remoteDesktop_UseCustomScreenSize; + set { - get => _remoteDesktop_UseCustomScreenSize; - set - { - if (value == _remoteDesktop_UseCustomScreenSize) - return; + if (value == _remoteDesktop_UseCustomScreenSize) + return; - _remoteDesktop_UseCustomScreenSize = value; - OnPropertyChanged(); - } + _remoteDesktop_UseCustomScreenSize = value; + OnPropertyChanged(); } + } - private string _remoteDesktop_CustomScreenWidth; - public string RemoteDesktop_CustomScreenWidth + private string _remoteDesktop_CustomScreenWidth; + public string RemoteDesktop_CustomScreenWidth + { + get => _remoteDesktop_CustomScreenWidth; + set { - get => _remoteDesktop_CustomScreenWidth; - set - { - if (value == _remoteDesktop_CustomScreenWidth) - return; + if (value == _remoteDesktop_CustomScreenWidth) + return; - _remoteDesktop_CustomScreenWidth = value; - OnPropertyChanged(); - } + _remoteDesktop_CustomScreenWidth = value; + OnPropertyChanged(); } + } - private string _remoteDesktop_CustomScreenHeight; - public string RemoteDesktop_CustomScreenHeight + private string _remoteDesktop_CustomScreenHeight; + public string RemoteDesktop_CustomScreenHeight + { + get => _remoteDesktop_CustomScreenHeight; + set { - get => _remoteDesktop_CustomScreenHeight; - set - { - if (value == _remoteDesktop_CustomScreenHeight) - return; + if (value == _remoteDesktop_CustomScreenHeight) + return; - _remoteDesktop_CustomScreenHeight = value; - OnPropertyChanged(); - } + _remoteDesktop_CustomScreenHeight = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideColorDepth; - public bool RemoteDesktop_OverrideColorDepth + private bool _remoteDesktop_OverrideColorDepth; + public bool RemoteDesktop_OverrideColorDepth + { + get => _remoteDesktop_OverrideColorDepth; + set { - get => _remoteDesktop_OverrideColorDepth; - set - { - if (value == _remoteDesktop_OverrideColorDepth) - return; + if (value == _remoteDesktop_OverrideColorDepth) + return; - _remoteDesktop_OverrideColorDepth = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideColorDepth = value; + OnPropertyChanged(); } + } - public List RemoteDesktop_ColorDepths => RemoteDesktop.ColorDepths; + public List RemoteDesktop_ColorDepths => RemoteDesktop.ColorDepths; - private int _remoteDesktop_SelectedColorDepth; - public int RemoteDesktop_SelectedColorDepth + private int _remoteDesktop_SelectedColorDepth; + public int RemoteDesktop_SelectedColorDepth + { + get => _remoteDesktop_SelectedColorDepth; + set { - get => _remoteDesktop_SelectedColorDepth; - set - { - if (value == _remoteDesktop_SelectedColorDepth) - return; + if (value == _remoteDesktop_SelectedColorDepth) + return; - _remoteDesktop_SelectedColorDepth = value; - OnPropertyChanged(); - } + _remoteDesktop_SelectedColorDepth = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverridePort; - public bool RemoteDesktop_OverridePort + private bool _remoteDesktop_OverridePort; + public bool RemoteDesktop_OverridePort + { + get => _remoteDesktop_OverridePort; + set { - get => _remoteDesktop_OverridePort; - set - { - if (value == _remoteDesktop_OverridePort) - return; + if (value == _remoteDesktop_OverridePort) + return; - _remoteDesktop_OverridePort = value; - OnPropertyChanged(); - } + _remoteDesktop_OverridePort = value; + OnPropertyChanged(); } + } - private int _remoteDesktop_Port; - public int RemoteDesktop_Port + private int _remoteDesktop_Port; + public int RemoteDesktop_Port + { + get => _remoteDesktop_Port; + set { - get => _remoteDesktop_Port; - set - { - if (value == _remoteDesktop_Port) - return; + if (value == _remoteDesktop_Port) + return; - _remoteDesktop_Port = value; - OnPropertyChanged(); - } + _remoteDesktop_Port = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideCredSspSupport; - public bool RemoteDesktop_OverrideCredSspSupport + private bool _remoteDesktop_OverrideCredSspSupport; + public bool RemoteDesktop_OverrideCredSspSupport + { + get => _remoteDesktop_OverrideCredSspSupport; + set { - get => _remoteDesktop_OverrideCredSspSupport; - set - { - if (value == _remoteDesktop_OverrideCredSspSupport) - return; + if (value == _remoteDesktop_OverrideCredSspSupport) + return; - _remoteDesktop_OverrideCredSspSupport = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideCredSspSupport = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_EnableCredSspSupport; - public bool RemoteDesktop_EnableCredSspSupport + private bool _remoteDesktop_EnableCredSspSupport; + public bool RemoteDesktop_EnableCredSspSupport + { + get => _remoteDesktop_EnableCredSspSupport; + set { - get => _remoteDesktop_EnableCredSspSupport; - set - { - if (value == _remoteDesktop_EnableCredSspSupport) - return; + if (value == _remoteDesktop_EnableCredSspSupport) + return; - _remoteDesktop_EnableCredSspSupport = value; - OnPropertyChanged(); - } + _remoteDesktop_EnableCredSspSupport = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideAuthenticationLevel; - public bool RemoteDesktop_OverrideAuthenticationLevel + private bool _remoteDesktop_OverrideAuthenticationLevel; + public bool RemoteDesktop_OverrideAuthenticationLevel + { + get => _remoteDesktop_OverrideAuthenticationLevel; + set { - get => _remoteDesktop_OverrideAuthenticationLevel; - set - { - if (value == _remoteDesktop_OverrideAuthenticationLevel) - return; + if (value == _remoteDesktop_OverrideAuthenticationLevel) + return; - _remoteDesktop_OverrideAuthenticationLevel = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideAuthenticationLevel = value; + OnPropertyChanged(); } + } - private uint _remoteDesktop_AuthenticationLevel; - public uint RemoteDesktop_AuthenticationLevel + private uint _remoteDesktop_AuthenticationLevel; + public uint RemoteDesktop_AuthenticationLevel + { + get => _remoteDesktop_AuthenticationLevel; + set { - get => _remoteDesktop_AuthenticationLevel; - set - { - if (value == _remoteDesktop_AuthenticationLevel) - return; + if (value == _remoteDesktop_AuthenticationLevel) + return; - _remoteDesktop_AuthenticationLevel = value; - OnPropertyChanged(); - } + _remoteDesktop_AuthenticationLevel = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideAudioRedirectionMode; - public bool RemoteDesktop_OverrideAudioRedirectionMode + private bool _remoteDesktop_OverrideAudioRedirectionMode; + public bool RemoteDesktop_OverrideAudioRedirectionMode + { + get => _remoteDesktop_OverrideAudioRedirectionMode; + set { - get => _remoteDesktop_OverrideAudioRedirectionMode; - set - { - if (value == _remoteDesktop_OverrideAudioRedirectionMode) - return; + if (value == _remoteDesktop_OverrideAudioRedirectionMode) + return; - _remoteDesktop_OverrideAudioRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideAudioRedirectionMode = value; + OnPropertyChanged(); } + } - public IEnumerable RemoteDesktop_AudioRedirectionModes => Enum.GetValues(typeof(AudioRedirectionMode)).Cast(); + public IEnumerable RemoteDesktop_AudioRedirectionModes => Enum.GetValues(typeof(AudioRedirectionMode)).Cast(); - private AudioRedirectionMode _remoteDesktop_AudioRedirectionMode; - public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode + private AudioRedirectionMode _remoteDesktop_AudioRedirectionMode; + public AudioRedirectionMode RemoteDesktop_AudioRedirectionMode + { + get => _remoteDesktop_AudioRedirectionMode; + set { - get => _remoteDesktop_AudioRedirectionMode; - set - { - if (Equals(value, _remoteDesktop_AudioRedirectionMode)) - return; + if (Equals(value, _remoteDesktop_AudioRedirectionMode)) + return; - _remoteDesktop_AudioRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_AudioRedirectionMode = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideAudioCaptureRedirectionMode; - public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode + private bool _remoteDesktop_OverrideAudioCaptureRedirectionMode; + public bool RemoteDesktop_OverrideAudioCaptureRedirectionMode + { + get => _remoteDesktop_OverrideAudioCaptureRedirectionMode; + set { - get => _remoteDesktop_OverrideAudioCaptureRedirectionMode; - set - { - if (value == _remoteDesktop_OverrideAudioCaptureRedirectionMode) - return; + if (value == _remoteDesktop_OverrideAudioCaptureRedirectionMode) + return; - _remoteDesktop_OverrideAudioCaptureRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideAudioCaptureRedirectionMode = value; + OnPropertyChanged(); } + } - public IEnumerable RemoteDesktop_AudioCaptureRedirectionModes => Enum.GetValues(typeof(AudioCaptureRedirectionMode)).Cast(); + public IEnumerable RemoteDesktop_AudioCaptureRedirectionModes => Enum.GetValues(typeof(AudioCaptureRedirectionMode)).Cast(); - private AudioCaptureRedirectionMode _remoteDesktop_AudioCaptureRedirectionMode; - public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode + private AudioCaptureRedirectionMode _remoteDesktop_AudioCaptureRedirectionMode; + public AudioCaptureRedirectionMode RemoteDesktop_AudioCaptureRedirectionMode + { + get => _remoteDesktop_AudioCaptureRedirectionMode; + set { - get => _remoteDesktop_AudioCaptureRedirectionMode; - set - { - if (Equals(value, _remoteDesktop_AudioCaptureRedirectionMode)) - return; + if (Equals(value, _remoteDesktop_AudioCaptureRedirectionMode)) + return; - _remoteDesktop_AudioCaptureRedirectionMode = value; - OnPropertyChanged(); - } + _remoteDesktop_AudioCaptureRedirectionMode = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideApplyWindowsKeyCombinations; - public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations + private bool _remoteDesktop_OverrideApplyWindowsKeyCombinations; + public bool RemoteDesktop_OverrideApplyWindowsKeyCombinations + { + get => _remoteDesktop_OverrideApplyWindowsKeyCombinations; + set { - get => _remoteDesktop_OverrideApplyWindowsKeyCombinations; - set - { - if (value == _remoteDesktop_OverrideApplyWindowsKeyCombinations) - return; + if (value == _remoteDesktop_OverrideApplyWindowsKeyCombinations) + return; - _remoteDesktop_OverrideApplyWindowsKeyCombinations = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideApplyWindowsKeyCombinations = value; + OnPropertyChanged(); } + } - public IEnumerable RemoteDesktop_KeyboardHookModes => System.Enum.GetValues(typeof(KeyboardHookMode)).Cast(); + public IEnumerable RemoteDesktop_KeyboardHookModes => System.Enum.GetValues(typeof(KeyboardHookMode)).Cast(); - private KeyboardHookMode _remoteDesktop_KeyboardHookMode; - public KeyboardHookMode RemoteDesktop_KeyboardHookMode + private KeyboardHookMode _remoteDesktop_KeyboardHookMode; + public KeyboardHookMode RemoteDesktop_KeyboardHookMode + { + get => _remoteDesktop_KeyboardHookMode; + set { - get => _remoteDesktop_KeyboardHookMode; - set - { - if (Equals(value, _remoteDesktop_KeyboardHookMode)) - return; + if (Equals(value, _remoteDesktop_KeyboardHookMode)) + return; - _remoteDesktop_KeyboardHookMode = value; - OnPropertyChanged(); - } + _remoteDesktop_KeyboardHookMode = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectClipboard; - public bool RemoteDesktop_OverrideRedirectClipboard + private bool _remoteDesktop_OverrideRedirectClipboard; + public bool RemoteDesktop_OverrideRedirectClipboard + { + get => _remoteDesktop_OverrideRedirectClipboard; + set { - get => _remoteDesktop_OverrideRedirectClipboard; - set - { - if (value == _remoteDesktop_OverrideRedirectClipboard) - return; + if (value == _remoteDesktop_OverrideRedirectClipboard) + return; - _remoteDesktop_OverrideRedirectClipboard = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectClipboard = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectClipboard; - public bool RemoteDesktop_RedirectClipboard + private bool _remoteDesktop_RedirectClipboard; + public bool RemoteDesktop_RedirectClipboard + { + get => _remoteDesktop_RedirectClipboard; + set { - get => _remoteDesktop_RedirectClipboard; - set - { - if (value == _remoteDesktop_RedirectClipboard) - return; + if (value == _remoteDesktop_RedirectClipboard) + return; - _remoteDesktop_RedirectClipboard = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectClipboard = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectDevices; - public bool RemoteDesktop_OverrideRedirectDevices + private bool _remoteDesktop_OverrideRedirectDevices; + public bool RemoteDesktop_OverrideRedirectDevices + { + get => _remoteDesktop_OverrideRedirectDevices; + set { - get => _remoteDesktop_OverrideRedirectDevices; - set - { - if (value == _remoteDesktop_OverrideRedirectDevices) - return; + if (value == _remoteDesktop_OverrideRedirectDevices) + return; - _remoteDesktop_OverrideRedirectDevices = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectDevices = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectDevices; - public bool RemoteDesktop_RedirectDevices + private bool _remoteDesktop_RedirectDevices; + public bool RemoteDesktop_RedirectDevices + { + get => _remoteDesktop_RedirectDevices; + set { - get => _remoteDesktop_RedirectDevices; - set - { - if (value == _remoteDesktop_RedirectDevices) - return; + if (value == _remoteDesktop_RedirectDevices) + return; - _remoteDesktop_RedirectDevices = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectDevices = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectDrives; - public bool RemoteDesktop_OverrideRedirectDrives + private bool _remoteDesktop_OverrideRedirectDrives; + public bool RemoteDesktop_OverrideRedirectDrives + { + get => _remoteDesktop_OverrideRedirectDrives; + set { - get => _remoteDesktop_OverrideRedirectDrives; - set - { - if (value == _remoteDesktop_OverrideRedirectDrives) - return; + if (value == _remoteDesktop_OverrideRedirectDrives) + return; - _remoteDesktop_OverrideRedirectDrives = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectDrives = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectDrives; - public bool RemoteDesktop_RedirectDrives + private bool _remoteDesktop_RedirectDrives; + public bool RemoteDesktop_RedirectDrives + { + get => _remoteDesktop_RedirectDrives; + set { - get => _remoteDesktop_RedirectDrives; - set - { - if (value == _remoteDesktop_RedirectDrives) - return; + if (value == _remoteDesktop_RedirectDrives) + return; - _remoteDesktop_RedirectDrives = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectDrives = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectPorts; - public bool RemoteDesktop_OverrideRedirectPorts + private bool _remoteDesktop_OverrideRedirectPorts; + public bool RemoteDesktop_OverrideRedirectPorts + { + get => _remoteDesktop_OverrideRedirectPorts; + set { - get => _remoteDesktop_OverrideRedirectPorts; - set - { - if (value == _remoteDesktop_OverrideRedirectPorts) - return; + if (value == _remoteDesktop_OverrideRedirectPorts) + return; - _remoteDesktop_OverrideRedirectPorts = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectPorts = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectPorts; - public bool RemoteDesktop_RedirectPorts + private bool _remoteDesktop_RedirectPorts; + public bool RemoteDesktop_RedirectPorts + { + get => _remoteDesktop_RedirectPorts; + set { - get => _remoteDesktop_RedirectPorts; - set - { - if (value == _remoteDesktop_RedirectPorts) - return; + if (value == _remoteDesktop_RedirectPorts) + return; - _remoteDesktop_RedirectPorts = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectPorts = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectSmartcards; - public bool RemoteDesktop_OverrideRedirectSmartcards + private bool _remoteDesktop_OverrideRedirectSmartcards; + public bool RemoteDesktop_OverrideRedirectSmartcards + { + get => _remoteDesktop_OverrideRedirectSmartcards; + set { - get => _remoteDesktop_OverrideRedirectSmartcards; - set - { - if (value == _remoteDesktop_OverrideRedirectSmartcards) - return; + if (value == _remoteDesktop_OverrideRedirectSmartcards) + return; - _remoteDesktop_OverrideRedirectSmartcards = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectSmartcards = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectSmartCards; - public bool RemoteDesktop_RedirectSmartCards + private bool _remoteDesktop_RedirectSmartCards; + public bool RemoteDesktop_RedirectSmartCards + { + get => _remoteDesktop_RedirectSmartCards; + set { - get => _remoteDesktop_RedirectSmartCards; - set - { - if (value == _remoteDesktop_RedirectSmartCards) - return; + if (value == _remoteDesktop_RedirectSmartCards) + return; - _remoteDesktop_RedirectSmartCards = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectSmartCards = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideRedirectPrinters; - public bool RemoteDesktop_OverrideRedirectPrinters + private bool _remoteDesktop_OverrideRedirectPrinters; + public bool RemoteDesktop_OverrideRedirectPrinters + { + get => _remoteDesktop_OverrideRedirectPrinters; + set { - get => _remoteDesktop_OverrideRedirectPrinters; - set - { - if (value == _remoteDesktop_OverrideRedirectPrinters) - return; + if (value == _remoteDesktop_OverrideRedirectPrinters) + return; - _remoteDesktop_OverrideRedirectPrinters = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideRedirectPrinters = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_RedirectPrinters; - public bool RemoteDesktop_RedirectPrinters + private bool _remoteDesktop_RedirectPrinters; + public bool RemoteDesktop_RedirectPrinters + { + get => _remoteDesktop_RedirectPrinters; + set { - get => _remoteDesktop_RedirectPrinters; - set - { - if (value == _remoteDesktop_RedirectPrinters) - return; + if (value == _remoteDesktop_RedirectPrinters) + return; - _remoteDesktop_RedirectPrinters = value; - OnPropertyChanged(); - } + _remoteDesktop_RedirectPrinters = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverridePersistentBitmapCaching; - public bool RemoteDesktop_OverridePersistentBitmapCaching + private bool _remoteDesktop_OverridePersistentBitmapCaching; + public bool RemoteDesktop_OverridePersistentBitmapCaching + { + get => _remoteDesktop_OverridePersistentBitmapCaching; + set { - get => _remoteDesktop_OverridePersistentBitmapCaching; - set - { - if (value == _remoteDesktop_OverridePersistentBitmapCaching) - return; + if (value == _remoteDesktop_OverridePersistentBitmapCaching) + return; - _remoteDesktop_OverridePersistentBitmapCaching = value; - OnPropertyChanged(); - } + _remoteDesktop_OverridePersistentBitmapCaching = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_PersistentBitmapCaching; - public bool RemoteDesktop_PersistentBitmapCaching + private bool _remoteDesktop_PersistentBitmapCaching; + public bool RemoteDesktop_PersistentBitmapCaching + { + get => _remoteDesktop_PersistentBitmapCaching; + set { - get => _remoteDesktop_PersistentBitmapCaching; - set - { - if (value == _remoteDesktop_PersistentBitmapCaching) - return; + if (value == _remoteDesktop_PersistentBitmapCaching) + return; - _remoteDesktop_PersistentBitmapCaching = value; - OnPropertyChanged(); - } + _remoteDesktop_PersistentBitmapCaching = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped + private bool _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + public bool RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped + { + get => _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + set { - get => _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - set - { - if (value == _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped) - return; + if (value == _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped) + return; - _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideReconnectIfTheConnectionIsDropped = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_ReconnectIfTheConnectionIsDropped; - public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped + private bool _remoteDesktop_ReconnectIfTheConnectionIsDropped; + public bool RemoteDesktop_ReconnectIfTheConnectionIsDropped + { + get => _remoteDesktop_ReconnectIfTheConnectionIsDropped; + set { - get => _remoteDesktop_ReconnectIfTheConnectionIsDropped; - set - { - if (value == _remoteDesktop_ReconnectIfTheConnectionIsDropped) - return; + if (value == _remoteDesktop_ReconnectIfTheConnectionIsDropped) + return; - _remoteDesktop_ReconnectIfTheConnectionIsDropped = value; - OnPropertyChanged(); - } + _remoteDesktop_ReconnectIfTheConnectionIsDropped = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_OverrideNetworkConnectionType; - public bool RemoteDesktop_OverrideNetworkConnectionType + private bool _remoteDesktop_OverrideNetworkConnectionType; + public bool RemoteDesktop_OverrideNetworkConnectionType + { + get => _remoteDesktop_OverrideNetworkConnectionType; + set { - get => _remoteDesktop_OverrideNetworkConnectionType; - set - { - if (value == _remoteDesktop_OverrideNetworkConnectionType) - return; + if (value == _remoteDesktop_OverrideNetworkConnectionType) + return; - _remoteDesktop_OverrideNetworkConnectionType = value; - OnPropertyChanged(); - } + _remoteDesktop_OverrideNetworkConnectionType = value; + OnPropertyChanged(); } + } - public IEnumerable RemoteDesktop_NetworkConnectionTypes => Enum.GetValues(typeof(NetworkConnectionType)).Cast(); + public IEnumerable RemoteDesktop_NetworkConnectionTypes => Enum.GetValues(typeof(NetworkConnectionType)).Cast(); - private NetworkConnectionType _remoteDesktop_NetworkConnectionType; - public NetworkConnectionType RemoteDesktop_NetworkConnectionType + private NetworkConnectionType _remoteDesktop_NetworkConnectionType; + public NetworkConnectionType RemoteDesktop_NetworkConnectionType + { + get => _remoteDesktop_NetworkConnectionType; + set { - get => _remoteDesktop_NetworkConnectionType; - set - { - if (Equals(value, _remoteDesktop_NetworkConnectionType)) - return; + if (Equals(value, _remoteDesktop_NetworkConnectionType)) + return; - if (!_isLoading) - ChangeNetworkConnectionTypeSettings(value); + if (!_isLoading) + ChangeNetworkConnectionTypeSettings(value); - _remoteDesktop_NetworkConnectionType = value; - OnPropertyChanged(); - } + _remoteDesktop_NetworkConnectionType = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_DesktopBackground; - public bool RemoteDesktop_DesktopBackground + private bool _remoteDesktop_DesktopBackground; + public bool RemoteDesktop_DesktopBackground + { + get => _remoteDesktop_DesktopBackground; + set { - get => _remoteDesktop_DesktopBackground; - set - { - if (value == _remoteDesktop_DesktopBackground) - return; + if (value == _remoteDesktop_DesktopBackground) + return; - _remoteDesktop_DesktopBackground = value; - OnPropertyChanged(); - } + _remoteDesktop_DesktopBackground = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_FontSmoothing; - public bool RemoteDesktop_FontSmoothing + private bool _remoteDesktop_FontSmoothing; + public bool RemoteDesktop_FontSmoothing + { + get => _remoteDesktop_FontSmoothing; + set { - get => _remoteDesktop_FontSmoothing; - set - { - if (value == _remoteDesktop_FontSmoothing) - return; + if (value == _remoteDesktop_FontSmoothing) + return; - _remoteDesktop_FontSmoothing = value; - OnPropertyChanged(); - } + _remoteDesktop_FontSmoothing = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_DesktopComposition; - public bool RemoteDesktop_DesktopComposition + private bool _remoteDesktop_DesktopComposition; + public bool RemoteDesktop_DesktopComposition + { + get => _remoteDesktop_DesktopComposition; + set { - get => _remoteDesktop_DesktopComposition; - set - { - if (value == _remoteDesktop_DesktopComposition) - return; + if (value == _remoteDesktop_DesktopComposition) + return; - _remoteDesktop_DesktopComposition = value; - OnPropertyChanged(); - } + _remoteDesktop_DesktopComposition = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_ShowWindowContentsWhileDragging; - public bool RemoteDesktop_ShowWindowContentsWhileDragging + private bool _remoteDesktop_ShowWindowContentsWhileDragging; + public bool RemoteDesktop_ShowWindowContentsWhileDragging + { + get => _remoteDesktop_ShowWindowContentsWhileDragging; + set { - get => _remoteDesktop_ShowWindowContentsWhileDragging; - set - { - if (value == _remoteDesktop_ShowWindowContentsWhileDragging) - return; + if (value == _remoteDesktop_ShowWindowContentsWhileDragging) + return; - _remoteDesktop_ShowWindowContentsWhileDragging = value; - OnPropertyChanged(); - } + _remoteDesktop_ShowWindowContentsWhileDragging = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_MenuAndWindowAnimation; - public bool RemoteDesktop_MenuAndWindowAnimation + private bool _remoteDesktop_MenuAndWindowAnimation; + public bool RemoteDesktop_MenuAndWindowAnimation + { + get => _remoteDesktop_MenuAndWindowAnimation; + set { - get => _remoteDesktop_MenuAndWindowAnimation; - set - { - if (value == _remoteDesktop_MenuAndWindowAnimation) - return; + if (value == _remoteDesktop_MenuAndWindowAnimation) + return; - _remoteDesktop_MenuAndWindowAnimation = value; - OnPropertyChanged(); - } + _remoteDesktop_MenuAndWindowAnimation = value; + OnPropertyChanged(); } + } - private bool _remoteDesktop_VisualStyles; - public bool RemoteDesktop_VisualStyles + private bool _remoteDesktop_VisualStyles; + public bool RemoteDesktop_VisualStyles + { + get => _remoteDesktop_VisualStyles; + set { - get => _remoteDesktop_VisualStyles; - set - { - if (value == _remoteDesktop_VisualStyles) - return; + if (value == _remoteDesktop_VisualStyles) + return; - _remoteDesktop_VisualStyles = value; - OnPropertyChanged(); - } + _remoteDesktop_VisualStyles = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region PowerShell - private bool _powerShell_Enabled; - public bool PowerShell_Enabled + #region PowerShell + private bool _powerShell_Enabled; + public bool PowerShell_Enabled + { + get => _powerShell_Enabled; + set { - get => _powerShell_Enabled; - set - { - if (value == _powerShell_Enabled) - return; + if (value == _powerShell_Enabled) + return; - _powerShell_Enabled = value; + _powerShell_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _powerShell_EnableRemoteConsole; - public bool PowerShell_EnableRemoteConsole + private bool _powerShell_EnableRemoteConsole; + public bool PowerShell_EnableRemoteConsole + { + get => _powerShell_EnableRemoteConsole; + set { - get => _powerShell_EnableRemoteConsole; - set - { - if (value == _powerShell_EnableRemoteConsole) - return; + if (value == _powerShell_EnableRemoteConsole) + return; - _powerShell_EnableRemoteConsole = value; - OnPropertyChanged(); - } + _powerShell_EnableRemoteConsole = value; + OnPropertyChanged(); } + } - private bool _powerShell_InheritHost; - public bool PowerShell_InheritHost + private bool _powerShell_InheritHost; + public bool PowerShell_InheritHost + { + get => _powerShell_InheritHost; + set { - get => _powerShell_InheritHost; - set - { - if (value == _powerShell_InheritHost) - return; + if (value == _powerShell_InheritHost) + return; - _powerShell_InheritHost = value; - OnPropertyChanged(); - } + _powerShell_InheritHost = value; + OnPropertyChanged(); } + } - private string _powerShell_Host; - public string PowerShell_Host + private string _powerShell_Host; + public string PowerShell_Host + { + get => _powerShell_Host; + set { - get => _powerShell_Host; - set - { - if (value == _powerShell_Host) - return; + if (value == _powerShell_Host) + return; - _powerShell_Host = value; - OnPropertyChanged(); - } + _powerShell_Host = value; + OnPropertyChanged(); } + } - private bool _powerShell_OverrideCommand; - public bool PowerShell_OverrideCommand + private bool _powerShell_OverrideCommand; + public bool PowerShell_OverrideCommand + { + get => _powerShell_OverrideCommand; + set { - get => _powerShell_OverrideCommand; - set - { - if (value == _powerShell_OverrideCommand) - return; + if (value == _powerShell_OverrideCommand) + return; - _powerShell_OverrideCommand = value; - OnPropertyChanged(); - } + _powerShell_OverrideCommand = value; + OnPropertyChanged(); } + } - private string _powerShell_Command; - public string PowerShell_Command + private string _powerShell_Command; + public string PowerShell_Command + { + get => _powerShell_Command; + set { - get => _powerShell_Command; - set - { - if (value == _powerShell_Command) - return; + if (value == _powerShell_Command) + return; - _powerShell_Command = value; - OnPropertyChanged(); - } + _powerShell_Command = value; + OnPropertyChanged(); } + } - private bool _powerShell_OverrideAdditionalCommandLine; - public bool PowerShell_OverrideAdditionalCommandLine + private bool _powerShell_OverrideAdditionalCommandLine; + public bool PowerShell_OverrideAdditionalCommandLine + { + get => _powerShell_OverrideAdditionalCommandLine; + set { - get => _powerShell_OverrideAdditionalCommandLine; - set - { - if (value == _powerShell_OverrideAdditionalCommandLine) - return; + if (value == _powerShell_OverrideAdditionalCommandLine) + return; - _powerShell_OverrideAdditionalCommandLine = value; - OnPropertyChanged(); - } + _powerShell_OverrideAdditionalCommandLine = value; + OnPropertyChanged(); } + } - private string _powerShell_AdditionalCommandLine; - public string PowerShell_AdditionalCommandLine + private string _powerShell_AdditionalCommandLine; + public string PowerShell_AdditionalCommandLine + { + get => _powerShell_AdditionalCommandLine; + set { - get => _powerShell_AdditionalCommandLine; - set - { - if (value == _powerShell_AdditionalCommandLine) - return; + if (value == _powerShell_AdditionalCommandLine) + return; - _powerShell_AdditionalCommandLine = value; - OnPropertyChanged(); - } + _powerShell_AdditionalCommandLine = value; + OnPropertyChanged(); } + } - private List _powerShell_ExecutionPolicies = new List(); - public List PowerShell_ExecutionPolicies + private List _powerShell_ExecutionPolicies = new List(); + public List PowerShell_ExecutionPolicies + { + get => _powerShell_ExecutionPolicies; + set { - get => _powerShell_ExecutionPolicies; - set - { - if (value == _powerShell_ExecutionPolicies) - return; + if (value == _powerShell_ExecutionPolicies) + return; - _powerShell_ExecutionPolicies = value; - OnPropertyChanged(); - } + _powerShell_ExecutionPolicies = value; + OnPropertyChanged(); } + } - private bool _powerShell_OverrideExecutionPolicy; - public bool PowerShell_OverrideExecutionPolicy + private bool _powerShell_OverrideExecutionPolicy; + public bool PowerShell_OverrideExecutionPolicy + { + get => _powerShell_OverrideExecutionPolicy; + set { - get => _powerShell_OverrideExecutionPolicy; - set - { - if (value == _powerShell_OverrideExecutionPolicy) - return; + if (value == _powerShell_OverrideExecutionPolicy) + return; - _powerShell_OverrideExecutionPolicy = value; - OnPropertyChanged(); - } + _powerShell_OverrideExecutionPolicy = value; + OnPropertyChanged(); } + } - private PowerShell.ExecutionPolicy _powerShell_ExecutionPolicy; - public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy + private PowerShell.ExecutionPolicy _powerShell_ExecutionPolicy; + public PowerShell.ExecutionPolicy PowerShell_ExecutionPolicy + { + get => _powerShell_ExecutionPolicy; + set { - get => _powerShell_ExecutionPolicy; - set - { - if (value == _powerShell_ExecutionPolicy) - return; + if (value == _powerShell_ExecutionPolicy) + return; - _powerShell_ExecutionPolicy = value; - OnPropertyChanged(); - } + _powerShell_ExecutionPolicy = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region PuTTY - private bool _puTTY_Enabled; - public bool PuTTY_Enabled + #region PuTTY + private bool _puTTY_Enabled; + public bool PuTTY_Enabled + { + get => _puTTY_Enabled; + set { - get => _puTTY_Enabled; - set - { - if (value == _puTTY_Enabled) - return; + if (value == _puTTY_Enabled) + return; - _puTTY_Enabled = value; + _puTTY_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _puTTY_InheritHost; - public bool PuTTY_InheritHost + private bool _puTTY_InheritHost; + public bool PuTTY_InheritHost + { + get => _puTTY_InheritHost; + set { - get => _puTTY_InheritHost; - set - { - if (value == _puTTY_InheritHost) - return; + if (value == _puTTY_InheritHost) + return; - _puTTY_InheritHost = value; - OnPropertyChanged(); - } + _puTTY_InheritHost = value; + OnPropertyChanged(); } + } - private bool _puTTY_UseSSH; // Default is SSH - public bool PuTTY_UseSSH + private bool _puTTY_UseSSH; // Default is SSH + public bool PuTTY_UseSSH + { + get => _puTTY_UseSSH; + set { - get => _puTTY_UseSSH; - set - { - if (value == _puTTY_UseSSH) - return; + if (value == _puTTY_UseSSH) + return; - if (value) - { - if (PuTTY_ConnectionMode == ConnectionMode.Serial) - PuTTY_HostOrSerialLine = Host; - - PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_SSHPort; - PuTTY_ConnectionMode = ConnectionMode.SSH; - } + if (value) + { + if (PuTTY_ConnectionMode == ConnectionMode.Serial) + PuTTY_HostOrSerialLine = Host; - _puTTY_UseSSH = value; - OnPropertyChanged(); + PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_SSHPort; + PuTTY_ConnectionMode = ConnectionMode.SSH; } + + _puTTY_UseSSH = value; + OnPropertyChanged(); } + } - private bool _puTTY_UseTelnet; - public bool PuTTY_UseTelnet + private bool _puTTY_UseTelnet; + public bool PuTTY_UseTelnet + { + get => _puTTY_UseTelnet; + set { - get => _puTTY_UseTelnet; - set - { - if (value == _puTTY_UseTelnet) - return; + if (value == _puTTY_UseTelnet) + return; - if (value) - { - if (PuTTY_ConnectionMode == ConnectionMode.Serial) - PuTTY_HostOrSerialLine = Host; - - PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_TelnetPort; - PuTTY_ConnectionMode = ConnectionMode.Telnet; - } + if (value) + { + if (PuTTY_ConnectionMode == ConnectionMode.Serial) + PuTTY_HostOrSerialLine = Host; - _puTTY_UseTelnet = value; - OnPropertyChanged(); + PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_TelnetPort; + PuTTY_ConnectionMode = ConnectionMode.Telnet; } + + _puTTY_UseTelnet = value; + OnPropertyChanged(); } + } - private bool _puTTY_UseSerial; - public bool PuTTY_UseSerial + private bool _puTTY_UseSerial; + public bool PuTTY_UseSerial + { + get => _puTTY_UseSerial; + set { - get => _puTTY_UseSerial; - set - { - if (value == _puTTY_UseSerial) - return; + if (value == _puTTY_UseSerial) + return; - if (value) - { - if (PuTTY_ConnectionMode != ConnectionMode.Serial) - PuTTY_HostOrSerialLine = SettingsManager.Current.PuTTY_SerialLine; - - PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_BaudRate; - PuTTY_ConnectionMode = ConnectionMode.Serial; - } + if (value) + { + if (PuTTY_ConnectionMode != ConnectionMode.Serial) + PuTTY_HostOrSerialLine = SettingsManager.Current.PuTTY_SerialLine; - _puTTY_UseSerial = value; - OnPropertyChanged(); + PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_BaudRate; + PuTTY_ConnectionMode = ConnectionMode.Serial; } + + _puTTY_UseSerial = value; + OnPropertyChanged(); } + } - private bool _puTTY_UseRlogin; - public bool PuTTY_UseRlogin + private bool _puTTY_UseRlogin; + public bool PuTTY_UseRlogin + { + get => _puTTY_UseRlogin; + set { - get => _puTTY_UseRlogin; - set - { - if (value == _puTTY_UseRlogin) - return; - - if (value) - { - if (PuTTY_ConnectionMode == ConnectionMode.Serial) - PuTTY_HostOrSerialLine = Host; + if (value == _puTTY_UseRlogin) + return; - PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_RloginPort; - PuTTY_ConnectionMode = ConnectionMode.Rlogin; - } + if (value) + { + if (PuTTY_ConnectionMode == ConnectionMode.Serial) + PuTTY_HostOrSerialLine = Host; - _puTTY_UseRlogin = value; - OnPropertyChanged(); + PuTTY_PortOrBaud = SettingsManager.Current.PuTTY_RloginPort; + PuTTY_ConnectionMode = ConnectionMode.Rlogin; } + + _puTTY_UseRlogin = value; + OnPropertyChanged(); } + } - private bool _puTTY_UseRAW; - public bool PuTTY_UseRAW + private bool _puTTY_UseRAW; + public bool PuTTY_UseRAW + { + get => _puTTY_UseRAW; + set { - get => _puTTY_UseRAW; - set - { - if (value == _puTTY_UseRAW) - return; - - if (value) - { - if (PuTTY_ConnectionMode == ConnectionMode.Serial) - PuTTY_HostOrSerialLine = Host; + if (value == _puTTY_UseRAW) + return; - PuTTY_PortOrBaud = 0; - PuTTY_ConnectionMode = ConnectionMode.RAW; - } + if (value) + { + if (PuTTY_ConnectionMode == ConnectionMode.Serial) + PuTTY_HostOrSerialLine = Host; - _puTTY_UseRAW = value; - OnPropertyChanged(); + PuTTY_PortOrBaud = 0; + PuTTY_ConnectionMode = ConnectionMode.RAW; } + + _puTTY_UseRAW = value; + OnPropertyChanged(); } + } - private string _puTTY_HostOrSerialLine; - public string PuTTY_HostOrSerialLine + private string _puTTY_HostOrSerialLine; + public string PuTTY_HostOrSerialLine + { + get => _puTTY_HostOrSerialLine; + set { - get => _puTTY_HostOrSerialLine; - set - { - if (value == _puTTY_HostOrSerialLine) - return; + if (value == _puTTY_HostOrSerialLine) + return; - _puTTY_HostOrSerialLine = value; - OnPropertyChanged(); - } + _puTTY_HostOrSerialLine = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverridePortOrBaud; - public bool PuTTY_OverridePortOrBaud + private bool _puTTY_OverridePortOrBaud; + public bool PuTTY_OverridePortOrBaud + { + get => _puTTY_OverridePortOrBaud; + set { - get => _puTTY_OverridePortOrBaud; - set - { - if (value == _puTTY_OverridePortOrBaud) - return; + if (value == _puTTY_OverridePortOrBaud) + return; - _puTTY_OverridePortOrBaud = value; - OnPropertyChanged(); - } + _puTTY_OverridePortOrBaud = value; + OnPropertyChanged(); } + } - private int _puTTY_PortOrBaud; - public int PuTTY_PortOrBaud + private int _puTTY_PortOrBaud; + public int PuTTY_PortOrBaud + { + get => _puTTY_PortOrBaud; + set { - get => _puTTY_PortOrBaud; - set - { - if (value == _puTTY_PortOrBaud) - return; + if (value == _puTTY_PortOrBaud) + return; - _puTTY_PortOrBaud = value; - OnPropertyChanged(); - } + _puTTY_PortOrBaud = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideUsername; - public bool PuTTY_OverrideUsername + private bool _puTTY_OverrideUsername; + public bool PuTTY_OverrideUsername + { + get => _puTTY_OverrideUsername; + set { - get => _puTTY_OverrideUsername; - set - { - if (value == _puTTY_OverrideUsername) - return; + if (value == _puTTY_OverrideUsername) + return; - _puTTY_OverrideUsername = value; - OnPropertyChanged(); - } + _puTTY_OverrideUsername = value; + OnPropertyChanged(); } + } - private string _puTTY__Username; - public string PuTTY_Username + private string _puTTY__Username; + public string PuTTY_Username + { + get => _puTTY__Username; + set { - get => _puTTY__Username; - set - { - if (value == _puTTY__Username) - return; + if (value == _puTTY__Username) + return; - _puTTY__Username = value; - OnPropertyChanged(); - } + _puTTY__Username = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverridePrivateKeyFile; - public bool PuTTY_OverridePrivateKeyFile + private bool _puTTY_OverridePrivateKeyFile; + public bool PuTTY_OverridePrivateKeyFile + { + get => _puTTY_OverridePrivateKeyFile; + set { - get => _puTTY_OverridePrivateKeyFile; - set - { - if (value == _puTTY_OverridePrivateKeyFile) - return; + if (value == _puTTY_OverridePrivateKeyFile) + return; - _puTTY_OverridePrivateKeyFile = value; - OnPropertyChanged(); - } + _puTTY_OverridePrivateKeyFile = value; + OnPropertyChanged(); } + } - private string _puTTY__PrivateKeyFile; - public string PuTTY_PrivateKeyFile + private string _puTTY__PrivateKeyFile; + public string PuTTY_PrivateKeyFile + { + get => _puTTY__PrivateKeyFile; + set { - get => _puTTY__PrivateKeyFile; - set - { - if (value == _puTTY__PrivateKeyFile) - return; + if (value == _puTTY__PrivateKeyFile) + return; - _puTTY__PrivateKeyFile = value; - OnPropertyChanged(); - } + _puTTY__PrivateKeyFile = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideProfile; - public bool PuTTY_OverrideProfile + private bool _puTTY_OverrideProfile; + public bool PuTTY_OverrideProfile + { + get => _puTTY_OverrideProfile; + set { - get => _puTTY_OverrideProfile; - set - { - if (value == _puTTY_OverrideProfile) - return; + if (value == _puTTY_OverrideProfile) + return; - _puTTY_OverrideProfile = value; - OnPropertyChanged(); - } + _puTTY_OverrideProfile = value; + OnPropertyChanged(); } + } - private string _puTTY_Profile; - public string PuTTY_Profile + private string _puTTY_Profile; + public string PuTTY_Profile + { + get => _puTTY_Profile; + set { - get => _puTTY_Profile; - set - { - if (value == _puTTY_Profile) - return; + if (value == _puTTY_Profile) + return; - _puTTY_Profile = value; - OnPropertyChanged(); - } + _puTTY_Profile = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideHostkey; - public bool PuTTY_OverrideHostkey + private bool _puTTY_OverrideHostkey; + public bool PuTTY_OverrideHostkey + { + get => _puTTY_OverrideHostkey; + set { - get => _puTTY_OverrideHostkey; - set - { - if (value == _puTTY_OverrideHostkey) - return; + if (value == _puTTY_OverrideHostkey) + return; - _puTTY_OverrideHostkey = value; - OnPropertyChanged(); - } + _puTTY_OverrideHostkey = value; + OnPropertyChanged(); } + } - private string _puTTY_Hostkey; - public string PuTTY_Hostkey + private string _puTTY_Hostkey; + public string PuTTY_Hostkey + { + get => _puTTY_Hostkey; + set { - get => _puTTY_Hostkey; - set - { - if (value == _puTTY_Hostkey) - return; + if (value == _puTTY_Hostkey) + return; - _puTTY_Hostkey = value; - OnPropertyChanged(); - } + _puTTY_Hostkey = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideEnableLog; - public bool PuTTY_OverrideEnableLog + private bool _puTTY_OverrideEnableLog; + public bool PuTTY_OverrideEnableLog + { + get => _puTTY_OverrideEnableLog; + set { - get => _puTTY_OverrideEnableLog; - set - { - if (value == _puTTY_OverrideEnableLog) - return; + if (value == _puTTY_OverrideEnableLog) + return; - _puTTY_OverrideEnableLog = value; - OnPropertyChanged(); - } + _puTTY_OverrideEnableLog = value; + OnPropertyChanged(); } + } - private bool _puTTY_EnableLog; - public bool PuTTY_EnableLog + private bool _puTTY_EnableLog; + public bool PuTTY_EnableLog + { + get => _puTTY_EnableLog; + set { - get => _puTTY_EnableLog; - set - { - if (value == _puTTY_EnableLog) - return; + if (value == _puTTY_EnableLog) + return; - _puTTY_EnableLog = value; - OnPropertyChanged(); - } + _puTTY_EnableLog = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideLogMode; - public bool PuTTY_OverrideLogMode + private bool _puTTY_OverrideLogMode; + public bool PuTTY_OverrideLogMode + { + get => _puTTY_OverrideLogMode; + set { - get => _puTTY_OverrideLogMode; - set - { - if (value == _puTTY_OverrideLogMode) - return; + if (value == _puTTY_OverrideLogMode) + return; - _puTTY_OverrideLogMode = value; - OnPropertyChanged(); - } + _puTTY_OverrideLogMode = value; + OnPropertyChanged(); } + } - public IEnumerable PuTTY_LogModes => Enum.GetValues(typeof(LogMode)).Cast(); + public IEnumerable PuTTY_LogModes => Enum.GetValues(typeof(LogMode)).Cast(); - private LogMode _puTTY_LogMode; - public LogMode PuTTY_LogMode + private LogMode _puTTY_LogMode; + public LogMode PuTTY_LogMode + { + get => _puTTY_LogMode; + set { - get => _puTTY_LogMode; - set - { - if (Equals(value, _puTTY_LogMode)) - return; + if (Equals(value, _puTTY_LogMode)) + return; - _puTTY_LogMode = value; - OnPropertyChanged(); - } + _puTTY_LogMode = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideLogPath; - public bool PuTTY_OverrideLogPath + private bool _puTTY_OverrideLogPath; + public bool PuTTY_OverrideLogPath + { + get => _puTTY_OverrideLogPath; + set { - get => _puTTY_OverrideLogPath; - set - { - if (value == _puTTY_OverrideLogPath) - return; + if (value == _puTTY_OverrideLogPath) + return; - _puTTY_OverrideLogPath = value; - OnPropertyChanged(); - } + _puTTY_OverrideLogPath = value; + OnPropertyChanged(); } + } - private string _puTTY_LogPath; - public string PuTTY_LogPath + private string _puTTY_LogPath; + public string PuTTY_LogPath + { + get => _puTTY_LogPath; + set { - get => _puTTY_LogPath; - set - { - if (value == _puTTY_LogPath) - return; + if (value == _puTTY_LogPath) + return; - _puTTY_LogPath = value; - OnPropertyChanged(); - } + _puTTY_LogPath = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideLogFileName; - public bool PuTTY_OverrideLogFileName + private bool _puTTY_OverrideLogFileName; + public bool PuTTY_OverrideLogFileName + { + get => _puTTY_OverrideLogFileName; + set { - get => _puTTY_OverrideLogFileName; - set - { - if (value == _puTTY_OverrideLogFileName) - return; + if (value == _puTTY_OverrideLogFileName) + return; - _puTTY_OverrideLogFileName = value; - OnPropertyChanged(); - } + _puTTY_OverrideLogFileName = value; + OnPropertyChanged(); } + } - private string _puTTY_LogFileName; - public string PuTTY_LogFileName + private string _puTTY_LogFileName; + public string PuTTY_LogFileName + { + get => _puTTY_LogFileName; + set { - get => _puTTY_LogFileName; - set - { - if (value == _puTTY_LogFileName) - return; + if (value == _puTTY_LogFileName) + return; - _puTTY_LogFileName = value; - OnPropertyChanged(); - } + _puTTY_LogFileName = value; + OnPropertyChanged(); } + } - private bool _puTTY_OverrideAdditionalCommandLine; - public bool PuTTY_OverrideAdditionalCommandLine + private bool _puTTY_OverrideAdditionalCommandLine; + public bool PuTTY_OverrideAdditionalCommandLine + { + get => _puTTY_OverrideAdditionalCommandLine; + set { - get => _puTTY_OverrideAdditionalCommandLine; - set - { - if (value == _puTTY_OverrideAdditionalCommandLine) - return; + if (value == _puTTY_OverrideAdditionalCommandLine) + return; - _puTTY_OverrideAdditionalCommandLine = value; - OnPropertyChanged(); - } + _puTTY_OverrideAdditionalCommandLine = value; + OnPropertyChanged(); } + } - private string _puTTY_AdditionalCommandLine; - public string PuTTY_AdditionalCommandLine + private string _puTTY_AdditionalCommandLine; + public string PuTTY_AdditionalCommandLine + { + get => _puTTY_AdditionalCommandLine; + set { - get => _puTTY_AdditionalCommandLine; - set - { - if (value == _puTTY_AdditionalCommandLine) - return; + if (value == _puTTY_AdditionalCommandLine) + return; - _puTTY_AdditionalCommandLine = value; - OnPropertyChanged(); - } + _puTTY_AdditionalCommandLine = value; + OnPropertyChanged(); } + } - private ConnectionMode _puTTY_ConnectionMode; - public ConnectionMode PuTTY_ConnectionMode + private ConnectionMode _puTTY_ConnectionMode; + public ConnectionMode PuTTY_ConnectionMode + { + get => _puTTY_ConnectionMode; + set { - get => _puTTY_ConnectionMode; - set - { - if (value == _puTTY_ConnectionMode) - return; + if (value == _puTTY_ConnectionMode) + return; - _puTTY_ConnectionMode = value; - } + _puTTY_ConnectionMode = value; } - #endregion + } + #endregion - #region AWS Session Manager - private bool _awsSessionManager_Enabled; - public bool AWSSessionManager_Enabled + #region AWS Session Manager + private bool _awsSessionManager_Enabled; + public bool AWSSessionManager_Enabled + { + get => _awsSessionManager_Enabled; + set { - get => _awsSessionManager_Enabled; - set - { - if (value == _awsSessionManager_Enabled) - return; + if (value == _awsSessionManager_Enabled) + return; - _awsSessionManager_Enabled = value; - OnPropertyChanged(); - } + _awsSessionManager_Enabled = value; + OnPropertyChanged(); } + } - private string _awsSessionManager_InstanceID; - public string AWSSessionManager_InstanceID + private string _awsSessionManager_InstanceID; + public string AWSSessionManager_InstanceID + { + get => _awsSessionManager_InstanceID; + set { - get => _awsSessionManager_InstanceID; - set - { - if (value == _awsSessionManager_InstanceID) - return; + if (value == _awsSessionManager_InstanceID) + return; - _awsSessionManager_InstanceID = value; - OnPropertyChanged(); - } + _awsSessionManager_InstanceID = value; + OnPropertyChanged(); } + } - private bool _awsSessionManager_OverrideProfile; - public bool AWSSessionManager_OverrideProfile + private bool _awsSessionManager_OverrideProfile; + public bool AWSSessionManager_OverrideProfile + { + get => _awsSessionManager_OverrideProfile; + set { - get => _awsSessionManager_OverrideProfile; - set - { - if (value == _awsSessionManager_OverrideProfile) - return; + if (value == _awsSessionManager_OverrideProfile) + return; - _awsSessionManager_OverrideProfile = value; - OnPropertyChanged(); - } + _awsSessionManager_OverrideProfile = value; + OnPropertyChanged(); } + } - private string _awsSessionManager_Profile; - public string AWSSessionManager_Profile + private string _awsSessionManager_Profile; + public string AWSSessionManager_Profile + { + get => _awsSessionManager_Profile; + set { - get => _awsSessionManager_Profile; - set - { - if (value == _awsSessionManager_Profile) - return; + if (value == _awsSessionManager_Profile) + return; - _awsSessionManager_Profile = value; - OnPropertyChanged(); - } + _awsSessionManager_Profile = value; + OnPropertyChanged(); } + } - private bool _awsSessionManager_OverrideRegion; - public bool AWSSessionManager_OverrideRegion + private bool _awsSessionManager_OverrideRegion; + public bool AWSSessionManager_OverrideRegion + { + get => _awsSessionManager_OverrideRegion; + set { - get => _awsSessionManager_OverrideRegion; - set - { - if (value == _awsSessionManager_OverrideRegion) - return; + if (value == _awsSessionManager_OverrideRegion) + return; - _awsSessionManager_OverrideRegion = value; - OnPropertyChanged(); - } + _awsSessionManager_OverrideRegion = value; + OnPropertyChanged(); } + } - private string _awsSessionManager_Region; - public string AWSSessionManager_Region + private string _awsSessionManager_Region; + public string AWSSessionManager_Region + { + get => _awsSessionManager_Region; + set { - get => _awsSessionManager_Region; - set - { - if (value == _awsSessionManager_Region) - return; + if (value == _awsSessionManager_Region) + return; - _awsSessionManager_Region = value; - OnPropertyChanged(); - } + _awsSessionManager_Region = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region TigerVNC - private bool _tigerVNC_Enabled; - public bool TigerVNC_Enabled + #region TigerVNC + private bool _tigerVNC_Enabled; + public bool TigerVNC_Enabled + { + get => _tigerVNC_Enabled; + set { - get => _tigerVNC_Enabled; - set - { - if (value == _tigerVNC_Enabled) - return; + if (value == _tigerVNC_Enabled) + return; - _tigerVNC_Enabled = value; - OnPropertyChanged(); - } + _tigerVNC_Enabled = value; + OnPropertyChanged(); } + } - private bool _tigerVNC_InheritHost; - public bool TigerVNC_InheritHost + private bool _tigerVNC_InheritHost; + public bool TigerVNC_InheritHost + { + get => _tigerVNC_InheritHost; + set { - get => _tigerVNC_InheritHost; - set - { - if (value == _tigerVNC_InheritHost) - return; + if (value == _tigerVNC_InheritHost) + return; - _tigerVNC_InheritHost = value; - OnPropertyChanged(); - } + _tigerVNC_InheritHost = value; + OnPropertyChanged(); } + } - private string _tigerVNC_Host; - public string TigerVNC_Host + private string _tigerVNC_Host; + public string TigerVNC_Host + { + get => _tigerVNC_Host; + set { - get => _tigerVNC_Host; - set - { - if (value == _tigerVNC_Host) - return; + if (value == _tigerVNC_Host) + return; - _tigerVNC_Host = value; - OnPropertyChanged(); - } + _tigerVNC_Host = value; + OnPropertyChanged(); } + } - private bool _tigerVNC_OverridePort; - public bool TigerVNC_OverridePort + private bool _tigerVNC_OverridePort; + public bool TigerVNC_OverridePort + { + get => _tigerVNC_OverridePort; + set { - get => _tigerVNC_OverridePort; - set - { - if (value == _tigerVNC_OverridePort) - return; + if (value == _tigerVNC_OverridePort) + return; - _tigerVNC_OverridePort = value; - OnPropertyChanged(); - } + _tigerVNC_OverridePort = value; + OnPropertyChanged(); } + } - private int _tigerVNC_Port; - public int TigerVNC_Port + private int _tigerVNC_Port; + public int TigerVNC_Port + { + get => _tigerVNC_Port; + set { - get => _tigerVNC_Port; - set - { - if (value == _tigerVNC_Port) - return; + if (value == _tigerVNC_Port) + return; - _tigerVNC_Port = value; - OnPropertyChanged(); - } + _tigerVNC_Port = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Web Console - private bool _webConsole_Enabled; - public bool WebConsole_Enabled + #region Web Console + private bool _webConsole_Enabled; + public bool WebConsole_Enabled + { + get => _webConsole_Enabled; + set { - get => _webConsole_Enabled; - set - { - if (value == _webConsole_Enabled) - return; + if (value == _webConsole_Enabled) + return; - _webConsole_Enabled = value; - OnPropertyChanged(); - } + _webConsole_Enabled = value; + OnPropertyChanged(); } + } - private string _webConsole_Url; - public string WebConsole_Url + private string _webConsole_Url; + public string WebConsole_Url + { + get => _webConsole_Url; + set { - get => _webConsole_Url; - set - { - if (value == _webConsole_Url) - return; + if (value == _webConsole_Url) + return; - _webConsole_Url = value; - OnPropertyChanged(); - } + _webConsole_Url = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Wake on LAN - private bool _wakeOnLAN_Enabled; - public bool WakeOnLAN_Enabled + #region Wake on LAN + private bool _wakeOnLAN_Enabled; + public bool WakeOnLAN_Enabled + { + get => _wakeOnLAN_Enabled; + set { - get => _wakeOnLAN_Enabled; - set - { - if (value == _wakeOnLAN_Enabled) - return; + if (value == _wakeOnLAN_Enabled) + return; - _wakeOnLAN_Enabled = value; + _wakeOnLAN_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private string _wakeOnLAN_MACAddress; - public string WakeOnLAN_MACAddress + private string _wakeOnLAN_MACAddress; + public string WakeOnLAN_MACAddress + { + get => _wakeOnLAN_MACAddress; + set { - get => _wakeOnLAN_MACAddress; - set - { - if (value == _wakeOnLAN_MACAddress) - return; + if (value == _wakeOnLAN_MACAddress) + return; - _wakeOnLAN_MACAddress = value; - OnPropertyChanged(); - } + _wakeOnLAN_MACAddress = value; + OnPropertyChanged(); } + } - private string _wakeOnLAN_Broadcast; - public string WakeOnLAN_Broadcast + private string _wakeOnLAN_Broadcast; + public string WakeOnLAN_Broadcast + { + get => _wakeOnLAN_Broadcast; + set { - get => _wakeOnLAN_Broadcast; - set - { - if (value == _wakeOnLAN_Broadcast) - return; + if (value == _wakeOnLAN_Broadcast) + return; - _wakeOnLAN_Broadcast = value; - OnPropertyChanged(); - } + _wakeOnLAN_Broadcast = value; + OnPropertyChanged(); } + } - private bool _wakeOnLAN_OverridePort; - public bool WakeOnLAN_OverridePort + private bool _wakeOnLAN_OverridePort; + public bool WakeOnLAN_OverridePort + { + get => _wakeOnLAN_OverridePort; + set { - get => _wakeOnLAN_OverridePort; - set - { - if (value == _wakeOnLAN_OverridePort) - return; + if (value == _wakeOnLAN_OverridePort) + return; - _wakeOnLAN_OverridePort = value; - OnPropertyChanged(); - } + _wakeOnLAN_OverridePort = value; + OnPropertyChanged(); } + } - private int _wakeOnLAN_Port; - public int WakeOnLAN_Port + private int _wakeOnLAN_Port; + public int WakeOnLAN_Port + { + get => _wakeOnLAN_Port; + set { - get => _wakeOnLAN_Port; - set - { - if (value == _wakeOnLAN_Port) - return; + if (value == _wakeOnLAN_Port) + return; - _wakeOnLAN_Port = value; - OnPropertyChanged(); - } + _wakeOnLAN_Port = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Whois - private bool _whois_Enabled; - public bool Whois_Enabled + #region Whois + private bool _whois_Enabled; + public bool Whois_Enabled + { + get => _whois_Enabled; + set { - get => _whois_Enabled; - set - { - if (value == _whois_Enabled) - return; + if (value == _whois_Enabled) + return; - _whois_Enabled = value; + _whois_Enabled = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _whois_InheritHost; - public bool Whois_InheritHost + private bool _whois_InheritHost; + public bool Whois_InheritHost + { + get => _whois_InheritHost; + set { - get => _whois_InheritHost; - set - { - if (value == _whois_InheritHost) - return; + if (value == _whois_InheritHost) + return; - _whois_InheritHost = value; - OnPropertyChanged(); - } + _whois_InheritHost = value; + OnPropertyChanged(); } + } - private string _whois_Domain; - public string Whois_Domain + private string _whois_Domain; + public string Whois_Domain + { + get => _whois_Domain; + set { - get => _whois_Domain; - set - { - if (value == _whois_Domain) - return; - - _whois_Domain = value; - OnPropertyChanged(); - } - } - #endregion - #endregion - public ProfileViewModel(Action saveCommand, Action cancelHandler, IReadOnlyCollection groups, string group = null, ProfileEditMode editMode = ProfileEditMode.Add, ProfileInfo profile = null, ApplicationName applicationName = ApplicationName.None) - { - // Load the view - ProfileViews = new CollectionViewSource { Source = ProfileViewManager.List }.View; - ProfileViews.SortDescriptions.Add(new SortDescription(nameof(ProfileViewInfo.Name), ListSortDirection.Ascending)); - - SaveCommand = new RelayCommand(p => saveCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); - - var profileInfo = profile ?? new ProfileInfo(); - - Name = profileInfo.Name; - - if (editMode == ProfileEditMode.Copy) - Name += " - " + Localization.Resources.Strings.CopyNoun; - - Host = profileInfo.Host; - - // Try to get group (name) as parameter, then from profile, then the first in the list of groups, then the default group - Group = group ?? (string.IsNullOrEmpty(profileInfo.Group) ? (groups.Count > 0 ? groups.OrderBy(x => x).First() : Localization.Resources.Strings.Default) : profileInfo.Group); - - Tags = profileInfo.Tags; - - Groups = CollectionViewSource.GetDefaultView(groups); - Groups.SortDescriptions.Add(new SortDescription()); - - // Network Interface - NetworkInterface_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.NetworkInterface : profileInfo.NetworkInterface_Enabled; - NetworkInterface_EnableDynamicIPAddress = !profileInfo.NetworkInterface_EnableStaticIPAddress; - NetworkInterface_EnableStaticIPAddress = profileInfo.NetworkInterface_EnableStaticIPAddress; - NetworkInterface_IPAddress = profileInfo.NetworkInterface_IPAddress; - NetworkInterface_Gateway = profileInfo.NetworkInterface_Gateway; - NetworkInterface_SubnetmaskOrCidr = profileInfo.NetworkInterface_SubnetmaskOrCidr; - NetworkInterface_EnableDynamicDNS = !profileInfo.NetworkInterface_EnableStaticDNS; - NetworkInterface_EnableStaticDNS = profileInfo.NetworkInterface_EnableStaticDNS; - NetworkInterface_PrimaryDNSServer = profileInfo.NetworkInterface_PrimaryDNSServer; - NetworkInterface_SecondaryDNSServer = profileInfo.NetworkInterface_SecondaryDNSServer; - - // IP Scanner - IPScanner_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.IPScanner : profileInfo.IPScanner_Enabled; - IPScanner_InheritHost = profileInfo.IPScanner_InheritHost; - IPScanner_HostOrIPRange = profileInfo.IPScanner_HostOrIPRange; - - // Port Scanner - PortScanner_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PortScanner : profileInfo.PortScanner_Enabled; - PortScanner_InheritHost = profileInfo.PortScanner_InheritHost; - PortScanner_Host = profileInfo.PortScanner_Host; - PortScanner_Ports = profileInfo.PortScanner_Ports; - - // Ping Monitor - PingMonitor_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PingMonitor : profileInfo.PingMonitor_Enabled; - PingMonitor_InheritHost = profileInfo.PingMonitor_InheritHost; - PingMonitor_Host = profileInfo.PingMonitor_Host; - - // Traceroute - Traceroute_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.Traceroute : profileInfo.Traceroute_Enabled; - Traceroute_InheritHost = profileInfo.Traceroute_InheritHost; - Traceroute_Host = profileInfo.Traceroute_Host; - - // DNS Lookup - DNSLookup_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.DNSLookup : profileInfo.DNSLookup_Enabled; - DNSLookup_InheritHost = profileInfo.DNSLookup_InheritHost; - DNSLookup_Host = profileInfo.DNSLookup_Host; - - // Remote Desktop - RemoteDesktop_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.RemoteDesktop : profileInfo.RemoteDesktop_Enabled; - RemoteDesktop_InheritHost = profileInfo.RemoteDesktop_InheritHost; - RemoteDesktop_Host = profileInfo.RemoteDesktop_Host; - RemoteDesktop_UseCredentials = profileInfo.RemoteDesktop_UseCredentials; - RemoteDesktop_Username = profileInfo.RemoteDesktop_Username; - RemoteDesktop_Password = profileInfo.RemoteDesktop_Password; - RemoteDesktop_OverrideDisplay = profileInfo.RemoteDesktop_OverrideDisplay; - RemoteDesktop_AdjustScreenAutomatically = profileInfo.RemoteDesktop_AdjustScreenAutomatically; - RemoteDesktop_UseCurrentViewSize = profileInfo.RemoteDesktop_UseCurrentViewSize; - RemoteDesktop_UseFixedScreenSize = profileInfo.RemoteDesktop_UseFixedScreenSize; - RemoteDesktop_SelectedScreenResolution = RemoteDesktop_ScreenResolutions.FirstOrDefault(x => x == $"{profileInfo.RemoteDesktop_ScreenWidth}x{profileInfo.RemoteDesktop_ScreenHeight}"); - RemoteDesktop_UseCustomScreenSize = profileInfo.RemoteDesktop_UseCustomScreenSize; - RemoteDesktop_CustomScreenWidth = profileInfo.RemoteDesktop_CustomScreenWidth.ToString(); - RemoteDesktop_CustomScreenHeight = profileInfo.RemoteDesktop_CustomScreenHeight.ToString(); - RemoteDesktop_OverrideColorDepth = profileInfo.RemoteDesktop_OverrideColorDepth; - RemoteDesktop_SelectedColorDepth = RemoteDesktop_ColorDepths.FirstOrDefault(x => x == profileInfo.RemoteDesktop_ColorDepth); - RemoteDesktop_OverridePort = profileInfo.RemoteDesktop_OverridePort; - RemoteDesktop_Port = profileInfo.RemoteDesktop_Port; - RemoteDesktop_OverrideCredSspSupport = profileInfo.RemoteDesktop_OverrideCredSspSupport; - RemoteDesktop_EnableCredSspSupport = profileInfo.RemoteDesktop_EnableCredSspSupport; - RemoteDesktop_OverrideAuthenticationLevel = profileInfo.RemoteDesktop_OverrideAuthenticationLevel; - RemoteDesktop_AuthenticationLevel = profileInfo.RemoteDesktop_AuthenticationLevel; - RemoteDesktop_OverrideAudioRedirectionMode = profileInfo.RemoteDesktop_OverrideAudioRedirectionMode; - RemoteDesktop_AudioRedirectionMode = RemoteDesktop_AudioRedirectionModes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_AudioRedirectionMode); - RemoteDesktop_OverrideAudioCaptureRedirectionMode = profileInfo.RemoteDesktop_OverrideAudioCaptureRedirectionMode; - RemoteDesktop_AudioCaptureRedirectionMode = RemoteDesktop_AudioCaptureRedirectionModes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_AudioCaptureRedirectionMode); - RemoteDesktop_OverrideApplyWindowsKeyCombinations = profileInfo.RemoteDesktop_OverrideApplyWindowsKeyCombinations; - RemoteDesktop_KeyboardHookMode = RemoteDesktop_KeyboardHookModes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_KeyboardHookMode); - RemoteDesktop_OverrideRedirectClipboard = profileInfo.RemoteDesktop_OverrideRedirectClipboard; - RemoteDesktop_RedirectClipboard = profileInfo.RemoteDesktop_RedirectClipboard; - RemoteDesktop_OverrideRedirectDevices = profileInfo.RemoteDesktop_OverrideRedirectDevices; - RemoteDesktop_RedirectDevices = profileInfo.RemoteDesktop_RedirectDevices; - RemoteDesktop_OverrideRedirectDrives = profileInfo.RemoteDesktop_OverrideRedirectDrives; - RemoteDesktop_RedirectDrives = profileInfo.RemoteDesktop_RedirectDrives; - RemoteDesktop_OverrideRedirectPorts = profileInfo.RemoteDesktop_OverrideRedirectPorts; - RemoteDesktop_RedirectPorts = profileInfo.RemoteDesktop_RedirectPorts; - RemoteDesktop_OverrideRedirectSmartcards = profileInfo.RemoteDesktop_OverrideRedirectSmartcards; - RemoteDesktop_RedirectSmartCards = profileInfo.RemoteDesktop_RedirectSmartCards; - RemoteDesktop_OverrideRedirectPrinters = profileInfo.RemoteDesktop_OverrideRedirectPrinters; - RemoteDesktop_RedirectPrinters = profileInfo.RemoteDesktop_RedirectPrinters; - RemoteDesktop_OverridePersistentBitmapCaching = profileInfo.RemoteDesktop_OverridePersistentBitmapCaching; - RemoteDesktop_PersistentBitmapCaching = profileInfo.RemoteDesktop_PersistentBitmapCaching; - RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = profileInfo.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; - RemoteDesktop_ReconnectIfTheConnectionIsDropped = profileInfo.RemoteDesktop_ReconnectIfTheConnectionIsDropped; - RemoteDesktop_NetworkConnectionType = RemoteDesktop_NetworkConnectionTypes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_NetworkConnectionType); - RemoteDesktop_DesktopBackground = profileInfo.RemoteDesktop_DesktopBackground; - RemoteDesktop_FontSmoothing = profileInfo.RemoteDesktop_FontSmoothing; - RemoteDesktop_DesktopComposition = profileInfo.RemoteDesktop_DesktopComposition; - RemoteDesktop_ShowWindowContentsWhileDragging = profileInfo.RemoteDesktop_ShowWindowContentsWhileDragging; - RemoteDesktop_MenuAndWindowAnimation = profileInfo.RemoteDesktop_MenuAndWindowAnimation; - RemoteDesktop_VisualStyles = profileInfo.RemoteDesktop_VisualStyles; - - // PowerShell - PowerShell_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PowerShell : profileInfo.PowerShell_Enabled; - PowerShell_EnableRemoteConsole = profileInfo.PowerShell_EnableRemoteConsole; - PowerShell_InheritHost = profileInfo.PowerShell_InheritHost; - PowerShell_Host = profileInfo.PowerShell_Host; - PowerShell_OverrideCommand = profileInfo.PowerShell_OverrideCommand; - PowerShell_Command = profileInfo.PowerShell_Command; - PowerShell_OverrideAdditionalCommandLine = profileInfo.PowerShell_OverrideAdditionalCommandLine; - PowerShell_AdditionalCommandLine = profileInfo.PowerShell_AdditionalCommandLine; - PowerShell_ExecutionPolicies = Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); - PowerShell_OverrideExecutionPolicy = profileInfo.PowerShell_OverrideExecutionPolicy; - PowerShell_ExecutionPolicy = editMode != ProfileEditMode.Add ? profileInfo.PowerShell_ExecutionPolicy : PowerShell_ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); ; - - // PuTTY - PuTTY_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PuTTY : profileInfo.PuTTY_Enabled; - - switch (profileInfo.PuTTY_ConnectionMode) - { - // SSH is default - case ConnectionMode.SSH: - PuTTY_UseSSH = true; - break; - case ConnectionMode.Telnet: - PuTTY_UseTelnet = true; - break; - case ConnectionMode.Serial: - PuTTY_UseSerial = true; - break; - case ConnectionMode.Rlogin: - PuTTY_UseRlogin = true; - break; - case ConnectionMode.RAW: - PuTTY_UseRAW = true; - break; - } - - PuTTY_InheritHost = profileInfo.PuTTY_InheritHost; - PuTTY_HostOrSerialLine = profileInfo.PuTTY_HostOrSerialLine; - PuTTY_OverridePortOrBaud = profileInfo.PuTTY_OverridePortOrBaud; - PuTTY_PortOrBaud = profileInfo.PuTTY_OverridePortOrBaud ? profileInfo.PuTTY_PortOrBaud : Settings.Application.PuTTY.GetPortOrBaudByConnectionMode(PuTTY_ConnectionMode); - PuTTY_OverrideUsername = profileInfo.PuTTY_OverrideUsername; - PuTTY_Username = profileInfo.PuTTY_Username; - PuTTY_OverridePrivateKeyFile = profileInfo.PuTTY_OverridePrivateKeyFile; - PuTTY_PrivateKeyFile = profileInfo.PuTTY_PrivateKeyFile; - PuTTY_OverrideProfile = profileInfo.PuTTY_OverrideProfile; - PuTTY_Profile = profileInfo.PuTTY_Profile; - PuTTY_OverrideHostkey = profileInfo.PuTTY_OverrideHostkey; - PuTTY_Hostkey = profileInfo.PuTTY_Hostkey; - PuTTY_OverrideEnableLog = profileInfo.PuTTY_OverrideEnableLog; - PuTTY_EnableLog = profileInfo.PuTTY_EnableLog; - PuTTY_OverrideLogMode = profileInfo.PuTTY_OverrideLogMode; - PuTTY_LogMode = PuTTY_LogModes.FirstOrDefault(x => x == profileInfo.PuTTY_LogMode); - PuTTY_OverrideLogPath = profileInfo.PuTTY_OverrideLogPath; - PuTTY_LogPath = profileInfo.PuTTY_LogPath; - PuTTY_OverrideLogFileName = profileInfo.PuTTY_OverrideLogFileName; - PuTTY_LogFileName = profileInfo.PuTTY_LogFileName; - PuTTY_OverrideAdditionalCommandLine = profileInfo.PuTTY_OverrideAdditionalCommandLine; - PuTTY_AdditionalCommandLine = profileInfo.PuTTY_AdditionalCommandLine; - - // AWS Session Manager - AWSSessionManager_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.AWSSessionManager : profileInfo.AWSSessionManager_Enabled; - AWSSessionManager_InstanceID = profileInfo.AWSSessionManager_InstanceID; - AWSSessionManager_OverrideProfile = profileInfo.AWSSessionManager_OverrideProfile; - AWSSessionManager_Profile = profileInfo.AWSSessionManager_Profile; - AWSSessionManager_OverrideRegion = profileInfo.AWSSessionManager_OverrideRegion; - AWSSessionManager_Region = profileInfo.AWSSessionManager_Region; - - // TigerVNC - TigerVNC_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.TigerVNC : profileInfo.TigerVNC_Enabled; - TigerVNC_InheritHost = profileInfo.TigerVNC_InheritHost; - TigerVNC_Host = profileInfo.TigerVNC_Host; - TigerVNC_OverridePort = profileInfo.TigerVNC_OverridePort; - TigerVNC_Port = profileInfo.TigerVNC_OverridePort ? profileInfo.TigerVNC_Port : SettingsManager.Current.TigerVNC_Port; - - // Web Console - WebConsole_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.WebConsole : profileInfo.WebConsole_Enabled; - WebConsole_Url = profileInfo.WebConsole_Url; + if (value == _whois_Domain) + return; - // Wake on LAN - WakeOnLAN_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.WakeOnLAN : profileInfo.WakeOnLAN_Enabled; - WakeOnLAN_MACAddress = profileInfo.WakeOnLAN_MACAddress; - WakeOnLAN_Broadcast = profileInfo.WakeOnLAN_Broadcast; - WakeOnLAN_OverridePort = profileInfo.WakeOnLAN_OverridePort; - WakeOnLAN_Port = profileInfo.WakeOnLAN_OverridePort ? profileInfo.WakeOnLAN_Port : SettingsManager.Current.WakeOnLAN_Port; - - // Whois - Whois_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.Whois : profileInfo.Whois_Enabled; - Whois_InheritHost = profileInfo.Whois_InheritHost; - Whois_Domain = profileInfo.Whois_Domain; - - _isLoading = false; + _whois_Domain = value; + OnPropertyChanged(); } + } + #endregion + #endregion + public ProfileViewModel(Action saveCommand, Action cancelHandler, IReadOnlyCollection groups, string group = null, ProfileEditMode editMode = ProfileEditMode.Add, ProfileInfo profile = null, ApplicationName applicationName = ApplicationName.None) + { + // Load the view + ProfileViews = new CollectionViewSource { Source = ProfileViewManager.List }.View; + ProfileViews.SortDescriptions.Add(new SortDescription(nameof(ProfileViewInfo.Name), ListSortDirection.Ascending)); + + SaveCommand = new RelayCommand(p => saveCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); + + var profileInfo = profile ?? new ProfileInfo(); + + Name = profileInfo.Name; + + if (editMode == ProfileEditMode.Copy) + Name += " - " + Localization.Resources.Strings.CopyNoun; + + Host = profileInfo.Host; + + // Try to get group (name) as parameter, then from profile, then the first in the list of groups, then the default group + Group = group ?? (string.IsNullOrEmpty(profileInfo.Group) ? (groups.Count > 0 ? groups.OrderBy(x => x).First() : Localization.Resources.Strings.Default) : profileInfo.Group); + + Tags = profileInfo.Tags; + + Groups = CollectionViewSource.GetDefaultView(groups); + Groups.SortDescriptions.Add(new SortDescription()); + + // Network Interface + NetworkInterface_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.NetworkInterface : profileInfo.NetworkInterface_Enabled; + NetworkInterface_EnableDynamicIPAddress = !profileInfo.NetworkInterface_EnableStaticIPAddress; + NetworkInterface_EnableStaticIPAddress = profileInfo.NetworkInterface_EnableStaticIPAddress; + NetworkInterface_IPAddress = profileInfo.NetworkInterface_IPAddress; + NetworkInterface_Gateway = profileInfo.NetworkInterface_Gateway; + NetworkInterface_SubnetmaskOrCidr = profileInfo.NetworkInterface_SubnetmaskOrCidr; + NetworkInterface_EnableDynamicDNS = !profileInfo.NetworkInterface_EnableStaticDNS; + NetworkInterface_EnableStaticDNS = profileInfo.NetworkInterface_EnableStaticDNS; + NetworkInterface_PrimaryDNSServer = profileInfo.NetworkInterface_PrimaryDNSServer; + NetworkInterface_SecondaryDNSServer = profileInfo.NetworkInterface_SecondaryDNSServer; + + // IP Scanner + IPScanner_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.IPScanner : profileInfo.IPScanner_Enabled; + IPScanner_InheritHost = profileInfo.IPScanner_InheritHost; + IPScanner_HostOrIPRange = profileInfo.IPScanner_HostOrIPRange; + + // Port Scanner + PortScanner_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PortScanner : profileInfo.PortScanner_Enabled; + PortScanner_InheritHost = profileInfo.PortScanner_InheritHost; + PortScanner_Host = profileInfo.PortScanner_Host; + PortScanner_Ports = profileInfo.PortScanner_Ports; + + // Ping Monitor + PingMonitor_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PingMonitor : profileInfo.PingMonitor_Enabled; + PingMonitor_InheritHost = profileInfo.PingMonitor_InheritHost; + PingMonitor_Host = profileInfo.PingMonitor_Host; + + // Traceroute + Traceroute_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.Traceroute : profileInfo.Traceroute_Enabled; + Traceroute_InheritHost = profileInfo.Traceroute_InheritHost; + Traceroute_Host = profileInfo.Traceroute_Host; + + // DNS Lookup + DNSLookup_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.DNSLookup : profileInfo.DNSLookup_Enabled; + DNSLookup_InheritHost = profileInfo.DNSLookup_InheritHost; + DNSLookup_Host = profileInfo.DNSLookup_Host; + + // Remote Desktop + RemoteDesktop_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.RemoteDesktop : profileInfo.RemoteDesktop_Enabled; + RemoteDesktop_InheritHost = profileInfo.RemoteDesktop_InheritHost; + RemoteDesktop_Host = profileInfo.RemoteDesktop_Host; + RemoteDesktop_UseCredentials = profileInfo.RemoteDesktop_UseCredentials; + RemoteDesktop_Username = profileInfo.RemoteDesktop_Username; + RemoteDesktop_Password = profileInfo.RemoteDesktop_Password; + RemoteDesktop_OverrideDisplay = profileInfo.RemoteDesktop_OverrideDisplay; + RemoteDesktop_AdjustScreenAutomatically = profileInfo.RemoteDesktop_AdjustScreenAutomatically; + RemoteDesktop_UseCurrentViewSize = profileInfo.RemoteDesktop_UseCurrentViewSize; + RemoteDesktop_UseFixedScreenSize = profileInfo.RemoteDesktop_UseFixedScreenSize; + RemoteDesktop_SelectedScreenResolution = RemoteDesktop_ScreenResolutions.FirstOrDefault(x => x == $"{profileInfo.RemoteDesktop_ScreenWidth}x{profileInfo.RemoteDesktop_ScreenHeight}"); + RemoteDesktop_UseCustomScreenSize = profileInfo.RemoteDesktop_UseCustomScreenSize; + RemoteDesktop_CustomScreenWidth = profileInfo.RemoteDesktop_CustomScreenWidth.ToString(); + RemoteDesktop_CustomScreenHeight = profileInfo.RemoteDesktop_CustomScreenHeight.ToString(); + RemoteDesktop_OverrideColorDepth = profileInfo.RemoteDesktop_OverrideColorDepth; + RemoteDesktop_SelectedColorDepth = RemoteDesktop_ColorDepths.FirstOrDefault(x => x == profileInfo.RemoteDesktop_ColorDepth); + RemoteDesktop_OverridePort = profileInfo.RemoteDesktop_OverridePort; + RemoteDesktop_Port = profileInfo.RemoteDesktop_Port; + RemoteDesktop_OverrideCredSspSupport = profileInfo.RemoteDesktop_OverrideCredSspSupport; + RemoteDesktop_EnableCredSspSupport = profileInfo.RemoteDesktop_EnableCredSspSupport; + RemoteDesktop_OverrideAuthenticationLevel = profileInfo.RemoteDesktop_OverrideAuthenticationLevel; + RemoteDesktop_AuthenticationLevel = profileInfo.RemoteDesktop_AuthenticationLevel; + RemoteDesktop_OverrideAudioRedirectionMode = profileInfo.RemoteDesktop_OverrideAudioRedirectionMode; + RemoteDesktop_AudioRedirectionMode = RemoteDesktop_AudioRedirectionModes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_AudioRedirectionMode); + RemoteDesktop_OverrideAudioCaptureRedirectionMode = profileInfo.RemoteDesktop_OverrideAudioCaptureRedirectionMode; + RemoteDesktop_AudioCaptureRedirectionMode = RemoteDesktop_AudioCaptureRedirectionModes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_AudioCaptureRedirectionMode); + RemoteDesktop_OverrideApplyWindowsKeyCombinations = profileInfo.RemoteDesktop_OverrideApplyWindowsKeyCombinations; + RemoteDesktop_KeyboardHookMode = RemoteDesktop_KeyboardHookModes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_KeyboardHookMode); + RemoteDesktop_OverrideRedirectClipboard = profileInfo.RemoteDesktop_OverrideRedirectClipboard; + RemoteDesktop_RedirectClipboard = profileInfo.RemoteDesktop_RedirectClipboard; + RemoteDesktop_OverrideRedirectDevices = profileInfo.RemoteDesktop_OverrideRedirectDevices; + RemoteDesktop_RedirectDevices = profileInfo.RemoteDesktop_RedirectDevices; + RemoteDesktop_OverrideRedirectDrives = profileInfo.RemoteDesktop_OverrideRedirectDrives; + RemoteDesktop_RedirectDrives = profileInfo.RemoteDesktop_RedirectDrives; + RemoteDesktop_OverrideRedirectPorts = profileInfo.RemoteDesktop_OverrideRedirectPorts; + RemoteDesktop_RedirectPorts = profileInfo.RemoteDesktop_RedirectPorts; + RemoteDesktop_OverrideRedirectSmartcards = profileInfo.RemoteDesktop_OverrideRedirectSmartcards; + RemoteDesktop_RedirectSmartCards = profileInfo.RemoteDesktop_RedirectSmartCards; + RemoteDesktop_OverrideRedirectPrinters = profileInfo.RemoteDesktop_OverrideRedirectPrinters; + RemoteDesktop_RedirectPrinters = profileInfo.RemoteDesktop_RedirectPrinters; + RemoteDesktop_OverridePersistentBitmapCaching = profileInfo.RemoteDesktop_OverridePersistentBitmapCaching; + RemoteDesktop_PersistentBitmapCaching = profileInfo.RemoteDesktop_PersistentBitmapCaching; + RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped = profileInfo.RemoteDesktop_OverrideReconnectIfTheConnectionIsDropped; + RemoteDesktop_ReconnectIfTheConnectionIsDropped = profileInfo.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + RemoteDesktop_NetworkConnectionType = RemoteDesktop_NetworkConnectionTypes.FirstOrDefault(x => x == profileInfo.RemoteDesktop_NetworkConnectionType); + RemoteDesktop_DesktopBackground = profileInfo.RemoteDesktop_DesktopBackground; + RemoteDesktop_FontSmoothing = profileInfo.RemoteDesktop_FontSmoothing; + RemoteDesktop_DesktopComposition = profileInfo.RemoteDesktop_DesktopComposition; + RemoteDesktop_ShowWindowContentsWhileDragging = profileInfo.RemoteDesktop_ShowWindowContentsWhileDragging; + RemoteDesktop_MenuAndWindowAnimation = profileInfo.RemoteDesktop_MenuAndWindowAnimation; + RemoteDesktop_VisualStyles = profileInfo.RemoteDesktop_VisualStyles; + + // PowerShell + PowerShell_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PowerShell : profileInfo.PowerShell_Enabled; + PowerShell_EnableRemoteConsole = profileInfo.PowerShell_EnableRemoteConsole; + PowerShell_InheritHost = profileInfo.PowerShell_InheritHost; + PowerShell_Host = profileInfo.PowerShell_Host; + PowerShell_OverrideCommand = profileInfo.PowerShell_OverrideCommand; + PowerShell_Command = profileInfo.PowerShell_Command; + PowerShell_OverrideAdditionalCommandLine = profileInfo.PowerShell_OverrideAdditionalCommandLine; + PowerShell_AdditionalCommandLine = profileInfo.PowerShell_AdditionalCommandLine; + PowerShell_ExecutionPolicies = Enum.GetValues(typeof(PowerShell.ExecutionPolicy)).Cast().ToList(); + PowerShell_OverrideExecutionPolicy = profileInfo.PowerShell_OverrideExecutionPolicy; + PowerShell_ExecutionPolicy = editMode != ProfileEditMode.Add ? profileInfo.PowerShell_ExecutionPolicy : PowerShell_ExecutionPolicies.FirstOrDefault(x => x == SettingsManager.Current.PowerShell_ExecutionPolicy); ; + + // PuTTY + PuTTY_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.PuTTY : profileInfo.PuTTY_Enabled; + + switch (profileInfo.PuTTY_ConnectionMode) + { + // SSH is default + case ConnectionMode.SSH: + PuTTY_UseSSH = true; + break; + case ConnectionMode.Telnet: + PuTTY_UseTelnet = true; + break; + case ConnectionMode.Serial: + PuTTY_UseSerial = true; + break; + case ConnectionMode.Rlogin: + PuTTY_UseRlogin = true; + break; + case ConnectionMode.RAW: + PuTTY_UseRAW = true; + break; + } + + PuTTY_InheritHost = profileInfo.PuTTY_InheritHost; + PuTTY_HostOrSerialLine = profileInfo.PuTTY_HostOrSerialLine; + PuTTY_OverridePortOrBaud = profileInfo.PuTTY_OverridePortOrBaud; + PuTTY_PortOrBaud = profileInfo.PuTTY_OverridePortOrBaud ? profileInfo.PuTTY_PortOrBaud : Settings.Application.PuTTY.GetPortOrBaudByConnectionMode(PuTTY_ConnectionMode); + PuTTY_OverrideUsername = profileInfo.PuTTY_OverrideUsername; + PuTTY_Username = profileInfo.PuTTY_Username; + PuTTY_OverridePrivateKeyFile = profileInfo.PuTTY_OverridePrivateKeyFile; + PuTTY_PrivateKeyFile = profileInfo.PuTTY_PrivateKeyFile; + PuTTY_OverrideProfile = profileInfo.PuTTY_OverrideProfile; + PuTTY_Profile = profileInfo.PuTTY_Profile; + PuTTY_OverrideHostkey = profileInfo.PuTTY_OverrideHostkey; + PuTTY_Hostkey = profileInfo.PuTTY_Hostkey; + PuTTY_OverrideEnableLog = profileInfo.PuTTY_OverrideEnableLog; + PuTTY_EnableLog = profileInfo.PuTTY_EnableLog; + PuTTY_OverrideLogMode = profileInfo.PuTTY_OverrideLogMode; + PuTTY_LogMode = PuTTY_LogModes.FirstOrDefault(x => x == profileInfo.PuTTY_LogMode); + PuTTY_OverrideLogPath = profileInfo.PuTTY_OverrideLogPath; + PuTTY_LogPath = profileInfo.PuTTY_LogPath; + PuTTY_OverrideLogFileName = profileInfo.PuTTY_OverrideLogFileName; + PuTTY_LogFileName = profileInfo.PuTTY_LogFileName; + PuTTY_OverrideAdditionalCommandLine = profileInfo.PuTTY_OverrideAdditionalCommandLine; + PuTTY_AdditionalCommandLine = profileInfo.PuTTY_AdditionalCommandLine; + + // AWS Session Manager + AWSSessionManager_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.AWSSessionManager : profileInfo.AWSSessionManager_Enabled; + AWSSessionManager_InstanceID = profileInfo.AWSSessionManager_InstanceID; + AWSSessionManager_OverrideProfile = profileInfo.AWSSessionManager_OverrideProfile; + AWSSessionManager_Profile = profileInfo.AWSSessionManager_Profile; + AWSSessionManager_OverrideRegion = profileInfo.AWSSessionManager_OverrideRegion; + AWSSessionManager_Region = profileInfo.AWSSessionManager_Region; + + // TigerVNC + TigerVNC_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.TigerVNC : profileInfo.TigerVNC_Enabled; + TigerVNC_InheritHost = profileInfo.TigerVNC_InheritHost; + TigerVNC_Host = profileInfo.TigerVNC_Host; + TigerVNC_OverridePort = profileInfo.TigerVNC_OverridePort; + TigerVNC_Port = profileInfo.TigerVNC_OverridePort ? profileInfo.TigerVNC_Port : SettingsManager.Current.TigerVNC_Port; + + // Web Console + WebConsole_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.WebConsole : profileInfo.WebConsole_Enabled; + WebConsole_Url = profileInfo.WebConsole_Url; + + // Wake on LAN + WakeOnLAN_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.WakeOnLAN : profileInfo.WakeOnLAN_Enabled; + WakeOnLAN_MACAddress = profileInfo.WakeOnLAN_MACAddress; + WakeOnLAN_Broadcast = profileInfo.WakeOnLAN_Broadcast; + WakeOnLAN_OverridePort = profileInfo.WakeOnLAN_OverridePort; + WakeOnLAN_Port = profileInfo.WakeOnLAN_OverridePort ? profileInfo.WakeOnLAN_Port : SettingsManager.Current.WakeOnLAN_Port; + + // Whois + Whois_Enabled = editMode == ProfileEditMode.Add ? applicationName == ApplicationName.Whois : profileInfo.Whois_Enabled; + Whois_InheritHost = profileInfo.Whois_InheritHost; + Whois_Domain = profileInfo.Whois_Domain; + + _isLoading = false; + } - #region ICommands & Actions - public ICommand SaveCommand { get; } + #region ICommands & Actions + public ICommand SaveCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - public ICommand ResolveHostCommand => new RelayCommand(async p => await ResolveHostActionAsync()); + public ICommand ResolveHostCommand => new RelayCommand(async p => await ResolveHostActionAsync()); - private async System.Threading.Tasks.Task ResolveHostActionAsync() - { - IsResolveHostnameRunning = true; + private async System.Threading.Tasks.Task ResolveHostActionAsync() + { + IsResolveHostnameRunning = true; - var dnsResult = await DNSClientHelper.ResolveAorAaaaAsync(Host, SettingsManager.Current.Network_ResolveHostnamePreferIPv4); + var dnsResult = await DNSClientHelper.ResolveAorAaaaAsync(Host, SettingsManager.Current.Network_ResolveHostnamePreferIPv4); - if (!dnsResult.HasError) - Host = dnsResult.Value.ToString(); - else - ShowCouldNotResolveHostnameWarning = true; + if (!dnsResult.HasError) + Host = dnsResult.Value.ToString(); + else + ShowCouldNotResolveHostnameWarning = true; - IsResolveHostnameRunning = false; - } + IsResolveHostnameRunning = false; + } - public ICommand RemoteDesktopPasswordChangedCommand => new RelayCommand(p => RemoteDesktopPasswordChangedAction()); + public ICommand RemoteDesktopPasswordChangedCommand => new RelayCommand(p => RemoteDesktopPasswordChangedAction()); - #endregion + #endregion - #region Methods - private void RemoteDesktopPasswordChangedAction() - { - RemoteDesktop_PasswordChanged = true; - } + #region Methods + private void RemoteDesktopPasswordChangedAction() + { + RemoteDesktop_PasswordChanged = true; + } - private void ChangeNetworkConnectionTypeSettings(NetworkConnectionType connectionSpeed) - { - switch (connectionSpeed) - { - case NetworkConnectionType.Modem: - RemoteDesktop_DesktopBackground = false; - RemoteDesktop_FontSmoothing = false; - RemoteDesktop_DesktopComposition = false; - RemoteDesktop_ShowWindowContentsWhileDragging = false; - RemoteDesktop_MenuAndWindowAnimation = false; - RemoteDesktop_VisualStyles = false; - break; - case NetworkConnectionType.BroadbandLow: - RemoteDesktop_DesktopBackground = false; - RemoteDesktop_FontSmoothing = false; - RemoteDesktop_DesktopComposition = false; - RemoteDesktop_ShowWindowContentsWhileDragging = false; - RemoteDesktop_MenuAndWindowAnimation = false; - RemoteDesktop_VisualStyles = true; - break; - case NetworkConnectionType.Satellite: - case NetworkConnectionType.BroadbandHigh: - RemoteDesktop_DesktopBackground = false; - RemoteDesktop_FontSmoothing = false; - RemoteDesktop_DesktopComposition = true; - RemoteDesktop_ShowWindowContentsWhileDragging = false; - RemoteDesktop_MenuAndWindowAnimation = false; - RemoteDesktop_VisualStyles = true; - break; - case NetworkConnectionType.WAN: - case NetworkConnectionType.LAN: - RemoteDesktop_DesktopBackground = true; - RemoteDesktop_FontSmoothing = true; - RemoteDesktop_DesktopComposition = true; - RemoteDesktop_ShowWindowContentsWhileDragging = true; - RemoteDesktop_MenuAndWindowAnimation = true; - RemoteDesktop_VisualStyles = true; - break; - } + private void ChangeNetworkConnectionTypeSettings(NetworkConnectionType connectionSpeed) + { + switch (connectionSpeed) + { + case NetworkConnectionType.Modem: + RemoteDesktop_DesktopBackground = false; + RemoteDesktop_FontSmoothing = false; + RemoteDesktop_DesktopComposition = false; + RemoteDesktop_ShowWindowContentsWhileDragging = false; + RemoteDesktop_MenuAndWindowAnimation = false; + RemoteDesktop_VisualStyles = false; + break; + case NetworkConnectionType.BroadbandLow: + RemoteDesktop_DesktopBackground = false; + RemoteDesktop_FontSmoothing = false; + RemoteDesktop_DesktopComposition = false; + RemoteDesktop_ShowWindowContentsWhileDragging = false; + RemoteDesktop_MenuAndWindowAnimation = false; + RemoteDesktop_VisualStyles = true; + break; + case NetworkConnectionType.Satellite: + case NetworkConnectionType.BroadbandHigh: + RemoteDesktop_DesktopBackground = false; + RemoteDesktop_FontSmoothing = false; + RemoteDesktop_DesktopComposition = true; + RemoteDesktop_ShowWindowContentsWhileDragging = false; + RemoteDesktop_MenuAndWindowAnimation = false; + RemoteDesktop_VisualStyles = true; + break; + case NetworkConnectionType.WAN: + case NetworkConnectionType.LAN: + RemoteDesktop_DesktopBackground = true; + RemoteDesktop_FontSmoothing = true; + RemoteDesktop_DesktopComposition = true; + RemoteDesktop_ShowWindowContentsWhileDragging = true; + RemoteDesktop_MenuAndWindowAnimation = true; + RemoteDesktop_VisualStyles = true; + break; } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ProfilesViewModel.cs b/Source/NETworkManager/ViewModels/ProfilesViewModel.cs index bf0aa2bb51..77e518d577 100644 --- a/Source/NETworkManager/ViewModels/ProfilesViewModel.cs +++ b/Source/NETworkManager/ViewModels/ProfilesViewModel.cs @@ -14,299 +14,298 @@ using System.Windows; using System.ComponentModel.DataAnnotations; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ProfilesViewModel : ViewModelBase, IProfileManager { - public class ProfilesViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public ICollectionView _groups; - public ICollectionView Groups + public ICollectionView _groups; + public ICollectionView Groups + { + get => _groups; + set { - get => _groups; - set - { - if (value == _groups) - return; - - _groups = value; - OnPropertyChanged(); - } + if (value == _groups) + return; + + _groups = value; + OnPropertyChanged(); } - - private ProfileInfo _profileInfoOnRefresh = null; + } + + private ProfileInfo _profileInfoOnRefresh = null; - private GroupInfo _selectedGroup = new(); - public GroupInfo SelectedGroup + private GroupInfo _selectedGroup = new(); + public GroupInfo SelectedGroup + { + get => _selectedGroup; + set { - get => _selectedGroup; - set - { - if (value == _selectedGroup) - return; - - // NullReferenceException occurs if profile file is changed - if (value == null) - Profiles = null; - else - SetProfilesView(value.Name, _profileInfoOnRefresh); - - _selectedGroup = value; - OnPropertyChanged(); - } + if (value == _selectedGroup) + return; + + // NullReferenceException occurs if profile file is changed + if (value == null) + Profiles = null; + else + SetProfilesView(value.Name, _profileInfoOnRefresh); + + _selectedGroup = value; + OnPropertyChanged(); } + } - public ICollectionView _profiles; - public ICollectionView Profiles + public ICollectionView _profiles; + public ICollectionView Profiles + { + get => _profiles; + set { - get => _profiles; - set - { - if (value == _profiles) - return; - - _profiles = value; - OnPropertyChanged(); - } + if (value == _profiles) + return; + + _profiles = value; + OnPropertyChanged(); } + } - private ProfileInfo _selectedProfile = new(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; - - _selectedProfile = value; - OnPropertyChanged(); - } + if (value == _selectedProfile) + return; + + _selectedProfile = value; + OnPropertyChanged(); } + } - private IList _selectedProfiles = new ArrayList(); - public IList SelectedProfiles + private IList _selectedProfiles = new ArrayList(); + public IList SelectedProfiles + { + get => _selectedProfiles; + set { - get => _selectedProfiles; - set - { - if (Equals(value, _selectedProfiles)) - return; - - _selectedProfiles = value; - OnPropertyChanged(); - } + if (Equals(value, _selectedProfiles)) + return; + + _selectedProfiles = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; - - _isSearching = value; - OnPropertyChanged(); - } + if (value == _isSearching) + return; + + _isSearching = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor - public ProfilesViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor + public ProfilesViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - SetGroupView(); + SetGroupView(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - } + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + } - public void SetGroupView() - { - Groups = new CollectionViewSource { Source = ProfileManager.Groups.Where(x => !x.IsDynamic) }.View; + public void SetGroupView() + { + Groups = new CollectionViewSource { Source = ProfileManager.Groups.Where(x => !x.IsDynamic) }.View; - Groups.SortDescriptions.Add(new SortDescription(nameof(GroupInfo.Name), ListSortDirection.Ascending)); + Groups.SortDescriptions.Add(new SortDescription(nameof(GroupInfo.Name), ListSortDirection.Ascending)); - SelectedGroup = Groups.SourceCollection.Cast().OrderBy(x => x.Name).FirstOrDefault(); - } + SelectedGroup = Groups.SourceCollection.Cast().OrderBy(x => x.Name).FirstOrDefault(); + } - public void SetProfilesView(string groupName, ProfileInfo selectedProfileInfo = null) - { - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.FirstOrDefault(x => x.Name.Equals(groupName)).Profiles.Where(x => !x.IsDynamic) }.View; + public void SetProfilesView(string groupName, ProfileInfo selectedProfileInfo = null) + { + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.FirstOrDefault(x => x.Name.Equals(groupName)).Profiles.Where(x => !x.IsDynamic) }.View; - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (string.IsNullOrEmpty(Search)) - return true; + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (string.IsNullOrEmpty(Search)) + return true; - if (o is not ProfileInfo info) - return false; + if (o is not ProfileInfo info) + return false; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name - return info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1; - }; + // Search by: Name + return info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1; + }; - // Set specific profile or first if null - SelectedProfile = Profiles.SourceCollection.Cast().FirstOrDefault(x => x.Equals(selectedProfileInfo)) ?? Profiles.SourceCollection.Cast().OrderBy(x => x.Name).FirstOrDefault(); + // Set specific profile or first if null + SelectedProfile = Profiles.SourceCollection.Cast().FirstOrDefault(x => x.Equals(selectedProfileInfo)) ?? Profiles.SourceCollection.Cast().OrderBy(x => x.Name).FirstOrDefault(); - SelectedProfiles = new List { SelectedProfile }; // Fix --> Count need to be 1 for EditProfile_CanExecute - } - #endregion + SelectedProfiles = new List { SelectedProfile }; // Fix --> Count need to be 1 for EditProfile_CanExecute + } + #endregion - #region Commands & Actions - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + #region Commands & Actions + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, SelectedGroup?.Name); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, SelectedGroup?.Name); + } - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), EditProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), EditProfile_CanExecute); - private bool EditProfile_CanExecute(object paramter) => SelectedProfiles.Count == 1; + private bool EditProfile_CanExecute(object paramter) => SelectedProfiles.Count == 1; - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List(SelectedProfiles.Cast())); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List(SelectedProfiles.Cast())); + } - public ICommand AddGroupCommand => new RelayCommand(p => AddGroupAction()); + public ICommand AddGroupCommand => new RelayCommand(p => AddGroupAction()); - private void AddGroupAction() - { - ProfileDialogManager.ShowAddGroupDialog(this, _dialogCoordinator); - } + private void AddGroupAction() + { + ProfileDialogManager.ShowAddGroupDialog(this, _dialogCoordinator); + } - public ICommand EditGroupCommand => new RelayCommand(p => EditGroupAction()); + public ICommand EditGroupCommand => new RelayCommand(p => EditGroupAction()); - private void EditGroupAction() - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, SelectedGroup); - } + private void EditGroupAction() + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, SelectedGroup); + } - public ICommand DeleteGroupCommand => new RelayCommand(p => DeleteGroupAction()); + public ICommand DeleteGroupCommand => new RelayCommand(p => DeleteGroupAction()); - private void DeleteGroupAction() - { - ProfileDialogManager.ShowDeleteGroupDialog(this, _dialogCoordinator, SelectedGroup); - } - #endregion + private void DeleteGroupAction() + { + ProfileDialogManager.ShowDeleteGroupDialog(this, _dialogCoordinator, SelectedGroup); + } + #endregion - #region Methods - private void StartDelayedSearch() + #region Methods + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); - - RefreshProfiles(); - - IsSearching = false; + _searchDispatcherTimer.Start(); } + } - public async void RefreshProfiles() - { - var _selectedGroup = SelectedGroup; - _profileInfoOnRefresh = SelectedProfile; + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - if (SelectedGroup == null) - SetGroupView(); + RefreshProfiles(); - await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Groups?.Refresh(); + IsSearching = false; + } - // Set group again after refresh or first if null (_selectedGroup can be null in some cases) - SelectedGroup = Groups.SourceCollection.Cast().FirstOrDefault(x => x.Name == _selectedGroup?.Name) ?? Groups.SourceCollection.Cast().OrderBy(x => x.Name).FirstOrDefault(); - })); + public async void RefreshProfiles() + { + var _selectedGroup = SelectedGroup; + _profileInfoOnRefresh = SelectedProfile; - _profileInfoOnRefresh = null; - } + if (SelectedGroup == null) + SetGroupView(); - public void OnProfileDialogOpen() + await Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Groups?.Refresh(); - } + // Set group again after refresh or first if null (_selectedGroup can be null in some cases) + SelectedGroup = Groups.SourceCollection.Cast().FirstOrDefault(x => x.Name == _selectedGroup?.Name) ?? Groups.SourceCollection.Cast().OrderBy(x => x.Name).FirstOrDefault(); + })); - public void OnProfileDialogClose() - { + _profileInfoOnRefresh = null; + } - } - #endregion + public void OnProfileDialogOpen() + { - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - // Update group view (and profile view) when the profile file has changed - RefreshProfiles(); - } + } - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + public void OnProfileDialogClose() + { + + } + #endregion + + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + // Update group view (and profile view) when the profile file has changed + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PuTTYConnectViewModel.cs b/Source/NETworkManager/ViewModels/PuTTYConnectViewModel.cs index 22930d5e06..3867bcd9a9 100644 --- a/Source/NETworkManager/ViewModels/PuTTYConnectViewModel.cs +++ b/Source/NETworkManager/ViewModels/PuTTYConnectViewModel.cs @@ -6,298 +6,297 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + + +public class PuTTYConnectViewModel : ViewModelBase { - - public class PuTTYConnectViewModel : ViewModelBase - { - public ICommand ConnectCommand { get; } + public ICommand ConnectCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - public int DefaultSSHPort => SettingsManager.Current.PuTTY_SSHPort; - public int DefaultTelnetPort => SettingsManager.Current.PuTTY_TelnetPort; - public int DefaultBaudRate => SettingsManager.Current.PuTTY_BaudRate; - public int DefaultRloginPort => SettingsManager.Current.PuTTY_RloginPort; - public int DefaultRaw => SettingsManager.Current.PuTTY_DefaultRaw; + public int DefaultSSHPort => SettingsManager.Current.PuTTY_SSHPort; + public int DefaultTelnetPort => SettingsManager.Current.PuTTY_TelnetPort; + public int DefaultBaudRate => SettingsManager.Current.PuTTY_BaudRate; + public int DefaultRloginPort => SettingsManager.Current.PuTTY_RloginPort; + public int DefaultRaw => SettingsManager.Current.PuTTY_DefaultRaw; - public ConnectionMode ConnectionMode { get; set; } + public ConnectionMode ConnectionMode { get; set; } - private bool _useSSH; - public bool UseSSH + private bool _useSSH; + public bool UseSSH + { + get => _useSSH; + set { - get => _useSSH; - set - { - if (value == _useSSH) - return; + if (value == _useSSH) + return; - if (value) - { - Port = DefaultSSHPort; - ConnectionMode = ConnectionMode.SSH; - } - - _useSSH = value; - OnPropertyChanged(); + if (value) + { + Port = DefaultSSHPort; + ConnectionMode = ConnectionMode.SSH; } + + _useSSH = value; + OnPropertyChanged(); } + } - private bool _useTelnet; - public bool UseTelnet + private bool _useTelnet; + public bool UseTelnet + { + get => _useTelnet; + set { - get => _useTelnet; - set - { - if (value == _useTelnet) - return; - - if (value) - { - Port = DefaultTelnetPort; - ConnectionMode = ConnectionMode.Telnet; - } + if (value == _useTelnet) + return; - _useTelnet = value; - OnPropertyChanged(); + if (value) + { + Port = DefaultTelnetPort; + ConnectionMode = ConnectionMode.Telnet; } + + _useTelnet = value; + OnPropertyChanged(); } + } - private bool _useSerial; - public bool UseSerial + private bool _useSerial; + public bool UseSerial + { + get => _useSerial; + set { - get => _useSerial; - set - { - if (value == _useSerial) - return; + if (value == _useSerial) + return; - if (value) - { - Baud = DefaultBaudRate; - ConnectionMode = ConnectionMode.Serial; - } - - _useSerial = value; - OnPropertyChanged(); + if (value) + { + Baud = DefaultBaudRate; + ConnectionMode = ConnectionMode.Serial; } + + _useSerial = value; + OnPropertyChanged(); } + } - private bool _useRlogin; - public bool UseRlogin + private bool _useRlogin; + public bool UseRlogin + { + get => _useRlogin; + set { - get => _useRlogin; - set - { - if (value == _useRlogin) - return; - - if (value) - { - Port = DefaultRloginPort; - ConnectionMode = ConnectionMode.Rlogin; - } + if (value == _useRlogin) + return; - _useRlogin = value; - OnPropertyChanged(); + if (value) + { + Port = DefaultRloginPort; + ConnectionMode = ConnectionMode.Rlogin; } + + _useRlogin = value; + OnPropertyChanged(); } + } - private bool _useRAW; - public bool UseRAW + private bool _useRAW; + public bool UseRAW + { + get => _useRAW; + set { - get => _useRAW; - set - { - if (value == _useRAW) - return; + if (value == _useRAW) + return; - if (value) - { - Port = DefaultRaw; - ConnectionMode = ConnectionMode.RAW; - } - - _useRAW = value; - OnPropertyChanged(); + if (value) + { + Port = DefaultRaw; + ConnectionMode = ConnectionMode.RAW; } + + _useRAW = value; + OnPropertyChanged(); } + } - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; + if (value == _host) + return; - _host = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } + } - private string _serialLine; - public string SerialLine + private string _serialLine; + public string SerialLine + { + get => _serialLine; + set { - get => _serialLine; - set - { - if (value == _serialLine) - return; + if (value == _serialLine) + return; - _serialLine = value; - OnPropertyChanged(); - } + _serialLine = value; + OnPropertyChanged(); } + } - private int _port; - public int Port + private int _port; + public int Port + { + get => _port; + set { - get => _port; - set - { - if (value == _port) - return; + if (value == _port) + return; - _port = value; - OnPropertyChanged(); - } + _port = value; + OnPropertyChanged(); } + } - private int _baud; - public int Baud + private int _baud; + public int Baud + { + get => _baud; + set { - get => _baud; - set - { - if (value == _baud) - return; + if (value == _baud) + return; - _baud = value; - OnPropertyChanged(); - } + _baud = value; + OnPropertyChanged(); } + } - private string _username; - public string Username + private string _username; + public string Username + { + get => _username; + set { - get => _username; - set - { - if (value == _username) - return; + if (value == _username) + return; - _username = value; - OnPropertyChanged(); - } + _username = value; + OnPropertyChanged(); } + } - private string _privateKeyFile; - public string PrivateKeyFile + private string _privateKeyFile; + public string PrivateKeyFile + { + get => _privateKeyFile; + set { - get => _privateKeyFile; - set - { - if (value == _privateKeyFile) - return; + if (value == _privateKeyFile) + return; - _privateKeyFile = value; - OnPropertyChanged(); - } + _privateKeyFile = value; + OnPropertyChanged(); } + } - private string _profile; - public string Profile + private string _profile; + public string Profile + { + get => _profile; + set { - get => _profile; - set - { - if (value == _profile) - return; + if (value == _profile) + return; - _profile = value; - OnPropertyChanged(); - } + _profile = value; + OnPropertyChanged(); } + } - private string _additionalCommandLine; - public string AdditionalCommandLine + private string _additionalCommandLine; + public string AdditionalCommandLine + { + get => _additionalCommandLine; + set { - get => _additionalCommandLine; - set - { - if (value == _additionalCommandLine) - return; + if (value == _additionalCommandLine) + return; - _additionalCommandLine = value; - OnPropertyChanged(); - } + _additionalCommandLine = value; + OnPropertyChanged(); } + } - public ICollectionView HostHistoryView { get; } - - public ICollectionView SerialLineHistoryView { get; } + public ICollectionView HostHistoryView { get; } - public ICollectionView PortHistoryView { get; } + public ICollectionView SerialLineHistoryView { get; } - public ICollectionView BaudHistoryView { get; } + public ICollectionView PortHistoryView { get; } - public ICollectionView UsernameHistoryView { get; } + public ICollectionView BaudHistoryView { get; } - public ICollectionView PrivateKeyFileHistoryView { get; set; } + public ICollectionView UsernameHistoryView { get; } - public ICollectionView ProfileHistoryView { get; } + public ICollectionView PrivateKeyFileHistoryView { get; set; } - public PuTTYConnectViewModel(Action connectCommand, Action cancelHandler, string host = null) - { - ConnectCommand = new RelayCommand(p => connectCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + public ICollectionView ProfileHistoryView { get; } - if (!string.IsNullOrEmpty(host)) - Host = host; + public PuTTYConnectViewModel(Action connectCommand, Action cancelHandler, string host = null) + { + ConnectCommand = new RelayCommand(p => connectCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_HostHistory); - SerialLineHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_SerialLineHistory); - PortHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_PortHistory); - BaudHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_BaudHistory); - UsernameHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_UsernameHistory); - PrivateKeyFileHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_PrivateKeyFileHistory); - ProfileHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_ProfileHistory); + if (!string.IsNullOrEmpty(host)) + Host = host; - LoadSettings(); - } + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_HostHistory); + SerialLineHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_SerialLineHistory); + PortHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_PortHistory); + BaudHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_BaudHistory); + UsernameHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_UsernameHistory); + PrivateKeyFileHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_PrivateKeyFileHistory); + ProfileHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.PuTTY_ProfileHistory); - private void LoadSettings() - { + LoadSettings(); + } - ConnectionMode = SettingsManager.Current.PuTTY_DefaultConnectionMode; + private void LoadSettings() + { - switch (ConnectionMode) - { - case ConnectionMode.SSH: - UseSSH = true; - break; - case ConnectionMode.Telnet: - UseTelnet = true; - break; - case ConnectionMode.Serial: - UseSerial = true; - break; - case ConnectionMode.Rlogin: - UseRlogin = true; - break; - case ConnectionMode.RAW: - UseRAW = true; - break; - } + ConnectionMode = SettingsManager.Current.PuTTY_DefaultConnectionMode; - Username = SettingsManager.Current.PuTTY_Username; - PrivateKeyFile = SettingsManager.Current.PuTTY_PrivateKeyFile; - Profile = SettingsManager.Current.PuTTY_Profile; - SerialLine = SettingsManager.Current.PuTTY_SerialLine; - AdditionalCommandLine = SettingsManager.Current.PuTTY_AdditionalCommandLine; + switch (ConnectionMode) + { + case ConnectionMode.SSH: + UseSSH = true; + break; + case ConnectionMode.Telnet: + UseTelnet = true; + break; + case ConnectionMode.Serial: + UseSerial = true; + break; + case ConnectionMode.Rlogin: + UseRlogin = true; + break; + case ConnectionMode.RAW: + UseRAW = true; + break; } + + Username = SettingsManager.Current.PuTTY_Username; + PrivateKeyFile = SettingsManager.Current.PuTTY_PrivateKeyFile; + Profile = SettingsManager.Current.PuTTY_Profile; + SerialLine = SettingsManager.Current.PuTTY_SerialLine; + AdditionalCommandLine = SettingsManager.Current.PuTTY_AdditionalCommandLine; } } diff --git a/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs b/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs index a2939b1614..46b2fa74d6 100644 --- a/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PuTTYHostViewModel.cs @@ -21,681 +21,680 @@ using System.Threading.Tasks; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PuTTYHostViewModel : ViewModelBase, IProfileManager { - public class PuTTYHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private bool _isConfigured; - public bool IsConfigured + private bool _isConfigured; + public bool IsConfigured + { + get => _isConfigured; + set { - get => _isConfigured; - set - { - if (value == _isConfigured) - return; + if (value == _isConfigured) + return; - _isConfigured = value; - OnPropertyChanged(); - } + _isConfigured = value; + OnPropertyChanged(); } + } - private bool _disableFocusEmbeddedWindow; + private bool _disableFocusEmbeddedWindow; - private DragablzTabItem _selectedTabItem; - public DragablzTabItem SelectedTabItem + private DragablzTabItem _selectedTabItem; + public DragablzTabItem SelectedTabItem + { + get => _selectedTabItem; + set { - get => _selectedTabItem; - set - { - if (value == _selectedTabItem) - return; + if (value == _selectedTabItem) + return; - _selectedTabItem = value; + _selectedTabItem = value; - // Focus embedded window on switching tab - if (!_disableFocusEmbeddedWindow) - FocusEmbeddedWindow(); + // Focus embedded window on switching tab + if (!_disableFocusEmbeddedWindow) + FocusEmbeddedWindow(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _headerContextMenuIsOpen; - public bool HeaderContextMenuIsOpen + private bool _headerContextMenuIsOpen; + public bool HeaderContextMenuIsOpen + { + get => _headerContextMenuIsOpen; + set { - get => _headerContextMenuIsOpen; - set - { - if (value == _headerContextMenuIsOpen) - return; + if (value == _headerContextMenuIsOpen) + return; - _headerContextMenuIsOpen = value; - OnPropertyChanged(); - } + _headerContextMenuIsOpen = value; + OnPropertyChanged(); } + } - #region Profiles + #region Profiles - public ICollectionView Profiles { get; } + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _textBoxSearchIsFocused; - public bool TextBoxSearchIsFocused + private bool _textBoxSearchIsFocused; + public bool TextBoxSearchIsFocused + { + get => _textBoxSearchIsFocused; + set { - get => _textBoxSearchIsFocused; - set - { - if (value == _textBoxSearchIsFocused) - return; + if (value == _textBoxSearchIsFocused) + return; - _textBoxSearchIsFocused = value; - OnPropertyChanged(); - } + _textBoxSearchIsFocused = value; + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.PuTTY_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.PuTTY_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.PuTTY_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.PuTTY_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _profileContextMenuIsOpen; - public bool ProfileContextMenuIsOpen + private bool _profileContextMenuIsOpen; + public bool ProfileContextMenuIsOpen + { + get => _profileContextMenuIsOpen; + set { - get => _profileContextMenuIsOpen; - set - { - if (value == _profileContextMenuIsOpen) - return; + if (value == _profileContextMenuIsOpen) + return; - _profileContextMenuIsOpen = value; - OnPropertyChanged(); - } + _profileContextMenuIsOpen = value; + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public PuTTYHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public PuTTYHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - CheckSettings(); + CheckSettings(); - InterTabClient = new DragablzInterTabClient(ApplicationName.PuTTY); + InterTabClient = new DragablzInterTabClient(ApplicationName.PuTTY); - TabItems = new ObservableCollection(); + TabItems = new ObservableCollection(); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (o is not ProfileInfo info) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (o is not ProfileInfo info) + return false; - if (string.IsNullOrEmpty(Search)) - return info.PuTTY_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.PuTTY_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.PuTTY_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.PuTTY_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, PuTTY_HostOrSerialLine - return info.PuTTY_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PuTTY_HostOrSerialLine.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, PuTTY_HostOrSerialLine + return info.PuTTY_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.PuTTY_HostOrSerialLine.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PuTTY_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.PuTTY_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += Current_PropertyChanged; + SettingsManager.Current.PropertyChanged += Current_PropertyChanged; - _isLoading = false; - } - - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.PuTTY_ExpandProfileView; + _isLoading = false; + } + + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.PuTTY_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PuTTY_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.PuTTY_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.PuTTY_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.PuTTY_ProfileWidth; + } + #endregion - private void WriteDefaultProfileToRegistry() - { - if (IsConfigured) - PuTTY.WriteDefaultProfileToRegistry(SettingsManager.Current.Appearance_Theme); - } + private void WriteDefaultProfileToRegistry() + { + if (IsConfigured) + PuTTY.WriteDefaultProfileToRegistry(SettingsManager.Current.Appearance_Theme); + } - #region ICommand & Actions - public ItemActionCallback CloseItemCommand => CloseItemAction; + #region ICommand & Actions + public ItemActionCallback CloseItemCommand => CloseItemAction; - private void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as PuTTYControl)?.CloseTab(); - } + private void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as PuTTYControl)?.CloseTab(); + } - private bool PuTTY_Connected_CanExecute(object view) - { - if (view is PuTTYControl control) - return control.IsConnected; + private bool PuTTY_Connected_CanExecute(object view) + { + if (view is PuTTYControl control) + return control.IsConnected; - return false; - } + return false; + } - public ICommand PuTTY_ReconnectCommand => new RelayCommand(PuTTY_ReconnectAction); + public ICommand PuTTY_ReconnectCommand => new RelayCommand(PuTTY_ReconnectAction); - private void PuTTY_ReconnectAction(object view) + private void PuTTY_ReconnectAction(object view) + { + if (view is PuTTYControl control) { - if (view is PuTTYControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } + } - public ICommand PuTTY_ResizeWindowCommand => new RelayCommand(PuTTY_ResizeWindowAction, PuTTY_Connected_CanExecute); + public ICommand PuTTY_ResizeWindowCommand => new RelayCommand(PuTTY_ResizeWindowAction, PuTTY_Connected_CanExecute); - private void PuTTY_ResizeWindowAction(object view) - { - if (view is PuTTYControl control) - control.ResizeEmbeddedWindow(); - } + private void PuTTY_ResizeWindowAction(object view) + { + if (view is PuTTYControl control) + control.ResizeEmbeddedWindow(); + } - public ICommand PuTTY_RestartSessionCommand => new RelayCommand(PuTTY_RestartSessionAction, PuTTY_Connected_CanExecute); + public ICommand PuTTY_RestartSessionCommand => new RelayCommand(PuTTY_RestartSessionAction, PuTTY_Connected_CanExecute); - private void PuTTY_RestartSessionAction(object view) - { - if (view is PuTTYControl control) - control.RestartSession(); - } + private void PuTTY_RestartSessionAction(object view) + { + if (view is PuTTYControl control) + control.RestartSession(); + } - public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); + public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); - private bool Connect_CanExecute(object obj) - { - return IsConfigured; - } + private bool Connect_CanExecute(object obj) + { + return IsConfigured; + } - private void ConnectAction() - { - Connect(); - } + private void ConnectAction() + { + Connect(); + } - public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); + public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); - private bool ConnectProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool ConnectProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ConnectProfileAction() - { - ConnectProfile(); - } + private void ConnectProfileAction() + { + ConnectProfile(); + } - public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); + public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); - private void ConnectProfileExternalAction() - { - ConnectProfileExternal(); - } + private void ConnectProfileExternalAction() + { + ConnectProfileExternal(); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PuTTY); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.PuTTY); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand TextBoxSearchGotFocusCommand - { - get { return new RelayCommand(p => TextBoxSearchGotFocusAction()); } - } + public ICommand TextBoxSearchGotFocusCommand + { + get { return new RelayCommand(p => TextBoxSearchGotFocusAction()); } + } - private void TextBoxSearchGotFocusAction() - { - TextBoxSearchIsFocused = true; - } + private void TextBoxSearchGotFocusAction() + { + TextBoxSearchIsFocused = true; + } - public ICommand TextBoxSearchLostFocusCommand - { - get { return new RelayCommand(p => TextBoxSearchLostFocusAction()); } - } + public ICommand TextBoxSearchLostFocusCommand + { + get { return new RelayCommand(p => TextBoxSearchLostFocusAction()); } + } - private void TextBoxSearchLostFocusAction() - { - TextBoxSearchIsFocused = false; - } + private void TextBoxSearchLostFocusAction() + { + TextBoxSearchIsFocused = false; + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); + public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); - private static void OpenSettingsAction() - { - EventSystem.RedirectToSettings(); - } - #endregion + private static void OpenSettingsAction() + { + EventSystem.RedirectToSettings(); + } + #endregion - #region Methods - private void CheckSettings() - { - IsConfigured = !string.IsNullOrEmpty(SettingsManager.Current.PuTTY_ApplicationFilePath) && File.Exists(SettingsManager.Current.PuTTY_ApplicationFilePath); + #region Methods + private void CheckSettings() + { + IsConfigured = !string.IsNullOrEmpty(SettingsManager.Current.PuTTY_ApplicationFilePath) && File.Exists(SettingsManager.Current.PuTTY_ApplicationFilePath); - // Create default PuTTY profile for NETworkManager - WriteDefaultProfileToRegistry(); - } + // Create default PuTTY profile for NETworkManager + WriteDefaultProfileToRegistry(); + } + + private async Task Connect(string host = null) + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.Connect + }; - private async Task Connect(string host = null) + var connectViewModel = new PuTTYConnectViewModel(async instance => { - var customDialog = new CustomDialog + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; + + // Create profile info + var info = new PuTTYSessionInfo { - Title = Localization.Resources.Strings.Connect + HostOrSerialLine = instance.ConnectionMode == ConnectionMode.Serial ? instance.SerialLine : instance.Host, + Mode = instance.ConnectionMode, + PortOrBaud = instance.ConnectionMode == ConnectionMode.Serial ? instance.Baud : instance.Port, + Username = instance.Username, + PrivateKey = instance.PrivateKeyFile, + Profile = instance.Profile, + EnableLog = SettingsManager.Current.PuTTY_EnableSessionLog, + LogMode = SettingsManager.Current.PuTTY_LogMode, + LogFileName = SettingsManager.Current.PuTTY_LogFileName, + LogPath = Settings.Application.PuTTY.LogPath, + AdditionalCommandLine = instance.AdditionalCommandLine }; - var connectViewModel = new PuTTYConnectViewModel(async instance => + // Add to history + // Note: The history can only be updated after the values have been read. + // Otherwise, in some cases, incorrect values are taken over. + AddHostToHistory(instance.Host); + AddSerialLineToHistory(instance.SerialLine); + AddPortToHistory(instance.Port); + AddBaudToHistory(instance.Baud); + AddUsernameToHistory(instance.Username); + AddPrivateKeyToHistory(instance.PrivateKeyFile); + AddProfileToHistory(instance.Profile); + + Connect(info); + }, async instance => { await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); ConfigurationManager.Current.IsDialogOpen = false; + }, host); - // Create profile info - var info = new PuTTYSessionInfo - { - HostOrSerialLine = instance.ConnectionMode == ConnectionMode.Serial ? instance.SerialLine : instance.Host, - Mode = instance.ConnectionMode, - PortOrBaud = instance.ConnectionMode == ConnectionMode.Serial ? instance.Baud : instance.Port, - Username = instance.Username, - PrivateKey = instance.PrivateKeyFile, - Profile = instance.Profile, - EnableLog = SettingsManager.Current.PuTTY_EnableSessionLog, - LogMode = SettingsManager.Current.PuTTY_LogMode, - LogFileName = SettingsManager.Current.PuTTY_LogFileName, - LogPath = Settings.Application.PuTTY.LogPath, - AdditionalCommandLine = instance.AdditionalCommandLine - }; - - // Add to history - // Note: The history can only be updated after the values have been read. - // Otherwise, in some cases, incorrect values are taken over. - AddHostToHistory(instance.Host); - AddSerialLineToHistory(instance.SerialLine); - AddPortToHistory(instance.Port); - AddBaudToHistory(instance.Baud); - AddUsernameToHistory(instance.Username); - AddPrivateKeyToHistory(instance.PrivateKeyFile); - AddProfileToHistory(instance.Profile); - - Connect(info); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - }, host); - - customDialog.Content = new PuTTYConnectDialog - { - DataContext = connectViewModel - }; - - ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - - private void ConnectProfile() + customDialog.Content = new PuTTYConnectDialog { - Connect(NETworkManager.Profiles.Application.PuTTY.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); - } + DataContext = connectViewModel + }; - private void ConnectProfileExternal() - { - // Create log path - DirectoryHelper.CreateWithEnvironmentVariables(Settings.Application.PuTTY.LogPath); + ConfigurationManager.Current.IsDialogOpen = true; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - ProcessStartInfo info = new() - { - FileName = SettingsManager.Current.PuTTY_ApplicationFilePath, - Arguments = PuTTY.BuildCommandLine(NETworkManager.Profiles.Application.PuTTY.CreateSessionInfo(SelectedProfile)) - }; + private void ConnectProfile() + { + Connect(NETworkManager.Profiles.Application.PuTTY.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); + } - Process.Start(info); - } + private void ConnectProfileExternal() + { + // Create log path + DirectoryHelper.CreateWithEnvironmentVariables(Settings.Application.PuTTY.LogPath); - private void Connect(PuTTYSessionInfo profileInfo, string header = null) + ProcessStartInfo info = new() { - // Must be added here. So that it works with profiles and the connect dialog. - profileInfo.ApplicationFilePath = SettingsManager.Current.PuTTY_ApplicationFilePath; + FileName = SettingsManager.Current.PuTTY_ApplicationFilePath, + Arguments = PuTTY.BuildCommandLine(NETworkManager.Profiles.Application.PuTTY.CreateSessionInfo(SelectedProfile)) + }; - TabItems.Add(new DragablzTabItem(header ?? profileInfo.HostOrSerialLine, new PuTTYControl(profileInfo))); + Process.Start(info); + } - // Select the added tab - _disableFocusEmbeddedWindow = true; - SelectedTabItem = TabItems.Last(); - _disableFocusEmbeddedWindow = false; - } + private void Connect(PuTTYSessionInfo profileInfo, string header = null) + { + // Must be added here. So that it works with profiles and the connect dialog. + profileInfo.ApplicationFilePath = SettingsManager.Current.PuTTY_ApplicationFilePath; - public void AddTab(string host) - { - Connect(host); - } + TabItems.Add(new DragablzTabItem(header ?? profileInfo.HostOrSerialLine, new PuTTYControl(profileInfo))); - // Modify history list - private static void AddHostToHistory(string host) - { - if (string.IsNullOrEmpty(host)) - return; + // Select the added tab + _disableFocusEmbeddedWindow = true; + SelectedTabItem = TabItems.Last(); + _disableFocusEmbeddedWindow = false; + } - SettingsManager.Current.PuTTY_HostHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); - } + public void AddTab(string host) + { + Connect(host); + } - private static void AddSerialLineToHistory(string serialLine) - { - if (string.IsNullOrEmpty(serialLine)) - return; + // Modify history list + private static void AddHostToHistory(string host) + { + if (string.IsNullOrEmpty(host)) + return; - SettingsManager.Current.PuTTY_SerialLineHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_SerialLineHistory.ToList(), serialLine, SettingsManager.Current.General_HistoryListEntries)); - } + SettingsManager.Current.PuTTY_HostHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); + } - private static void AddPortToHistory(int port) - { - if (port == 0) - return; + private static void AddSerialLineToHistory(string serialLine) + { + if (string.IsNullOrEmpty(serialLine)) + return; - SettingsManager.Current.PuTTY_PortHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_PortHistory.ToList(), port.ToString(), SettingsManager.Current.General_HistoryListEntries)); - } + SettingsManager.Current.PuTTY_SerialLineHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_SerialLineHistory.ToList(), serialLine, SettingsManager.Current.General_HistoryListEntries)); + } - private static void AddBaudToHistory(int baud) - { - if (baud == 0) - return; + private static void AddPortToHistory(int port) + { + if (port == 0) + return; - SettingsManager.Current.PuTTY_BaudHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_BaudHistory.ToList(), baud.ToString(), SettingsManager.Current.General_HistoryListEntries)); - } + SettingsManager.Current.PuTTY_PortHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_PortHistory.ToList(), port.ToString(), SettingsManager.Current.General_HistoryListEntries)); + } - private static void AddUsernameToHistory(string username) - { - if (string.IsNullOrEmpty(username)) - return; + private static void AddBaudToHistory(int baud) + { + if (baud == 0) + return; - SettingsManager.Current.PuTTY_UsernameHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_UsernameHistory.ToList(), username, SettingsManager.Current.General_HistoryListEntries)); - } + SettingsManager.Current.PuTTY_BaudHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_BaudHistory.ToList(), baud.ToString(), SettingsManager.Current.General_HistoryListEntries)); + } - private static void AddPrivateKeyToHistory(string privateKey) - { - if (string.IsNullOrEmpty(privateKey)) - return; + private static void AddUsernameToHistory(string username) + { + if (string.IsNullOrEmpty(username)) + return; - SettingsManager.Current.PuTTY_PrivateKeyFileHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_PrivateKeyFileHistory.ToList(), privateKey, SettingsManager.Current.General_HistoryListEntries)); - } + SettingsManager.Current.PuTTY_UsernameHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_UsernameHistory.ToList(), username, SettingsManager.Current.General_HistoryListEntries)); + } - private static void AddProfileToHistory(string profile) - { - if (string.IsNullOrEmpty(profile)) - return; + private static void AddPrivateKeyToHistory(string privateKey) + { + if (string.IsNullOrEmpty(privateKey)) + return; - SettingsManager.Current.PuTTY_ProfileHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_ProfileHistory.ToList(), profile, SettingsManager.Current.General_HistoryListEntries)); - } + SettingsManager.Current.PuTTY_PrivateKeyFileHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_PrivateKeyFileHistory.ToList(), privateKey, SettingsManager.Current.General_HistoryListEntries)); + } - private void StartDelayedSearch() + private static void AddProfileToHistory(string profile) + { + if (string.IsNullOrEmpty(profile)) + return; + + SettingsManager.Current.PuTTY_ProfileHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.PuTTY_ProfileHistory.ToList(), profile, SettingsManager.Current.General_HistoryListEntries)); + } + + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void FocusEmbeddedWindow() - { - /* Don't continue if - - Search TextBox is focused - - Header ContextMenu is opened - - Profile ContextMenu is opened - */ - if (TextBoxSearchIsFocused || HeaderContextMenuIsOpen || ProfileContextMenuIsOpen) - return; - - (SelectedTabItem?.View as PuTTYControl)?.FocusEmbeddedWindow(); - } + _canProfileWidthChange = true; + } - public void OnViewVisible() - { - _isViewActive = true; + public void FocusEmbeddedWindow() + { + /* Don't continue if + - Search TextBox is focused + - Header ContextMenu is opened + - Profile ContextMenu is opened + */ + if (TextBoxSearchIsFocused || HeaderContextMenuIsOpen || ProfileContextMenuIsOpen) + return; + + (SelectedTabItem?.View as PuTTYControl)?.FocusEmbeddedWindow(); + } - RefreshProfiles(); + public void OnViewVisible() + { + _isViewActive = true; - FocusEmbeddedWindow(); - } + RefreshProfiles(); - public void OnViewHide() - { - _isViewActive = false; - } + FocusEmbeddedWindow(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - ConfigurationManager.Current.IsDialogOpen = true; - } + Profiles.Refresh(); + })); + } - public void OnProfileDialogClose() - { - ConfigurationManager.Current.IsDialogOpen = false; - } - #endregion + public void OnProfileDialogOpen() + { + ConfigurationManager.Current.IsDialogOpen = true; + } - #region Event - private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - if (e.PropertyName == nameof(SettingsInfo.PuTTY_ApplicationFilePath)) - CheckSettings(); + public void OnProfileDialogClose() + { + ConfigurationManager.Current.IsDialogOpen = false; + } + #endregion - // Update PuTTY profile "NETworkManager" if application theme has changed - if (e.PropertyName == nameof(SettingsInfo.Appearance_Theme)) - WriteDefaultProfileToRegistry(); - } + #region Event + private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(SettingsInfo.PuTTY_ApplicationFilePath)) + CheckSettings(); - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + // Update PuTTY profile "NETworkManager" if application theme has changed + if (e.PropertyName == nameof(SettingsInfo.Appearance_Theme)) + WriteDefaultProfileToRegistry(); + } - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/PuTTYSettingsViewModel.cs b/Source/NETworkManager/ViewModels/PuTTYSettingsViewModel.cs index 6e25bbdce6..3ed5d34228 100644 --- a/Source/NETworkManager/ViewModels/PuTTYSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/PuTTYSettingsViewModel.cs @@ -10,511 +10,510 @@ using System.Linq; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class PuTTYSettingsViewModel : ViewModelBase { - public class PuTTYSettingsViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - public bool IsPortable => ConfigurationManager.Current.IsPortable; + public bool IsPortable => ConfigurationManager.Current.IsPortable; - public string PortableLogPath => Settings.Application.PuTTY.PortableLogPath; + public string PortableLogPath => Settings.Application.PuTTY.PortableLogPath; - private readonly bool _isLoading; + private readonly bool _isLoading; - private string _applicationFilePath; - public string ApplicationFilePath + private string _applicationFilePath; + public string ApplicationFilePath + { + get => _applicationFilePath; + set { - get => _applicationFilePath; - set - { - if (value == _applicationFilePath) - return; + if (value == _applicationFilePath) + return; - if (!_isLoading) - SettingsManager.Current.PuTTY_ApplicationFilePath = value; + if (!_isLoading) + SettingsManager.Current.PuTTY_ApplicationFilePath = value; - IsConfigured = !string.IsNullOrEmpty(value); + IsConfigured = !string.IsNullOrEmpty(value); - _applicationFilePath = value; - OnPropertyChanged(); - } + _applicationFilePath = value; + OnPropertyChanged(); } + } - private bool _isConfigured; - public bool IsConfigured + private bool _isConfigured; + public bool IsConfigured + { + get => _isConfigured; + set { - get => _isConfigured; - set - { - if (value == _isConfigured) - return; - - _isConfigured = value; - OnPropertyChanged(); - } + if (value == _isConfigured) + return; + + _isConfigured = value; + OnPropertyChanged(); } + } - private bool _useSSH; - public bool UseSSH + private bool _useSSH; + public bool UseSSH + { + get => _useSSH; + set { - get => _useSSH; - set - { - if (value == _useSSH) - return; - - if (value) - SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.SSH; - - _useSSH = value; - OnPropertyChanged(); - } + if (value == _useSSH) + return; + + if (value) + SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.SSH; + + _useSSH = value; + OnPropertyChanged(); } + } - private bool _useTelnet; - public bool UseTelnet + private bool _useTelnet; + public bool UseTelnet + { + get => _useTelnet; + set { - get => _useTelnet; - set - { - if (value == _useTelnet) - return; - - if (value) - SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.Telnet; - - _useTelnet = value; - OnPropertyChanged(); - } + if (value == _useTelnet) + return; + + if (value) + SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.Telnet; + + _useTelnet = value; + OnPropertyChanged(); } + } - private bool _useSerial; - public bool UseSerial + private bool _useSerial; + public bool UseSerial + { + get => _useSerial; + set { - get => _useSerial; - set - { - if (value == _useSerial) - return; - - if (value) - SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.Serial; - - _useSerial = value; - OnPropertyChanged(); - } + if (value == _useSerial) + return; + + if (value) + SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.Serial; + + _useSerial = value; + OnPropertyChanged(); } + } - private bool _useRlogin; - public bool UseRlogin + private bool _useRlogin; + public bool UseRlogin + { + get => _useRlogin; + set { - get => _useRlogin; - set - { - if (value == _useRlogin) - return; - - if (value) - SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.Rlogin; - - _useRlogin = value; - OnPropertyChanged(); - } + if (value == _useRlogin) + return; + + if (value) + SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.Rlogin; + + _useRlogin = value; + OnPropertyChanged(); } + } - private bool _useRAW; - public bool UseRAW + private bool _useRAW; + public bool UseRAW + { + get => _useRAW; + set { - get => _useRAW; - set - { - if (value == _useRAW) - return; - - if (value) - SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.RAW; - - _useRAW = value; - OnPropertyChanged(); - } + if (value == _useRAW) + return; + + if (value) + SettingsManager.Current.PuTTY_DefaultConnectionMode = ConnectionMode.RAW; + + _useRAW = value; + OnPropertyChanged(); } + } - private string _username; - public string Username + private string _username; + public string Username + { + get => _username; + set { - get => _username; - set - { - if (value == _username) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_Username = value; - - _username = value; - OnPropertyChanged(); - } + if (value == _username) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_Username = value; + + _username = value; + OnPropertyChanged(); } + } - private string _privateKeyFile; - public string PrivateKeyFile + private string _privateKeyFile; + public string PrivateKeyFile + { + get => _privateKeyFile; + set { - get => _privateKeyFile; - set - { - if (value == _privateKeyFile) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_PrivateKeyFile = value; - - _privateKeyFile = value; - OnPropertyChanged(); - } + if (value == _privateKeyFile) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_PrivateKeyFile = value; + + _privateKeyFile = value; + OnPropertyChanged(); } + } - private string _profile; - public string Profile + private string _profile; + public string Profile + { + get => _profile; + set { - get => _profile; - set - { - if (value == _profile) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_Profile = value; - - _profile = value; - OnPropertyChanged(); - } + if (value == _profile) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_Profile = value; + + _profile = value; + OnPropertyChanged(); } + } - private bool _enableLog; - public bool EnableLog + private bool _enableLog; + public bool EnableLog + { + get => _enableLog; + set { - get => _enableLog; - set - { - if (value == _enableLog) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_EnableSessionLog = value; - - _enableLog = value; - OnPropertyChanged(); - } + if (value == _enableLog) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_EnableSessionLog = value; + + _enableLog = value; + OnPropertyChanged(); } + } - public IEnumerable LogModes => Enum.GetValues(typeof(LogMode)).Cast(); + public IEnumerable LogModes => Enum.GetValues(typeof(LogMode)).Cast(); - private LogMode _logMode; - public LogMode LogMode + private LogMode _logMode; + public LogMode LogMode + { + get => _logMode; + set { - get => _logMode; - set - { - if (Equals(value, _logMode)) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_LogMode = value; - - _logMode = value; - OnPropertyChanged(); - } + if (Equals(value, _logMode)) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_LogMode = value; + + _logMode = value; + OnPropertyChanged(); } + } - private string _logPath; - public string LogPath + private string _logPath; + public string LogPath + { + get => _logPath; + set { - get => _logPath; - set - { - if (value == _logPath) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_LogPath = value; - - _logPath = value; - OnPropertyChanged(); - } + if (value == _logPath) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_LogPath = value; + + _logPath = value; + OnPropertyChanged(); } + } - private string _logFileName; - public string LogFileName + private string _logFileName; + public string LogFileName + { + get => _logFileName; + set { - get => _logFileName; - set - { - if (value == _logFileName) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_LogFileName = value; - - _logFileName = value; - OnPropertyChanged(); - } + if (value == _logFileName) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_LogFileName = value; + + _logFileName = value; + OnPropertyChanged(); } + } - private string _additionalCommandLine; - public string AdditionalCommandLine + private string _additionalCommandLine; + public string AdditionalCommandLine + { + get => _additionalCommandLine; + set { - get => _additionalCommandLine; - set - { - if (value == _additionalCommandLine) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_AdditionalCommandLine = value; - - _additionalCommandLine = value; - OnPropertyChanged(); - } + if (value == _additionalCommandLine) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_AdditionalCommandLine = value; + + _additionalCommandLine = value; + OnPropertyChanged(); } + } - private string _serialLine; - public string SerialLine + private string _serialLine; + public string SerialLine + { + get => _serialLine; + set { - get => _serialLine; - set - { - if (value == _serialLine) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_SerialLine = value; - - _serialLine = value; - OnPropertyChanged(); - } + if (value == _serialLine) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_SerialLine = value; + + _serialLine = value; + OnPropertyChanged(); } + } - private int _sshPort; - public int SSHPort + private int _sshPort; + public int SSHPort + { + get => _sshPort; + set { - get => _sshPort; - set - { - if (value == _sshPort) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_SSHPort = value; - - _sshPort = value; - OnPropertyChanged(); - } + if (value == _sshPort) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_SSHPort = value; + + _sshPort = value; + OnPropertyChanged(); } + } - private int _telnetPort; - public int TelnetPort + private int _telnetPort; + public int TelnetPort + { + get => _telnetPort; + set { - get => _telnetPort; - set - { - if (value == _telnetPort) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_TelnetPort = value; - - _telnetPort = value; - OnPropertyChanged(); - } + if (value == _telnetPort) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_TelnetPort = value; + + _telnetPort = value; + OnPropertyChanged(); } + } - private int _baudRate; - public int BaudRate + private int _baudRate; + public int BaudRate + { + get => _baudRate; + set { - get => _baudRate; - set - { - if (value == _baudRate) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_BaudRate = value; - - _baudRate = value; - OnPropertyChanged(); - } + if (value == _baudRate) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_BaudRate = value; + + _baudRate = value; + OnPropertyChanged(); } + } - private int _rloginPort; - public int RloginPort + private int _rloginPort; + public int RloginPort + { + get => _rloginPort; + set { - get => _rloginPort; - set - { - if (value == _rloginPort) - return; - - if (!_isLoading) - SettingsManager.Current.PuTTY_RloginPort = value; - - _rloginPort = value; - OnPropertyChanged(); - } + if (value == _rloginPort) + return; + + if (!_isLoading) + SettingsManager.Current.PuTTY_RloginPort = value; + + _rloginPort = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public PuTTYSettingsViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Contructor, load settings + public PuTTYSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() + private void LoadSettings() + { + ApplicationFilePath = SettingsManager.Current.PuTTY_ApplicationFilePath; + + switch (SettingsManager.Current.PuTTY_DefaultConnectionMode) { - ApplicationFilePath = SettingsManager.Current.PuTTY_ApplicationFilePath; - - switch (SettingsManager.Current.PuTTY_DefaultConnectionMode) - { - case ConnectionMode.SSH: - UseSSH = true; - break; - case ConnectionMode.Telnet: - UseTelnet = true; - break; - case ConnectionMode.Serial: - UseSerial = true; - break; - case ConnectionMode.Rlogin: - UseRlogin = true; - break; - case ConnectionMode.RAW: - UseRAW = true; - break; - } - - IsConfigured = File.Exists(ApplicationFilePath); - Username = SettingsManager.Current.PuTTY_Username; - PrivateKeyFile = SettingsManager.Current.PuTTY_PrivateKeyFile; - Profile = SettingsManager.Current.PuTTY_Profile; - EnableLog = SettingsManager.Current.PuTTY_EnableSessionLog; - LogMode = LogModes.FirstOrDefault(x => x == SettingsManager.Current.PuTTY_LogMode); - LogPath = SettingsManager.Current.PuTTY_LogPath; - LogFileName = SettingsManager.Current.PuTTY_LogFileName; - AdditionalCommandLine = SettingsManager.Current.PuTTY_AdditionalCommandLine; - SerialLine = SettingsManager.Current.PuTTY_SerialLine; - SSHPort = SettingsManager.Current.PuTTY_SSHPort; - TelnetPort = SettingsManager.Current.PuTTY_TelnetPort; - BaudRate = SettingsManager.Current.PuTTY_BaudRate; - RloginPort = SettingsManager.Current.PuTTY_RloginPort; + case ConnectionMode.SSH: + UseSSH = true; + break; + case ConnectionMode.Telnet: + UseTelnet = true; + break; + case ConnectionMode.Serial: + UseSerial = true; + break; + case ConnectionMode.Rlogin: + UseRlogin = true; + break; + case ConnectionMode.RAW: + UseRAW = true; + break; } - #endregion - #region ICommands & Actions - public ICommand ApplicationBrowseFileCommand => new RelayCommand(p => ApplicationBrowseFileAction()); + IsConfigured = File.Exists(ApplicationFilePath); + Username = SettingsManager.Current.PuTTY_Username; + PrivateKeyFile = SettingsManager.Current.PuTTY_PrivateKeyFile; + Profile = SettingsManager.Current.PuTTY_Profile; + EnableLog = SettingsManager.Current.PuTTY_EnableSessionLog; + LogMode = LogModes.FirstOrDefault(x => x == SettingsManager.Current.PuTTY_LogMode); + LogPath = SettingsManager.Current.PuTTY_LogPath; + LogFileName = SettingsManager.Current.PuTTY_LogFileName; + AdditionalCommandLine = SettingsManager.Current.PuTTY_AdditionalCommandLine; + SerialLine = SettingsManager.Current.PuTTY_SerialLine; + SSHPort = SettingsManager.Current.PuTTY_SSHPort; + TelnetPort = SettingsManager.Current.PuTTY_TelnetPort; + BaudRate = SettingsManager.Current.PuTTY_BaudRate; + RloginPort = SettingsManager.Current.PuTTY_RloginPort; + } + #endregion + + #region ICommands & Actions + public ICommand ApplicationBrowseFileCommand => new RelayCommand(p => ApplicationBrowseFileAction()); - private void ApplicationBrowseFileAction() + private void ApplicationBrowseFileAction() + { + var openFileDialog = new System.Windows.Forms.OpenFileDialog { - var openFileDialog = new System.Windows.Forms.OpenFileDialog - { - Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter - }; + Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter + }; - if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - ApplicationFilePath = openFileDialog.FileName; - } + if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + ApplicationFilePath = openFileDialog.FileName; + } - public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); + public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); - private void ConfigureAction() - { - Configure(); - } + private void ConfigureAction() + { + Configure(); + } - public ICommand PrivateKeyFileBrowseFileCommand => new RelayCommand(p => PrivateKeyFileBrowseFileAction()); + public ICommand PrivateKeyFileBrowseFileCommand => new RelayCommand(p => PrivateKeyFileBrowseFileAction()); - private void PrivateKeyFileBrowseFileAction() + private void PrivateKeyFileBrowseFileAction() + { + var openFileDialog = new System.Windows.Forms.OpenFileDialog { - var openFileDialog = new System.Windows.Forms.OpenFileDialog - { - Filter = GlobalStaticConfiguration.PuTTYPrivateKeyFileExtensionFilter - }; + Filter = GlobalStaticConfiguration.PuTTYPrivateKeyFileExtensionFilter + }; - if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - PrivateKeyFile = openFileDialog.FileName; - } + if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + PrivateKeyFile = openFileDialog.FileName; + } - public ICommand LogPathBrowseFolderCommand => new RelayCommand(p => LogPathBrowseFolderAction()); + public ICommand LogPathBrowseFolderCommand => new RelayCommand(p => LogPathBrowseFolderAction()); - private void LogPathBrowseFolderAction() + private void LogPathBrowseFolderAction() + { + var openFolderDialog = new System.Windows.Forms.FolderBrowserDialog { - var openFolderDialog = new System.Windows.Forms.FolderBrowserDialog - { - ShowNewFolderButton = true - }; + ShowNewFolderButton = true + }; - if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - LogPath = openFolderDialog.SelectedPath; - } - #endregion + if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + LogPath = openFolderDialog.SelectedPath; + } + #endregion - #region Methods - private async Task Configure() + #region Methods + private async Task Configure() + { + try { - try - { - Process.Start(SettingsManager.Current.PuTTY_ApplicationFilePath); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); - } + Process.Start(SettingsManager.Current.PuTTY_ApplicationFilePath); } - - /// - /// Method to set the from drag and drop. - /// - /// Path to the file. - public void SetApplicationFilePathFromDragDrop(string filePath) + catch (Exception ex) { - ApplicationFilePath = filePath; + var settings = AppearanceManager.MetroDialog; + + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - OnPropertyChanged(nameof(ApplicationFilePath)); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); } + } - /// - /// Method to set the drag drop. - /// - /// Path to the file. - public void SetPrivateKeyFilePathFromDragDrop(string filePath) - { - PrivateKeyFile = filePath; + /// + /// Method to set the from drag and drop. + /// + /// Path to the file. + public void SetApplicationFilePathFromDragDrop(string filePath) + { + ApplicationFilePath = filePath; - OnPropertyChanged(nameof(PrivateKeyFile)); - } + OnPropertyChanged(nameof(ApplicationFilePath)); + } - /// - /// Method to set the from drag and drop. - /// - /// Path to the folder. - public void SetLogPathFolderPathFromDragDrop(string folderPath) - { - LogPath = folderPath; + /// + /// Method to set the drag drop. + /// + /// Path to the file. + public void SetPrivateKeyFilePathFromDragDrop(string filePath) + { + PrivateKeyFile = filePath; - OnPropertyChanged(nameof(LogPath)); - } - #endregion + OnPropertyChanged(nameof(PrivateKeyFile)); + } + + /// + /// Method to set the from drag and drop. + /// + /// Path to the folder. + public void SetLogPathFolderPathFromDragDrop(string folderPath) + { + LogPath = folderPath; + + OnPropertyChanged(nameof(LogPath)); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/RemoteDesktopConnectViewModel.cs b/Source/NETworkManager/ViewModels/RemoteDesktopConnectViewModel.cs index 77218ecfb0..ea9175d8f3 100644 --- a/Source/NETworkManager/ViewModels/RemoteDesktopConnectViewModel.cs +++ b/Source/NETworkManager/ViewModels/RemoteDesktopConnectViewModel.cs @@ -6,110 +6,109 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class RemoteDesktopConnectViewModel : ViewModelBase { - public class RemoteDesktopConnectViewModel : ViewModelBase - { - public ICommand ConnectCommand { get; } + public ICommand ConnectCommand { get; } - public ICommand CancelCommand { get; } + public ICommand CancelCommand { get; } - private bool _connectAs; - public bool ConnectAs + private bool _connectAs; + public bool ConnectAs + { + get => _connectAs; + set { - get => _connectAs; - set - { - if (value == _connectAs) - return; - - _connectAs = value; - OnPropertyChanged(); - } + if (value == _connectAs) + return; + + _connectAs = value; + OnPropertyChanged(); } + } - private string _name; - public string Name + private string _name; + public string Name + { + get => _name; + set { - get => _name; - set - { - if (value == _name) - return; - - _name = value; - OnPropertyChanged(); - } + if (value == _name) + return; + + _name = value; + OnPropertyChanged(); } + } - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; - - _host = value; - OnPropertyChanged(); - } + if (value == _host) + return; + + _host = value; + OnPropertyChanged(); } + } - public ICollectionView HostHistoryView { get; } + public ICollectionView HostHistoryView { get; } - private bool _useCredentials; - public bool UseCredentials + private bool _useCredentials; + public bool UseCredentials + { + get => _useCredentials; + set { - get => _useCredentials; - set - { - if (value == _useCredentials) - return; - - _useCredentials = value; - OnPropertyChanged(); - } + if (value == _useCredentials) + return; + + _useCredentials = value; + OnPropertyChanged(); } - - private string _username; - public string Username + } + + private string _username; + public string Username + { + get => _username; + set { - get => _username; - set - { - if (value == _username) - return; - - _username = value; - OnPropertyChanged(); - } + if (value == _username) + return; + + _username = value; + OnPropertyChanged(); } + } - private SecureString _password = new SecureString(); - public SecureString Password + private SecureString _password = new SecureString(); + public SecureString Password + { + get => _password; + set { - get => _password; - set - { - if (value == _password) - return; - - _password = value; - OnPropertyChanged(); - } + if (value == _password) + return; + + _password = value; + OnPropertyChanged(); } + } - - public RemoteDesktopConnectViewModel(Action connectCommand, Action cancelHandler, bool connectAs = false) - { - ConnectCommand = new RelayCommand(p => connectCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + + public RemoteDesktopConnectViewModel(Action connectCommand, Action cancelHandler, bool connectAs = false) + { + ConnectCommand = new RelayCommand(p => connectCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - ConnectAs = connectAs; + ConnectAs = connectAs; - if (!ConnectAs) - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.RemoteDesktop_HostHistory); - } + if (!ConnectAs) + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.RemoteDesktop_HostHistory); } } diff --git a/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs b/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs index 04b4b872af..295947cd2a 100644 --- a/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/RemoteDesktopHostViewModel.cs @@ -19,576 +19,575 @@ using System.Threading.Tasks; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class RemoteDesktopHostViewModel : ViewModelBase, IProfileManager { - public class RemoteDesktopHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.RemoteDesktop_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.RemoteDesktop_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public RemoteDesktopHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public RemoteDesktopHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - InterTabClient = new DragablzInterTabClient(ApplicationName.RemoteDesktop); + InterTabClient = new DragablzInterTabClient(ApplicationName.RemoteDesktop); - TabItems = new ObservableCollection(); + TabItems = new ObservableCollection(); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.RemoteDesktop_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.RemoteDesktop_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.RemoteDesktop_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.RemoteDesktop_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, RemoteDesktop_Host - return info.RemoteDesktop_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.RemoteDesktop_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, RemoteDesktop_Host + return info.RemoteDesktop_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.RemoteDesktop_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.RemoteDesktop_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.RemoteDesktop_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.RemoteDesktop_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.RemoteDesktop_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.RemoteDesktop_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.RemoteDesktop_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.RemoteDesktop_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.RemoteDesktop_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ICommand ConnectCommand => new RelayCommand(p => ConnectAction()); + #region ICommand & Actions + public ICommand ConnectCommand => new RelayCommand(p => ConnectAction()); - private void ConnectAction() - { - Connect(); - } + private void ConnectAction() + { + Connect(); + } - private bool RemoteDesktop_Disconnected_CanExecute(object view) - { - if (view is RemoteDesktopControl control) - return !control.IsConnected; + private bool RemoteDesktop_Disconnected_CanExecute(object view) + { + if (view is RemoteDesktopControl control) + return !control.IsConnected; - return false; - } + return false; + } - private bool RemoteDesktop_Connected_CanExecute(object view) - { - if (view is RemoteDesktopControl control) - return control.IsConnected; + private bool RemoteDesktop_Connected_CanExecute(object view) + { + if (view is RemoteDesktopControl control) + return control.IsConnected; - return false; - } + return false; + } - public ICommand RemoteDesktop_ReconnectCommand => new RelayCommand(RemoteDesktop_ReconnectAction, RemoteDesktop_Disconnected_CanExecute); + public ICommand RemoteDesktop_ReconnectCommand => new RelayCommand(RemoteDesktop_ReconnectAction, RemoteDesktop_Disconnected_CanExecute); - private void RemoteDesktop_ReconnectAction(object view) + private void RemoteDesktop_ReconnectAction(object view) + { + if (view is RemoteDesktopControl control) { - if (view is RemoteDesktopControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } + } - public ICommand RemoteDesktop_DisconnectCommand => new RelayCommand(RemoteDesktop_DisconnectAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_DisconnectCommand => new RelayCommand(RemoteDesktop_DisconnectAction, RemoteDesktop_Connected_CanExecute); - private void RemoteDesktop_DisconnectAction(object view) + private void RemoteDesktop_DisconnectAction(object view) + { + if (view is RemoteDesktopControl control) { - if (view is RemoteDesktopControl control) - { - if (control.DisconnectCommand.CanExecute(null)) - control.DisconnectCommand.Execute(null); - } + if (control.DisconnectCommand.CanExecute(null)) + control.DisconnectCommand.Execute(null); } + } - public ICommand RemoteDesktop_FullscreenCommand => new RelayCommand(RemoteDesktop_FullscreenAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_FullscreenCommand => new RelayCommand(RemoteDesktop_FullscreenAction, RemoteDesktop_Connected_CanExecute); - private void RemoteDesktop_FullscreenAction(object view) - { - if (view is RemoteDesktopControl control) - control.FullScreen(); - } + private void RemoteDesktop_FullscreenAction(object view) + { + if (view is RemoteDesktopControl control) + control.FullScreen(); + } - public ICommand RemoteDesktop_AdjustScreenCommand => new RelayCommand(RemoteDesktop_AdjustScreenAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_AdjustScreenCommand => new RelayCommand(RemoteDesktop_AdjustScreenAction, RemoteDesktop_Connected_CanExecute); - private void RemoteDesktop_AdjustScreenAction(object view) - { - if (view is RemoteDesktopControl control) - control.AdjustScreen(); - } + private void RemoteDesktop_AdjustScreenAction(object view) + { + if (view is RemoteDesktopControl control) + control.AdjustScreen(); + } - public ICommand RemoteDesktop_SendCtrlAltDelCommand => new RelayCommand(RemoteDesktop_SendCtrlAltDelAction, RemoteDesktop_Connected_CanExecute); + public ICommand RemoteDesktop_SendCtrlAltDelCommand => new RelayCommand(RemoteDesktop_SendCtrlAltDelAction, RemoteDesktop_Connected_CanExecute); - private async void RemoteDesktop_SendCtrlAltDelAction(object view) + private async void RemoteDesktop_SendCtrlAltDelAction(object view) + { + if (view is RemoteDesktopControl control) { - if (view is RemoteDesktopControl control) + try { - try - { - control.SendKey(Keystroke.CtrlAltDel); - } - catch (Exception ex) - { - ConfigurationManager.Current.IsDialogOpen = true; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, string.Format("{0}\n\nMessage:\n{1}", Localization.Resources.Strings.CouldNotSendKeystroke, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog)); - - ConfigurationManager.Current.IsDialogOpen = false; - } + control.SendKey(Keystroke.CtrlAltDel); } - } + catch (Exception ex) + { + ConfigurationManager.Current.IsDialogOpen = true; - public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, string.Format("{0}\n\nMessage:\n{1}", Localization.Resources.Strings.CouldNotSendKeystroke, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog)); - private bool ConnectProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; + ConfigurationManager.Current.IsDialogOpen = false; + } } + } - private void ConnectProfileAction() - { - ConnectProfile(); - } + public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); - public ICommand ConnectProfileAsCommand => new RelayCommand(p => ConnectProfileAsAction()); + private bool ConnectProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ConnectProfileAsAction() - { - ConnectProfileAs(); - } + private void ConnectProfileAction() + { + ConnectProfile(); + } - public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); + public ICommand ConnectProfileAsCommand => new RelayCommand(p => ConnectProfileAsAction()); - private void ConnectProfileExternalAction() - { - Process.Start("mstsc.exe", $"/V:{SelectedProfile.RemoteDesktop_Host}"); - } + private void ConnectProfileAsAction() + { + ConnectProfileAs(); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.RemoteDesktop); - } + private void ConnectProfileExternalAction() + { + Process.Start("mstsc.exe", $"/V:{SelectedProfile.RemoteDesktop_Host}"); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.RemoteDesktop); + } - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } + + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + + private void ClearSearchAction() + { + Search = string.Empty; + } + + public ItemActionCallback CloseItemCommand => CloseItemAction; - public ItemActionCallback CloseItemCommand => CloseItemAction; + private static void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as RemoteDesktopControl)?.CloseTab(); + } + #endregion - private static void CloseItemAction(ItemActionCallbackArgs args) + #region Methods + // Connect via Dialog + private async Task Connect(string host = null) + { + var customDialog = new CustomDialog { - ((args.DragablzItem.Content as DragablzTabItem)?.View as RemoteDesktopControl)?.CloseTab(); - } - #endregion + Title = Localization.Resources.Strings.Connect + }; - #region Methods - // Connect via Dialog - private async Task Connect(string host = null) + var remoteDesktopConnectViewModel = new RemoteDesktopConnectViewModel(async instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Connect - }; + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - var remoteDesktopConnectViewModel = new RemoteDesktopConnectViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; + // Create new session info with default settings + var sessionInfo = NETworkManager.Profiles.Application.RemoteDesktop.CreateSessionInfo(); - // Create new session info with default settings - var sessionInfo = NETworkManager.Profiles.Application.RemoteDesktop.CreateSessionInfo(); - - if(instance.Host.Contains(':')) - { - // Validate input via UI - sessionInfo.Hostname = instance.Host.Split(':')[0]; - sessionInfo.Port = int.Parse(instance.Host.Split(':')[1]); - } - else - { - sessionInfo.Hostname = instance.Host; - } - - if (instance.UseCredentials) - { - sessionInfo.CustomCredentials = true; - - sessionInfo.Username = instance.Username; - sessionInfo.Password = instance.Password; - } - - // Add to history - // Note: The history can only be updated after the values have been read. - // Otherwise, in some cases, incorrect values are taken over. - AddHostToHistory(instance.Host); - - Connect(sessionInfo); - }, async instance => + if(instance.Host.Contains(':')) { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - }) + // Validate input via UI + sessionInfo.Hostname = instance.Host.Split(':')[0]; + sessionInfo.Port = int.Parse(instance.Host.Split(':')[1]); + } + else { - Host = host - }; + sessionInfo.Hostname = instance.Host; + } - customDialog.Content = new RemoteDesktopConnectDialog + if (instance.UseCredentials) { - DataContext = remoteDesktopConnectViewModel - }; + sessionInfo.CustomCredentials = true; - ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + sessionInfo.Username = instance.Username; + sessionInfo.Password = instance.Password; + } - // Connect via Profile - private void ConnectProfile() + // Add to history + // Note: The history can only be updated after the values have been read. + // Otherwise, in some cases, incorrect values are taken over. + AddHostToHistory(instance.Host); + + Connect(sessionInfo); + }, async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; + }) { - var profileInfo = SelectedProfile; + Host = host + }; - var sessionInfo = NETworkManager.Profiles.Application.RemoteDesktop.CreateSessionInfo(profileInfo); + customDialog.Content = new RemoteDesktopConnectDialog + { + DataContext = remoteDesktopConnectViewModel + }; - Connect(sessionInfo, profileInfo.Name); - } + ConfigurationManager.Current.IsDialogOpen = true; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - // Connect via Profile with Credentials - private async Task ConnectProfileAs() - { - var profileInfo = SelectedProfile; + // Connect via Profile + private void ConnectProfile() + { + var profileInfo = SelectedProfile; - var sessionInfo = NETworkManager.Profiles.Application.RemoteDesktop.CreateSessionInfo(profileInfo); + var sessionInfo = NETworkManager.Profiles.Application.RemoteDesktop.CreateSessionInfo(profileInfo); - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.ConnectAs - }; + Connect(sessionInfo, profileInfo.Name); + } - var remoteDesktopConnectViewModel = new RemoteDesktopConnectViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; + // Connect via Profile with Credentials + private async Task ConnectProfileAs() + { + var profileInfo = SelectedProfile; - if (instance.UseCredentials) - { - sessionInfo.CustomCredentials = true; - sessionInfo.Username = instance.Username; - sessionInfo.Password = instance.Password; - } + var sessionInfo = NETworkManager.Profiles.Application.RemoteDesktop.CreateSessionInfo(profileInfo); - Connect(sessionInfo, instance.Name); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - }, true) - { - // Set name, hostname - Name = profileInfo.Name, - Host = profileInfo.RemoteDesktop_Host, + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.ConnectAs + }; - // Request credentials - UseCredentials = true - }; + var remoteDesktopConnectViewModel = new RemoteDesktopConnectViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - customDialog.Content = new RemoteDesktopConnectDialog + if (instance.UseCredentials) { - DataContext = remoteDesktopConnectViewModel - }; - - ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + sessionInfo.CustomCredentials = true; + sessionInfo.Username = instance.Username; + sessionInfo.Password = instance.Password; + } - private void Connect(RemoteDesktopSessionInfo sessionInfo, string header = null) + Connect(sessionInfo, instance.Name); + }, async instance => { - TabItems.Add(new DragablzTabItem(header ?? sessionInfo.Hostname, new RemoteDesktopControl(sessionInfo))); - SelectedTabIndex = TabItems.Count - 1; - } - - public void AddTab(string host) + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; + }, true) { - Connect(host); - } + // Set name, hostname + Name = profileInfo.Name, + Host = profileInfo.RemoteDesktop_Host, + + // Request credentials + UseCredentials = true + }; - // Modify history list - private static void AddHostToHistory(string host) + customDialog.Content = new RemoteDesktopConnectDialog { - if (string.IsNullOrEmpty(host)) - return; - - SettingsManager.Current.RemoteDesktop_HostHistory = new ObservableCollection( ListHelper.Modify(SettingsManager.Current.RemoteDesktop_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); - } + DataContext = remoteDesktopConnectViewModel + }; + + ConfigurationManager.Current.IsDialogOpen = true; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - private void StartDelayedSearch() + private void Connect(RemoteDesktopSessionInfo sessionInfo, string header = null) + { + TabItems.Add(new DragablzTabItem(header ?? sessionInfo.Hostname, new RemoteDesktopControl(sessionInfo))); + SelectedTabIndex = TabItems.Count - 1; + } + + public void AddTab(string host) + { + Connect(host); + } + + // Modify history list + private static void AddHostToHistory(string host) + { + if (string.IsNullOrEmpty(host)) + return; + + SettingsManager.Current.RemoteDesktop_HostHistory = new ObservableCollection( ListHelper.Modify(SettingsManager.Current.RemoteDesktop_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); + } + + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } - if (dueToChangedSize) + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; + + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void OnViewVisible() - { - _isViewActive = true; + _canProfileWidthChange = true; + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - ConfigurationManager.Current.IsDialogOpen = true; - } + Profiles.Refresh(); + })); + } - public void OnProfileDialogClose() - { - ConfigurationManager.Current.IsDialogOpen = false; - } - #endregion + public void OnProfileDialogOpen() + { + ConfigurationManager.Current.IsDialogOpen = true; + } - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + public void OnProfileDialogClose() + { + ConfigurationManager.Current.IsDialogOpen = false; + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/RemoteDesktopSettingsViewModel.cs b/Source/NETworkManager/ViewModels/RemoteDesktopSettingsViewModel.cs index bb7dc32e46..1bf93b13de 100644 --- a/Source/NETworkManager/ViewModels/RemoteDesktopSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/RemoteDesktopSettingsViewModel.cs @@ -3,611 +3,610 @@ using System.Collections.Generic; using System.Linq; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class RemoteDesktopSettingsViewModel : ViewModelBase { - public class RemoteDesktopSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private bool _adjustScreenAutomatically; - public bool AdjustScreenAutomatically + private bool _adjustScreenAutomatically; + public bool AdjustScreenAutomatically + { + get => _adjustScreenAutomatically; + set { - get => _adjustScreenAutomatically; - set - { - if (value == _adjustScreenAutomatically) - return; + if (value == _adjustScreenAutomatically) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_AdjustScreenAutomatically = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_AdjustScreenAutomatically = value; - _adjustScreenAutomatically = value; - OnPropertyChanged(); - } + _adjustScreenAutomatically = value; + OnPropertyChanged(); } + } - private bool _useCurrentViewSize; - public bool UseCurrentViewSize + private bool _useCurrentViewSize; + public bool UseCurrentViewSize + { + get => _useCurrentViewSize; + set { - get => _useCurrentViewSize; - set - { - if (value == _useCurrentViewSize) - return; + if (value == _useCurrentViewSize) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_UseCurrentViewSize = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_UseCurrentViewSize = value; - _useCurrentViewSize = value; - OnPropertyChanged(); - } + _useCurrentViewSize = value; + OnPropertyChanged(); } + } - private bool _useFixedScreenSize; - public bool UseFixedScreenSize + private bool _useFixedScreenSize; + public bool UseFixedScreenSize + { + get => _useFixedScreenSize; + set { - get => _useFixedScreenSize; - set - { - if (value == _useFixedScreenSize) - return; + if (value == _useFixedScreenSize) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_UseFixedScreenSize = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_UseFixedScreenSize = value; - _useFixedScreenSize = value; - OnPropertyChanged(); - } + _useFixedScreenSize = value; + OnPropertyChanged(); } + } - public List ScreenResolutions => RemoteDesktop.ScreenResolutions; + public List ScreenResolutions => RemoteDesktop.ScreenResolutions; - private string _selectedScreenResolution; - public string SelectedScreenResolution + private string _selectedScreenResolution; + public string SelectedScreenResolution + { + get => _selectedScreenResolution; + set { - get => _selectedScreenResolution; - set - { - if (value == _selectedScreenResolution) - return; - - if (!_isLoading) - { - var resolution = value.Split('x'); + if (value == _selectedScreenResolution) + return; - SettingsManager.Current.RemoteDesktop_ScreenWidth = int.Parse(resolution[0]); - SettingsManager.Current.RemoteDesktop_ScreenHeight = int.Parse(resolution[1]); - } + if (!_isLoading) + { + var resolution = value.Split('x'); - _selectedScreenResolution = value; - OnPropertyChanged(); + SettingsManager.Current.RemoteDesktop_ScreenWidth = int.Parse(resolution[0]); + SettingsManager.Current.RemoteDesktop_ScreenHeight = int.Parse(resolution[1]); } + + _selectedScreenResolution = value; + OnPropertyChanged(); } + } - private bool _useCustomScreenSize; - public bool UseCustomScreenSize + private bool _useCustomScreenSize; + public bool UseCustomScreenSize + { + get => _useCustomScreenSize; + set { - get => _useCustomScreenSize; - set - { - if (value == _useCustomScreenSize) - return; + if (value == _useCustomScreenSize) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_UseCustomScreenSize = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_UseCustomScreenSize = value; - _useCustomScreenSize = value; - OnPropertyChanged(); - } + _useCustomScreenSize = value; + OnPropertyChanged(); } + } - private string _customScreenWidth; - public string CustomScreenWidth + private string _customScreenWidth; + public string CustomScreenWidth + { + get => _customScreenWidth; + set { - get => _customScreenWidth; - set - { - if (value == _customScreenWidth) - return; + if (value == _customScreenWidth) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_CustomScreenWidth = int.Parse(value); + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_CustomScreenWidth = int.Parse(value); - _customScreenWidth = value; - OnPropertyChanged(); - } + _customScreenWidth = value; + OnPropertyChanged(); } + } - private string _customScreenHeight; - public string CustomScreenHeight + private string _customScreenHeight; + public string CustomScreenHeight + { + get => _customScreenHeight; + set { - get => _customScreenHeight; - set - { - if (value == _customScreenHeight) - return; + if (value == _customScreenHeight) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_CustomScreenHeight = int.Parse(value); + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_CustomScreenHeight = int.Parse(value); - _customScreenHeight = value; - OnPropertyChanged(); - } + _customScreenHeight = value; + OnPropertyChanged(); } + } - public List ColorDepths => RemoteDesktop.ColorDepths; + public List ColorDepths => RemoteDesktop.ColorDepths; - private int _selectedColorDepth; - public int SelectedColorDepth + private int _selectedColorDepth; + public int SelectedColorDepth + { + get => _selectedColorDepth; + set { - get => _selectedColorDepth; - set - { - if (value == _selectedColorDepth) - return; + if (value == _selectedColorDepth) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_ColorDepth = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_ColorDepth = value; - _selectedColorDepth = value; - OnPropertyChanged(); - } + _selectedColorDepth = value; + OnPropertyChanged(); } + } - private int _port; - public int Port + private int _port; + public int Port + { + get => _port; + set { - get => _port; - set - { - if (value == _port) - return; + if (value == _port) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_Port = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_Port = value; - _port = value; - OnPropertyChanged(); - } + _port = value; + OnPropertyChanged(); } + } - private bool _enableCredSspSupport; - public bool EnableCredSspSupport + private bool _enableCredSspSupport; + public bool EnableCredSspSupport + { + get => _enableCredSspSupport; + set { - get => _enableCredSspSupport; - set - { - if (value == _enableCredSspSupport) - return; + if (value == _enableCredSspSupport) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_EnableCredSspSupport = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_EnableCredSspSupport = value; - _enableCredSspSupport = value; - OnPropertyChanged(); - } + _enableCredSspSupport = value; + OnPropertyChanged(); } + } - private uint _authenticationLevel; - public uint AuthenticationLevel + private uint _authenticationLevel; + public uint AuthenticationLevel + { + get => _authenticationLevel; + set { - get => _authenticationLevel; - set - { - if (value == _authenticationLevel) - return; + if (value == _authenticationLevel) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_AuthenticationLevel = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_AuthenticationLevel = value; - _authenticationLevel = value; - OnPropertyChanged(); - } + _authenticationLevel = value; + OnPropertyChanged(); } + } - public IEnumerable AudioRedirectionModes => System.Enum.GetValues(typeof(AudioRedirectionMode)).Cast(); + public IEnumerable AudioRedirectionModes => System.Enum.GetValues(typeof(AudioRedirectionMode)).Cast(); - private AudioRedirectionMode _audioRedirectionMode; - public AudioRedirectionMode AudioRedirectionMode + private AudioRedirectionMode _audioRedirectionMode; + public AudioRedirectionMode AudioRedirectionMode + { + get => _audioRedirectionMode; + set { - get => _audioRedirectionMode; - set - { - if (Equals(value, _audioRedirectionMode)) - return; + if (Equals(value, _audioRedirectionMode)) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_AudioRedirectionMode = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_AudioRedirectionMode = value; - _audioRedirectionMode = value; - OnPropertyChanged(); - } + _audioRedirectionMode = value; + OnPropertyChanged(); } + } - public IEnumerable AudioCaptureRedirectionModes => System.Enum.GetValues(typeof(AudioCaptureRedirectionMode)).Cast(); + public IEnumerable AudioCaptureRedirectionModes => System.Enum.GetValues(typeof(AudioCaptureRedirectionMode)).Cast(); - private AudioCaptureRedirectionMode _audioCaptureRedirectionMode; - public AudioCaptureRedirectionMode AudioCaptureRedirectionMode + private AudioCaptureRedirectionMode _audioCaptureRedirectionMode; + public AudioCaptureRedirectionMode AudioCaptureRedirectionMode + { + get => _audioCaptureRedirectionMode; + set { - get => _audioCaptureRedirectionMode; - set - { - if (Equals(value, _audioCaptureRedirectionMode)) - return; + if (Equals(value, _audioCaptureRedirectionMode)) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_AudioCaptureRedirectionMode = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_AudioCaptureRedirectionMode = value; - _audioCaptureRedirectionMode = value; - OnPropertyChanged(); - } + _audioCaptureRedirectionMode = value; + OnPropertyChanged(); } + } - public IEnumerable KeyboardHookModes => System.Enum.GetValues(typeof(KeyboardHookMode)).Cast(); + public IEnumerable KeyboardHookModes => System.Enum.GetValues(typeof(KeyboardHookMode)).Cast(); - private KeyboardHookMode _keyboardHookMode; - public KeyboardHookMode KeyboardHookMode + private KeyboardHookMode _keyboardHookMode; + public KeyboardHookMode KeyboardHookMode + { + get => _keyboardHookMode; + set { - get => _keyboardHookMode; - set - { - if (Equals(value, _keyboardHookMode)) - return; + if (Equals(value, _keyboardHookMode)) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_KeyboardHookMode = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_KeyboardHookMode = value; - _keyboardHookMode = value; - OnPropertyChanged(); - } + _keyboardHookMode = value; + OnPropertyChanged(); } + } - private bool _redirectClipboard; - public bool RedirectClipboard + private bool _redirectClipboard; + public bool RedirectClipboard + { + get => _redirectClipboard; + set { - get => _redirectClipboard; - set - { - if (value == _redirectClipboard) - return; + if (value == _redirectClipboard) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_RedirectClipboard = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_RedirectClipboard = value; - _redirectClipboard = value; - OnPropertyChanged(); - } + _redirectClipboard = value; + OnPropertyChanged(); } + } - private bool _redirectDevices; - public bool RedirectDevices + private bool _redirectDevices; + public bool RedirectDevices + { + get => _redirectDevices; + set { - get => _redirectDevices; - set - { - if (value == _redirectDevices) - return; + if (value == _redirectDevices) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_RedirectDevices = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_RedirectDevices = value; - _redirectDevices = value; - OnPropertyChanged(); - } + _redirectDevices = value; + OnPropertyChanged(); } + } - private bool _redirectDrives; - public bool RedirectDrives + private bool _redirectDrives; + public bool RedirectDrives + { + get => _redirectDrives; + set { - get => _redirectDrives; - set - { - if (value == _redirectDrives) - return; + if (value == _redirectDrives) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_RedirectDrives = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_RedirectDrives = value; - _redirectDrives = value; - OnPropertyChanged(); - } + _redirectDrives = value; + OnPropertyChanged(); } + } - private bool _redirectPorts; - public bool RedirectPorts + private bool _redirectPorts; + public bool RedirectPorts + { + get => _redirectPorts; + set { - get => _redirectPorts; - set - { - if (value == _redirectPorts) - return; + if (value == _redirectPorts) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_RedirectPorts = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_RedirectPorts = value; - _redirectPorts = value; - OnPropertyChanged(); - } + _redirectPorts = value; + OnPropertyChanged(); } + } - private bool _redirectSmartCards; - public bool RedirectSmartCards + private bool _redirectSmartCards; + public bool RedirectSmartCards + { + get => _redirectSmartCards; + set { - get => _redirectSmartCards; - set - { - if (value == _redirectSmartCards) - return; + if (value == _redirectSmartCards) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_RedirectSmartCards = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_RedirectSmartCards = value; - _redirectSmartCards = value; - OnPropertyChanged(); - } + _redirectSmartCards = value; + OnPropertyChanged(); } + } - private bool _redirectPrinters; - public bool RedirectPrinters + private bool _redirectPrinters; + public bool RedirectPrinters + { + get => _redirectPrinters; + set { - get => _redirectPrinters; - set - { - if (value == _redirectPrinters) - return; + if (value == _redirectPrinters) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_RedirectPrinters = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_RedirectPrinters = value; - _redirectPrinters = value; - OnPropertyChanged(); - } + _redirectPrinters = value; + OnPropertyChanged(); } + } - private bool _persistentBitmapCaching; - public bool PersistentBitmapCaching + private bool _persistentBitmapCaching; + public bool PersistentBitmapCaching + { + get => _persistentBitmapCaching; + set { - get => _persistentBitmapCaching; - set - { - if (value == _persistentBitmapCaching) - return; + if (value == _persistentBitmapCaching) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_PersistentBitmapCaching = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_PersistentBitmapCaching = value; - _persistentBitmapCaching = value; - OnPropertyChanged(); - } + _persistentBitmapCaching = value; + OnPropertyChanged(); } + } - private bool _reconnectIfTheConnectionIsDropped; - public bool ReconnectIfTheConnectionIsDropped + private bool _reconnectIfTheConnectionIsDropped; + public bool ReconnectIfTheConnectionIsDropped + { + get => _reconnectIfTheConnectionIsDropped; + set { - get => _reconnectIfTheConnectionIsDropped; - set - { - if (value == _reconnectIfTheConnectionIsDropped) - return; + if (value == _reconnectIfTheConnectionIsDropped) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_ReconnectIfTheConnectionIsDropped = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_ReconnectIfTheConnectionIsDropped = value; - _reconnectIfTheConnectionIsDropped = value; - OnPropertyChanged(); - } + _reconnectIfTheConnectionIsDropped = value; + OnPropertyChanged(); } - public IEnumerable NetworkConnectionTypes => System.Enum.GetValues(typeof(NetworkConnectionType)).Cast(); + } + public IEnumerable NetworkConnectionTypes => System.Enum.GetValues(typeof(NetworkConnectionType)).Cast(); - private NetworkConnectionType _networkConnectionType; - public NetworkConnectionType NetworkConnectionType + private NetworkConnectionType _networkConnectionType; + public NetworkConnectionType NetworkConnectionType + { + get => _networkConnectionType; + set { - get => _networkConnectionType; - set - { - if (Equals(value, _networkConnectionType)) - return; - - if (!_isLoading) - { - ChangeNetworkConnectionTypeSettings(value); - SettingsManager.Current.RemoteDesktop_NetworkConnectionType = value; - } + if (Equals(value, _networkConnectionType)) + return; - _networkConnectionType = value; - OnPropertyChanged(); + if (!_isLoading) + { + ChangeNetworkConnectionTypeSettings(value); + SettingsManager.Current.RemoteDesktop_NetworkConnectionType = value; } + + _networkConnectionType = value; + OnPropertyChanged(); } + } - private bool _desktopBackground; - public bool DesktopBackground + private bool _desktopBackground; + public bool DesktopBackground + { + get => _desktopBackground; + set { - get => _desktopBackground; - set - { - if (value == _desktopBackground) - return; + if (value == _desktopBackground) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_DesktopBackground = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_DesktopBackground = value; - _desktopBackground = value; - OnPropertyChanged(); - } + _desktopBackground = value; + OnPropertyChanged(); } + } - private bool _fontSmoothing; - public bool FontSmoothing + private bool _fontSmoothing; + public bool FontSmoothing + { + get => _fontSmoothing; + set { - get => _fontSmoothing; - set - { - if (value == _fontSmoothing) - return; + if (value == _fontSmoothing) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_FontSmoothing = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_FontSmoothing = value; - _fontSmoothing = value; - OnPropertyChanged(); - } + _fontSmoothing = value; + OnPropertyChanged(); } + } - private bool _desktopComposition; - public bool DesktopComposition + private bool _desktopComposition; + public bool DesktopComposition + { + get => _desktopComposition; + set { - get => _desktopComposition; - set - { - if (value == _desktopComposition) - return; + if (value == _desktopComposition) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_DesktopComposition = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_DesktopComposition = value; - _desktopComposition = value; - OnPropertyChanged(); - } + _desktopComposition = value; + OnPropertyChanged(); } + } - private bool _showWindowContentsWhileDragging; - public bool ShowWindowContentsWhileDragging + private bool _showWindowContentsWhileDragging; + public bool ShowWindowContentsWhileDragging + { + get => _showWindowContentsWhileDragging; + set { - get => _showWindowContentsWhileDragging; - set - { - if (value == _showWindowContentsWhileDragging) - return; + if (value == _showWindowContentsWhileDragging) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_ShowWindowContentsWhileDragging = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_ShowWindowContentsWhileDragging = value; - _showWindowContentsWhileDragging = value; - OnPropertyChanged(); - } + _showWindowContentsWhileDragging = value; + OnPropertyChanged(); } + } - private bool _menuAndWindowAnimation; - public bool MenuAndWindowAnimation + private bool _menuAndWindowAnimation; + public bool MenuAndWindowAnimation + { + get => _menuAndWindowAnimation; + set { - get => _menuAndWindowAnimation; - set - { - if (value == _menuAndWindowAnimation) - return; + if (value == _menuAndWindowAnimation) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_MenuAndWindowAnimation = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_MenuAndWindowAnimation = value; - _menuAndWindowAnimation = value; - OnPropertyChanged(); - } + _menuAndWindowAnimation = value; + OnPropertyChanged(); } + } - private bool _visualStyles; - public bool VisualStyles + private bool _visualStyles; + public bool VisualStyles + { + get => _visualStyles; + set { - get => _visualStyles; - set - { - if (value == _visualStyles) - return; + if (value == _visualStyles) + return; - if (!_isLoading) - SettingsManager.Current.RemoteDesktop_VisualStyles = value; + if (!_isLoading) + SettingsManager.Current.RemoteDesktop_VisualStyles = value; - _visualStyles = value; - OnPropertyChanged(); - } + _visualStyles = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public RemoteDesktopSettingsViewModel() - { - _isLoading = true; + #region Constructor, load settings + public RemoteDesktopSettingsViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - AdjustScreenAutomatically = SettingsManager.Current.RemoteDesktop_AdjustScreenAutomatically; - UseCurrentViewSize = SettingsManager.Current.RemoteDesktop_UseCurrentViewSize; - UseFixedScreenSize = SettingsManager.Current.RemoteDesktop_UseFixedScreenSize; - SelectedScreenResolution = ScreenResolutions.FirstOrDefault(x => x == $"{SettingsManager.Current.RemoteDesktop_ScreenWidth}x{SettingsManager.Current.RemoteDesktop_ScreenHeight}"); - UseCustomScreenSize = SettingsManager.Current.RemoteDesktop_UseCustomScreenSize; - CustomScreenWidth = SettingsManager.Current.RemoteDesktop_CustomScreenWidth.ToString(); - CustomScreenHeight = SettingsManager.Current.RemoteDesktop_CustomScreenHeight.ToString(); - SelectedColorDepth = ColorDepths.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_ColorDepth); - Port = SettingsManager.Current.RemoteDesktop_Port; - EnableCredSspSupport = SettingsManager.Current.RemoteDesktop_EnableCredSspSupport; - AuthenticationLevel = SettingsManager.Current.RemoteDesktop_AuthenticationLevel; - AudioRedirectionMode = AudioRedirectionModes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_AudioRedirectionMode); - AudioCaptureRedirectionMode = AudioCaptureRedirectionModes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_AudioCaptureRedirectionMode); - KeyboardHookMode = KeyboardHookModes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_KeyboardHookMode); - RedirectClipboard = SettingsManager.Current.RemoteDesktop_RedirectClipboard; - RedirectDevices = SettingsManager.Current.RemoteDesktop_RedirectDevices; - RedirectDrives = SettingsManager.Current.RemoteDesktop_RedirectDrives; - RedirectPorts = SettingsManager.Current.RemoteDesktop_RedirectPorts; - RedirectSmartCards = SettingsManager.Current.RemoteDesktop_RedirectSmartCards; - RedirectPrinters = SettingsManager.Current.RemoteDesktop_RedirectPrinters; - PersistentBitmapCaching = SettingsManager.Current.RemoteDesktop_PersistentBitmapCaching; - ReconnectIfTheConnectionIsDropped = SettingsManager.Current.RemoteDesktop_ReconnectIfTheConnectionIsDropped; - NetworkConnectionType = NetworkConnectionTypes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_NetworkConnectionType); - DesktopBackground = SettingsManager.Current.RemoteDesktop_DesktopBackground; - FontSmoothing = SettingsManager.Current.RemoteDesktop_FontSmoothing; - DesktopComposition = SettingsManager.Current.RemoteDesktop_DesktopComposition; - ShowWindowContentsWhileDragging = SettingsManager.Current.RemoteDesktop_ShowWindowContentsWhileDragging; - MenuAndWindowAnimation = SettingsManager.Current.RemoteDesktop_MenuAndWindowAnimation; - VisualStyles = SettingsManager.Current.RemoteDesktop_VisualStyles; - } - #endregion + private void LoadSettings() + { + AdjustScreenAutomatically = SettingsManager.Current.RemoteDesktop_AdjustScreenAutomatically; + UseCurrentViewSize = SettingsManager.Current.RemoteDesktop_UseCurrentViewSize; + UseFixedScreenSize = SettingsManager.Current.RemoteDesktop_UseFixedScreenSize; + SelectedScreenResolution = ScreenResolutions.FirstOrDefault(x => x == $"{SettingsManager.Current.RemoteDesktop_ScreenWidth}x{SettingsManager.Current.RemoteDesktop_ScreenHeight}"); + UseCustomScreenSize = SettingsManager.Current.RemoteDesktop_UseCustomScreenSize; + CustomScreenWidth = SettingsManager.Current.RemoteDesktop_CustomScreenWidth.ToString(); + CustomScreenHeight = SettingsManager.Current.RemoteDesktop_CustomScreenHeight.ToString(); + SelectedColorDepth = ColorDepths.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_ColorDepth); + Port = SettingsManager.Current.RemoteDesktop_Port; + EnableCredSspSupport = SettingsManager.Current.RemoteDesktop_EnableCredSspSupport; + AuthenticationLevel = SettingsManager.Current.RemoteDesktop_AuthenticationLevel; + AudioRedirectionMode = AudioRedirectionModes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_AudioRedirectionMode); + AudioCaptureRedirectionMode = AudioCaptureRedirectionModes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_AudioCaptureRedirectionMode); + KeyboardHookMode = KeyboardHookModes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_KeyboardHookMode); + RedirectClipboard = SettingsManager.Current.RemoteDesktop_RedirectClipboard; + RedirectDevices = SettingsManager.Current.RemoteDesktop_RedirectDevices; + RedirectDrives = SettingsManager.Current.RemoteDesktop_RedirectDrives; + RedirectPorts = SettingsManager.Current.RemoteDesktop_RedirectPorts; + RedirectSmartCards = SettingsManager.Current.RemoteDesktop_RedirectSmartCards; + RedirectPrinters = SettingsManager.Current.RemoteDesktop_RedirectPrinters; + PersistentBitmapCaching = SettingsManager.Current.RemoteDesktop_PersistentBitmapCaching; + ReconnectIfTheConnectionIsDropped = SettingsManager.Current.RemoteDesktop_ReconnectIfTheConnectionIsDropped; + NetworkConnectionType = NetworkConnectionTypes.FirstOrDefault(x => x == SettingsManager.Current.RemoteDesktop_NetworkConnectionType); + DesktopBackground = SettingsManager.Current.RemoteDesktop_DesktopBackground; + FontSmoothing = SettingsManager.Current.RemoteDesktop_FontSmoothing; + DesktopComposition = SettingsManager.Current.RemoteDesktop_DesktopComposition; + ShowWindowContentsWhileDragging = SettingsManager.Current.RemoteDesktop_ShowWindowContentsWhileDragging; + MenuAndWindowAnimation = SettingsManager.Current.RemoteDesktop_MenuAndWindowAnimation; + VisualStyles = SettingsManager.Current.RemoteDesktop_VisualStyles; + } + #endregion - #region Methods - private void ChangeNetworkConnectionTypeSettings(NetworkConnectionType networkConnectionType) - { - switch (networkConnectionType) - { - case NetworkConnectionType.Modem: - DesktopBackground = false; - FontSmoothing = false; - DesktopComposition = false; - ShowWindowContentsWhileDragging = false; - MenuAndWindowAnimation = false; - VisualStyles = false; - break; - case NetworkConnectionType.BroadbandLow: - DesktopBackground = false; - FontSmoothing = false; - DesktopComposition = false; - ShowWindowContentsWhileDragging = false; - MenuAndWindowAnimation = false; - VisualStyles = true; - break; - case NetworkConnectionType.Satellite: - case NetworkConnectionType.BroadbandHigh: - DesktopBackground = false; - FontSmoothing = false; - DesktopComposition = true; - ShowWindowContentsWhileDragging = false; - MenuAndWindowAnimation = false; - VisualStyles = true; - break; - case NetworkConnectionType.WAN: - case NetworkConnectionType.LAN: - DesktopBackground = true; - FontSmoothing = true; - DesktopComposition = true; - ShowWindowContentsWhileDragging = true; - MenuAndWindowAnimation = true; - VisualStyles = true; - break; - } + #region Methods + private void ChangeNetworkConnectionTypeSettings(NetworkConnectionType networkConnectionType) + { + switch (networkConnectionType) + { + case NetworkConnectionType.Modem: + DesktopBackground = false; + FontSmoothing = false; + DesktopComposition = false; + ShowWindowContentsWhileDragging = false; + MenuAndWindowAnimation = false; + VisualStyles = false; + break; + case NetworkConnectionType.BroadbandLow: + DesktopBackground = false; + FontSmoothing = false; + DesktopComposition = false; + ShowWindowContentsWhileDragging = false; + MenuAndWindowAnimation = false; + VisualStyles = true; + break; + case NetworkConnectionType.Satellite: + case NetworkConnectionType.BroadbandHigh: + DesktopBackground = false; + FontSmoothing = false; + DesktopComposition = true; + ShowWindowContentsWhileDragging = false; + MenuAndWindowAnimation = false; + VisualStyles = true; + break; + case NetworkConnectionType.WAN: + case NetworkConnectionType.LAN: + DesktopBackground = true; + FontSmoothing = true; + DesktopComposition = true; + ShowWindowContentsWhileDragging = true; + MenuAndWindowAnimation = true; + VisualStyles = true; + break; } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs b/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs index d00460cad1..a023b0dbfa 100644 --- a/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNMPHostViewModel.cs @@ -6,78 +6,77 @@ using NETworkManager.Utilities; using NETworkManager.Models; -namespace NETworkManager.ViewModels -{ - public class SNMPHostViewModel : ViewModelBase - { - #region Variables - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } +namespace NETworkManager.ViewModels; - private int _tabId; +public class SNMPHostViewModel : ViewModelBase +{ + #region Variables + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private int _selectedTabIndex; - public int SelectedTabIndex - { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; - - _selectedTabIndex = value; - OnPropertyChanged(); - } - } - #endregion + private int _tabId; - #region Constructor - public SNMPHostViewModel() + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - InterTabClient = new DragablzInterTabClient(ApplicationName.SNMP); + if (value == _selectedTabIndex) + return; - TabItems = new ObservableCollection - { - new DragablzTabItem(Localization.Resources.Strings.NewTab, new SNMPView (_tabId), _tabId) - }; + _selectedTabIndex = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region ICommand & Actions - public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); + #region Constructor + public SNMPHostViewModel() + { + InterTabClient = new DragablzInterTabClient(ApplicationName.SNMP); - private void AddTabAction() + TabItems = new ObservableCollection { - AddTab(); - } - - public ItemActionCallback CloseItemCommand => CloseItemAction; + new DragablzTabItem(Localization.Resources.Strings.NewTab, new SNMPView (_tabId), _tabId) + }; + } + #endregion - private static void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as SNMPView)?.CloseTab(); - } - #endregion + #region ICommand & Actions + public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); - #region Methods - public void AddTab(string host = null) - { - _tabId++; + private void AddTabAction() + { + AddTab(); + } + + public ItemActionCallback CloseItemCommand => CloseItemAction; - TabItems.Add(new DragablzTabItem(host ?? Localization.Resources.Strings.NewTab, new SNMPView(_tabId, host), _tabId)); + private static void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as SNMPView)?.CloseTab(); + } + #endregion - SelectedTabIndex = TabItems.Count - 1; - } + #region Methods + public void AddTab(string host = null) + { + _tabId++; - public void OnViewVisible() - { - - } + TabItems.Add(new DragablzTabItem(host ?? Localization.Resources.Strings.NewTab, new SNMPView(_tabId, host), _tabId)); - public void OnViewHide() - { + SelectedTabIndex = TabItems.Count - 1; + } + + public void OnViewVisible() + { + + } + + public void OnViewHide() + { - } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SNMPSettingsViewModel.cs b/Source/NETworkManager/ViewModels/SNMPSettingsViewModel.cs index 55a1ad6b76..94a0b3d767 100644 --- a/Source/NETworkManager/ViewModels/SNMPSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNMPSettingsViewModel.cs @@ -3,84 +3,83 @@ using System.Collections.Generic; using System.Linq; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SNMPSettingsViewModel : ViewModelBase { - public class SNMPSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; - - public List WalkModes { get; set; } + #region Variables + private readonly bool _isLoading; + + public List WalkModes { get; set; } - private WalkMode _walkMode; - public WalkMode WalkMode + private WalkMode _walkMode; + public WalkMode WalkMode + { + get => _walkMode; + set { - get => _walkMode; - set - { - if (value == _walkMode) - return; + if (value == _walkMode) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_WalkMode = value; + if (!_isLoading) + SettingsManager.Current.SNMP_WalkMode = value; - _walkMode = value; - OnPropertyChanged(); - } + _walkMode = value; + OnPropertyChanged(); } + } - private int _timeout; - public int Timeout + private int _timeout; + public int Timeout + { + get => _timeout; + set { - get => _timeout; - set - { - if (value == _timeout) - return; + if (value == _timeout) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_Timeout = value; + if (!_isLoading) + SettingsManager.Current.SNMP_Timeout = value; - _timeout = value; - OnPropertyChanged(); - } + _timeout = value; + OnPropertyChanged(); } + } - private int _port; - public int Port + private int _port; + public int Port + { + get => _port; + set { - get => _port; - set - { - if (value == _port) - return; + if (value == _port) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_Port = value; + if (!_isLoading) + SettingsManager.Current.SNMP_Port = value; - _port = value; - OnPropertyChanged(); - } + _port = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public SNMPSettingsViewModel() - { - _isLoading = true; + #region Contructor, load settings + public SNMPSettingsViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - WalkModes = System.Enum.GetValues(typeof(WalkMode)).Cast().OrderBy(x => x.ToString()).ToList(); - WalkMode = WalkModes.First(x => x == SettingsManager.Current.SNMP_WalkMode); - Timeout = SettingsManager.Current.SNMP_Timeout; - Port = SettingsManager.Current.SNMP_Port; - } - #endregion + private void LoadSettings() + { + WalkModes = System.Enum.GetValues(typeof(WalkMode)).Cast().OrderBy(x => x.ToString()).ToList(); + WalkMode = WalkModes.First(x => x == SettingsManager.Current.SNMP_WalkMode); + Timeout = SettingsManager.Current.SNMP_Timeout; + Port = SettingsManager.Current.SNMP_Port; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SNMPViewModel.cs b/Source/NETworkManager/ViewModels/SNMPViewModel.cs index d82860a39a..4a3e8e6c5d 100644 --- a/Source/NETworkManager/ViewModels/SNMPViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNMPViewModel.cs @@ -22,627 +22,626 @@ using System.Security; using Amazon.EC2.Model; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SNMPViewModel : ViewModelBase { - public class SNMPViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - public readonly int TabId; + public readonly int TabId; - private readonly bool _isLoading; + private readonly bool _isLoading; - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; + if (value == _host) + return; - _host = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } + } - public ICollectionView HostHistoryView { get; } + public ICollectionView HostHistoryView { get; } - public List Versions { get; set; } + public List Versions { get; set; } - private SNMPVersion _version; - public SNMPVersion Version + private SNMPVersion _version; + public SNMPVersion Version + { + get => _version; + set { - get => _version; - set - { - if (value == _version) - return; + if (value == _version) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_Version = value; + if (!_isLoading) + SettingsManager.Current.SNMP_Version = value; - _version = value; - OnPropertyChanged(); - } + _version = value; + OnPropertyChanged(); } + } - public List Modes { get; set; } + public List Modes { get; set; } - private SNMPMode _mode; - public SNMPMode Mode + private SNMPMode _mode; + public SNMPMode Mode + { + get => _mode; + set { - get => _mode; - set - { - if (value == _mode) - return; + if (value == _mode) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_Mode = value; + if (!_isLoading) + SettingsManager.Current.SNMP_Mode = value; - _mode = value; - OnPropertyChanged(); - } + _mode = value; + OnPropertyChanged(); } + } - private string _oid; - public string OID + private string _oid; + public string OID + { + get => _oid; + set { - get => _oid; - set - { - if (value == _oid) - return; + if (value == _oid) + return; - _oid = value; - OnPropertyChanged(); - } + _oid = value; + OnPropertyChanged(); } + } - public ICollectionView OIDHistoryView { get; } + public ICollectionView OIDHistoryView { get; } - public List Securitys { get; set; } + public List Securitys { get; set; } - private SNMPV3Security _security; - public SNMPV3Security Security + private SNMPV3Security _security; + public SNMPV3Security Security + { + get => _security; + set { - get => _security; - set - { - if (value == _security) - return; + if (value == _security) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_Security = value; + if (!_isLoading) + SettingsManager.Current.SNMP_Security = value; - _security = value; - OnPropertyChanged(); - } + _security = value; + OnPropertyChanged(); } + } - private bool _isCommunityEmpty = true; // Initial it's empty - public bool IsCommunityEmpty + private bool _isCommunityEmpty = true; // Initial it's empty + public bool IsCommunityEmpty + { + get => _isCommunityEmpty; + set { - get => _isCommunityEmpty; - set - { - if (value == _isCommunityEmpty) - return; + if (value == _isCommunityEmpty) + return; - _isCommunityEmpty = value; - OnPropertyChanged(); - } + _isCommunityEmpty = value; + OnPropertyChanged(); } + } - private SecureString _community; - public SecureString Community + private SecureString _community; + public SecureString Community + { + get => _community; + set { - get => _community; - set - { - if (value == _community) - return; + if (value == _community) + return; - // Validate the community string - if (value == null) - IsCommunityEmpty = true; - else - IsCommunityEmpty = string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); + // Validate the community string + if (value == null) + IsCommunityEmpty = true; + else + IsCommunityEmpty = string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); - _community = value; - OnPropertyChanged(); - } + _community = value; + OnPropertyChanged(); } + } - private string _username; - public string Username + private string _username; + public string Username + { + get => _username; + set { - get => _username; - set - { - if (value == _username) - return; + if (value == _username) + return; - _username = value; - OnPropertyChanged(); - } + _username = value; + OnPropertyChanged(); } + } - public List AuthenticationProviders { get; set; } + public List AuthenticationProviders { get; set; } - private SNMPV3AuthenticationProvider _authenticationProvider; - public SNMPV3AuthenticationProvider AuthenticationProvider + private SNMPV3AuthenticationProvider _authenticationProvider; + public SNMPV3AuthenticationProvider AuthenticationProvider + { + get => _authenticationProvider; + set { - get => _authenticationProvider; - set - { - if (value == _authenticationProvider) - return; + if (value == _authenticationProvider) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_AuthenticationProvider = value; + if (!_isLoading) + SettingsManager.Current.SNMP_AuthenticationProvider = value; - _authenticationProvider = value; - OnPropertyChanged(); - } + _authenticationProvider = value; + OnPropertyChanged(); } + } - private bool _isAuthEmpty = true; // Initial it's empty - public bool IsAuthEmpty + private bool _isAuthEmpty = true; // Initial it's empty + public bool IsAuthEmpty + { + get => _isAuthEmpty; + set { - get => _isAuthEmpty; - set - { - if (value == _isAuthEmpty) - return; + if (value == _isAuthEmpty) + return; - _isAuthEmpty = value; - OnPropertyChanged(); - } + _isAuthEmpty = value; + OnPropertyChanged(); } + } - private SecureString _auth; - public SecureString Auth + private SecureString _auth; + public SecureString Auth + { + get => _auth; + set { - get => _auth; - set - { - if (value == _auth) - return; + if (value == _auth) + return; - // Validate the auth string - if (value == null) - IsAuthEmpty = true; - else - IsAuthEmpty = string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); + // Validate the auth string + if (value == null) + IsAuthEmpty = true; + else + IsAuthEmpty = string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); - _auth = value; - OnPropertyChanged(); - } + _auth = value; + OnPropertyChanged(); } + } - public List PrivacyProviders { get; set; } + public List PrivacyProviders { get; set; } - private SNMPV3PrivacyProvider _privacyProvider; - public SNMPV3PrivacyProvider PrivacyProvider + private SNMPV3PrivacyProvider _privacyProvider; + public SNMPV3PrivacyProvider PrivacyProvider + { + get => _privacyProvider; + set { - get => _privacyProvider; - set - { - if (value == _privacyProvider) - return; + if (value == _privacyProvider) + return; - if (!_isLoading) - SettingsManager.Current.SNMP_PrivacyProvider = value; + if (!_isLoading) + SettingsManager.Current.SNMP_PrivacyProvider = value; - _privacyProvider = value; - OnPropertyChanged(); - } + _privacyProvider = value; + OnPropertyChanged(); } + } - private bool _isPrivEmpty = true; // Initial it's empty - public bool IsPrivEmpty + private bool _isPrivEmpty = true; // Initial it's empty + public bool IsPrivEmpty + { + get => _isPrivEmpty; + set { - get => _isPrivEmpty; - set - { - if (value == _isPrivEmpty) - return; + if (value == _isPrivEmpty) + return; - _isPrivEmpty = value; - OnPropertyChanged(); - } + _isPrivEmpty = value; + OnPropertyChanged(); } + } - private SecureString _priv; - public SecureString Priv + private SecureString _priv; + public SecureString Priv + { + get => _priv; + set { - get => _priv; - set - { - if (value == _priv) - return; + if (value == _priv) + return; - // Validate the auth string - if (value == null) - IsPrivEmpty = true; - else - IsPrivEmpty = string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); + // Validate the auth string + if (value == null) + IsPrivEmpty = true; + else + IsPrivEmpty = string.IsNullOrEmpty(SecureStringHelper.ConvertToString(value)); - _priv = value; - OnPropertyChanged(); - } + _priv = value; + OnPropertyChanged(); } + } - private string _data = string.Empty; - public string Data + private string _data = string.Empty; + public string Data + { + get => _data; + set { - get => _data; - set - { - if (value == _data) - return; + if (value == _data) + return; - _data = value; - OnPropertyChanged(); - } + _data = value; + OnPropertyChanged(); } + } - private bool _isRunning; - public bool IsRunning + private bool _isRunning; + public bool IsRunning + { + get => _isRunning; + set { - get => _isRunning; - set - { - if (value == _isRunning) - return; + if (value == _isRunning) + return; - _isRunning = value; - OnPropertyChanged(); - } + _isRunning = value; + OnPropertyChanged(); } + } - private ObservableCollection _queryResults = new ObservableCollection(); - public ObservableCollection QueryResults + private ObservableCollection _queryResults = new ObservableCollection(); + public ObservableCollection QueryResults + { + get => _queryResults; + set { - get => _queryResults; - set - { - if (Equals(value, _queryResults)) - return; + if (Equals(value, _queryResults)) + return; - _queryResults = value; - } + _queryResults = value; } + } - public ICollectionView QueryResultsView { get; } + public ICollectionView QueryResultsView { get; } - private SNMPReceivedInfo _selectedQueryResult; - public SNMPReceivedInfo SelectedQueryResult + private SNMPReceivedInfo _selectedQueryResult; + public SNMPReceivedInfo SelectedQueryResult + { + get => _selectedQueryResult; + set { - get => _selectedQueryResult; - set - { - if (value == _selectedQueryResult) - return; + if (value == _selectedQueryResult) + return; - _selectedQueryResult = value; - OnPropertyChanged(); - } + _selectedQueryResult = value; + OnPropertyChanged(); } + } - private IList _selectedQueryResults = new ArrayList(); - public IList SelectedQueryResults + private IList _selectedQueryResults = new ArrayList(); + public IList SelectedQueryResults + { + get => _selectedQueryResults; + set { - get => _selectedQueryResults; - set - { - if (Equals(value, _selectedQueryResults)) - return; + if (Equals(value, _selectedQueryResults)) + return; - _selectedQueryResults = value; - OnPropertyChanged(); - } + _selectedQueryResults = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public SNMPViewModel(IDialogCoordinator instance, int tabId, string host) - { - _isLoading = true; + #region Contructor, load settings + public SNMPViewModel(IDialogCoordinator instance, int tabId, string host) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - TabId = tabId; - Host = host; + TabId = tabId; + Host = host; - // Set collection view - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNMP_HostHistory); - OIDHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNMP_OIDHistory); + // Set collection view + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNMP_HostHistory); + OIDHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNMP_OIDHistory); - // Result view - QueryResultsView = CollectionViewSource.GetDefaultView(QueryResults); - QueryResultsView.SortDescriptions.Add(new SortDescription(nameof(SNMPReceivedInfo.OID), ListSortDirection.Ascending)); + // Result view + QueryResultsView = CollectionViewSource.GetDefaultView(QueryResults); + QueryResultsView.SortDescriptions.Add(new SortDescription(nameof(SNMPReceivedInfo.OID), ListSortDirection.Ascending)); - // Versions (v1, v2c, v3) - Versions = System.Enum.GetValues(typeof(SNMPVersion)).Cast().ToList(); + // Versions (v1, v2c, v3) + Versions = System.Enum.GetValues(typeof(SNMPVersion)).Cast().ToList(); - // Modes - Modes = new List { SNMPMode.Get, SNMPMode.Walk, SNMPMode.Set }; + // Modes + Modes = new List { SNMPMode.Get, SNMPMode.Walk, SNMPMode.Set }; - // Security - Securitys = new List { SNMPV3Security.NoAuthNoPriv, SNMPV3Security.AuthNoPriv, SNMPV3Security.AuthPriv }; + // Security + Securitys = new List { SNMPV3Security.NoAuthNoPriv, SNMPV3Security.AuthNoPriv, SNMPV3Security.AuthPriv }; - // Auth / Priv - AuthenticationProviders = new List { SNMPV3AuthenticationProvider.MD5, SNMPV3AuthenticationProvider.SHA1 }; - PrivacyProviders = new List { SNMPV3PrivacyProvider.DES, SNMPV3PrivacyProvider.AES }; + // Auth / Priv + AuthenticationProviders = new List { SNMPV3AuthenticationProvider.MD5, SNMPV3AuthenticationProvider.SHA1 }; + PrivacyProviders = new List { SNMPV3PrivacyProvider.DES, SNMPV3PrivacyProvider.AES }; - LoadSettings(); + LoadSettings(); - // Detect if settings have changed... - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + // Detect if settings have changed... + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - Version = Versions.FirstOrDefault(x => x == SettingsManager.Current.SNMP_Version); - Mode = Modes.FirstOrDefault(x => x == SettingsManager.Current.SNMP_Mode); - Security = Securitys.FirstOrDefault(x => x == SettingsManager.Current.SNMP_Security); - AuthenticationProvider = AuthenticationProviders.FirstOrDefault(x => x == SettingsManager.Current.SNMP_AuthenticationProvider); - PrivacyProvider = PrivacyProviders.FirstOrDefault(x => x == SettingsManager.Current.SNMP_PrivacyProvider); - } - #endregion + private void LoadSettings() + { + Version = Versions.FirstOrDefault(x => x == SettingsManager.Current.SNMP_Version); + Mode = Modes.FirstOrDefault(x => x == SettingsManager.Current.SNMP_Mode); + Security = Securitys.FirstOrDefault(x => x == SettingsManager.Current.SNMP_Security); + AuthenticationProvider = AuthenticationProviders.FirstOrDefault(x => x == SettingsManager.Current.SNMP_AuthenticationProvider); + PrivacyProvider = PrivacyProviders.FirstOrDefault(x => x == SettingsManager.Current.SNMP_PrivacyProvider); + } + #endregion - #region ICommands & Actions - public ICommand WorkCommand => new RelayCommand(p => WorkAction(), Work_CanExecute); + #region ICommands & Actions + public ICommand WorkCommand => new RelayCommand(p => WorkAction(), Work_CanExecute); - private bool Work_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Work_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void WorkAction() - { - Work(); - } + private void WorkAction() + { + Work(); + } - public ICommand CopySelectedOIDCommand => new RelayCommand(p => CopySelectedOIDAction()); + public ICommand CopySelectedOIDCommand => new RelayCommand(p => CopySelectedOIDAction()); - private void CopySelectedOIDAction() - { - ClipboardHelper.SetClipboard(SelectedQueryResult.OID); - } + private void CopySelectedOIDAction() + { + ClipboardHelper.SetClipboard(SelectedQueryResult.OID); + } - public ICommand CopySelectedDataCommand => new RelayCommand(p => CopySelectedDataAction()); + public ICommand CopySelectedDataCommand => new RelayCommand(p => CopySelectedDataAction()); - private void CopySelectedDataAction() - { - ClipboardHelper.SetClipboard(SelectedQueryResult.Data); - } + private void CopySelectedDataAction() + { + ClipboardHelper.SetClipboard(SelectedQueryResult.Data); + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private async void ExportAction() + private async void ExportAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; - - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? QueryResults : new ObservableCollection(SelectedQueryResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + Title = Localization.Resources.Strings.Export + }; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } - - SettingsManager.Current.SNMP_ExportFileType = instance.FileType; - SettingsManager.Current.SNMP_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.SNMP_ExportFileType, SettingsManager.Current.SNMP_ExportFilePath); + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - customDialog.Content = new ExportDialog + try { - DataContext = exportViewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? QueryResults : new ObservableCollection(SelectedQueryResults.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - #region Methods - private async void Work() - { - IsStatusMessageDisplayed = false; - IsRunning = true; + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - QueryResults.Clear(); + SettingsManager.Current.SNMP_ExportFileType = instance.FileType; + SettingsManager.Current.SNMP_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.SNMP_ExportFileType, SettingsManager.Current.SNMP_ExportFilePath); - // Change the tab title (not nice, but it works) - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - if (window != null) - { - foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) - { - tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Host; - } - } + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - // 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); + #region Methods + private async void Work() + { + IsStatusMessageDisplayed = false; + IsRunning = true; - if (dnsResult.HasError) - { - StatusMessage = DNSClientHelper.FormatDNSClientResultError(Host, dnsResult); - IsStatusMessageDisplayed = true; - IsRunning = false; - return; - } + QueryResults.Clear(); - ipAddress = dnsResult.Value; - } + // Change the tab title (not nice, but it works) + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); - // SNMP... - var snmp = new SNMP + if (window != null) + { + foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) { - Port = SettingsManager.Current.SNMP_Port, - Timeout = SettingsManager.Current.SNMP_Timeout - }; + tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Host; + } + } - snmp.Received += Snmp_Received; - snmp.TimeoutReached += Snmp_TimeoutReached; - snmp.Error += Snmp_Error; - snmp.UserHasCanceled += Snmp_UserHasCanceled; - snmp.Complete += Snmp_Complete; + // 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); - switch (Mode) + if (dnsResult.HasError) { - case SNMPMode.Get: - if (Version != SNMPVersion.V3) - snmp.GetV1V2CAsync(Version, ipAddress, Community, OID); - else - snmp.Getv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv); - break; - case SNMPMode.Walk: - if (Version != SNMPVersion.V3) - snmp.WalkV1V2CAsync(Version, ipAddress, Community, OID, SettingsManager.Current.SNMP_WalkMode); - else - snmp.WalkV3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, SettingsManager.Current.SNMP_WalkMode); - break; - case SNMPMode.Set: - if (Version != SNMPVersion.V3) - snmp.SetV1V2CAsync(Version, ipAddress, Community, OID, Data); - else - snmp.SetV3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, Data); - break; + StatusMessage = DNSClientHelper.FormatDNSClientResultError(Host, dnsResult); + IsStatusMessageDisplayed = true; + IsRunning = false; + return; } - // Add to history... - AddHostToHistory(Host); - AddOIDToHistory(OID); + ipAddress = dnsResult.Value; } - public void OnClose() + // SNMP... + var snmp = new SNMP { + Port = SettingsManager.Current.SNMP_Port, + Timeout = SettingsManager.Current.SNMP_Timeout + }; - } + snmp.Received += Snmp_Received; + snmp.TimeoutReached += Snmp_TimeoutReached; + snmp.Error += Snmp_Error; + snmp.UserHasCanceled += Snmp_UserHasCanceled; + snmp.Complete += Snmp_Complete; - private void AddHostToHistory(string host) + switch (Mode) { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.SNMP_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); + case SNMPMode.Get: + if (Version != SNMPVersion.V3) + snmp.GetV1V2CAsync(Version, ipAddress, Community, OID); + else + snmp.Getv3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv); + break; + case SNMPMode.Walk: + if (Version != SNMPVersion.V3) + snmp.WalkV1V2CAsync(Version, ipAddress, Community, OID, SettingsManager.Current.SNMP_WalkMode); + else + snmp.WalkV3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, SettingsManager.Current.SNMP_WalkMode); + break; + case SNMPMode.Set: + if (Version != SNMPVersion.V3) + snmp.SetV1V2CAsync(Version, ipAddress, Community, OID, Data); + else + snmp.SetV3Async(ipAddress, OID, Security, Username, AuthenticationProvider, Auth, PrivacyProvider, Priv, Data); + break; + } - // Clear the old items - SettingsManager.Current.SNMP_HostHistory.Clear(); - OnPropertyChanged(nameof(Host)); // Raise property changed again, after the collection has been cleared + // Add to history... + AddHostToHistory(Host); + AddOIDToHistory(OID); + } - // Fill with the new items - list.ForEach(x => SettingsManager.Current.SNMP_HostHistory.Add(x)); - } + public void OnClose() + { - 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 + private void AddHostToHistory(string host) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.SNMP_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); - // Fill with the new items - list.ForEach(x => SettingsManager.Current.SNMP_OIDHistory.Add(x)); - } - #endregion + // Clear the old items + SettingsManager.Current.SNMP_HostHistory.Clear(); + OnPropertyChanged(nameof(Host)); // Raise property changed again, after the collection has been cleared - #region Events - private void Snmp_Received(object sender, SNMPReceivedArgs e) - { - var snmpReceivedInfo = SNMPReceivedInfo.Parse(e); + // Fill with the new items + list.ForEach(x => SettingsManager.Current.SNMP_HostHistory.Add(x)); + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - //lock (QueryResults) - QueryResults.Add(snmpReceivedInfo); - })); - } + private void AddOIDToHistory(string oid) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.SNMP_OIDHistory.ToList(), oid, SettingsManager.Current.General_HistoryListEntries); - private void Snmp_TimeoutReached(object sender, EventArgs e) - { - StatusMessage = Localization.Resources.Strings.TimeoutOnSNMPQuery; - IsStatusMessageDisplayed = true; - IsRunning = false; - } + // Clear the old items + SettingsManager.Current.SNMP_OIDHistory.Clear(); + OnPropertyChanged(nameof(OID)); // Raise property changed again, after the collection has been cleared - private void Snmp_Error(object sender, EventArgs e) + // Fill with the new items + list.ForEach(x => SettingsManager.Current.SNMP_OIDHistory.Add(x)); + } + #endregion + + #region Events + private void Snmp_Received(object sender, SNMPReceivedArgs e) + { + var snmpReceivedInfo = SNMPReceivedInfo.Parse(e); + + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - StatusMessage = Mode == SNMPMode.Set ? Localization.Resources.Strings.ErrorInResponseCheckIfYouHaveWritePermissions : Localization.Resources.Strings.ErrorInResponse; - IsStatusMessageDisplayed = true; - IsRunning = false; - } + //lock (QueryResults) + QueryResults.Add(snmpReceivedInfo); + })); + } + + private void Snmp_TimeoutReached(object sender, EventArgs e) + { + StatusMessage = Localization.Resources.Strings.TimeoutOnSNMPQuery; + IsStatusMessageDisplayed = true; + IsRunning = false; + } + + private void Snmp_Error(object sender, EventArgs e) + { + StatusMessage = Mode == SNMPMode.Set ? Localization.Resources.Strings.ErrorInResponseCheckIfYouHaveWritePermissions : Localization.Resources.Strings.ErrorInResponse; + IsStatusMessageDisplayed = true; + IsRunning = false; + } + + private void Snmp_UserHasCanceled(object sender, EventArgs e) + { + StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; + IsStatusMessageDisplayed = true; + IsRunning = false; + } - private void Snmp_UserHasCanceled(object sender, EventArgs e) + private void Snmp_Complete(object sender, EventArgs e) + { + if (Mode == SNMPMode.Set) { - StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; + StatusMessage = Localization.Resources.Strings.DataHasBeenUpdated; IsStatusMessageDisplayed = true; - IsRunning = false; } - private void Snmp_Complete(object sender, EventArgs e) - { - if (Mode == SNMPMode.Set) - { - StatusMessage = Localization.Resources.Strings.DataHasBeenUpdated; - IsStatusMessageDisplayed = true; - } - - IsRunning = false; - } + IsRunning = false; + } - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) - { + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { - } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SNTPLookupHostViewModel.cs b/Source/NETworkManager/ViewModels/SNTPLookupHostViewModel.cs index 0a61520ab4..c22b51f634 100644 --- a/Source/NETworkManager/ViewModels/SNTPLookupHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNTPLookupHostViewModel.cs @@ -16,114 +16,113 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SNTPLookupHostViewModel : ViewModelBase { - public class SNTPLookupHostViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private int _tabId; + private int _tabId; - private int _selectedTabIndex; - public int SelectedTabIndex - { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; - - _selectedTabIndex = value; - OnPropertyChanged(); - } - } - #endregion - - #region Constructor, load settings - public SNTPLookupHostViewModel(IDialogCoordinator instance) + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - _dialogCoordinator = instance; + if (value == _selectedTabIndex) + return; - InterTabClient = new DragablzInterTabClient(ApplicationName.SNTPLookup); + _selectedTabIndex = value; + OnPropertyChanged(); + } + } + #endregion - TabItems = new ObservableCollection - { - new DragablzTabItem(Localization.Resources.Strings.NewTab, new SNTPLookupView (_tabId), _tabId) - }; - - LoadSettings(); + #region Constructor, load settings + public SNTPLookupHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - _isLoading = false; - } + InterTabClient = new DragablzInterTabClient(ApplicationName.SNTPLookup); - private void LoadSettings() + TabItems = new ObservableCollection { - - } - #endregion + new DragablzTabItem(Localization.Resources.Strings.NewTab, new SNTPLookupView (_tabId), _tabId) + }; + + LoadSettings(); - #region ICommand & Actions - public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); + _isLoading = false; + } - private void AddTabAction() - { - AddTab(); - } + private void LoadSettings() + { + + } + #endregion - public ItemActionCallback CloseItemCommand => CloseItemAction; + #region ICommand & Actions + public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); - private static void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as DNSLookupView)?.CloseTab(); - } - #endregion + private void AddTabAction() + { + AddTab(); + } - #region Methods - public void AddTab() - { - _tabId++; + public ItemActionCallback CloseItemCommand => CloseItemAction; + + private static void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as DNSLookupView)?.CloseTab(); + } + #endregion - TabItems.Add(new DragablzTabItem(Localization.Resources.Strings.NewTab, new SNTPLookupView(_tabId), _tabId)); + #region Methods + public void AddTab() + { + _tabId++; - SelectedTabIndex = TabItems.Count - 1; - } + TabItems.Add(new DragablzTabItem(Localization.Resources.Strings.NewTab, new SNTPLookupView(_tabId), _tabId)); - public void OnViewVisible() - { - _isViewActive = true; - } + SelectedTabIndex = TabItems.Count - 1; + } - public void OnViewHide() - { - _isViewActive = false; - } + public void OnViewVisible() + { + _isViewActive = true; + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; - } + public void OnViewHide() + { + _isViewActive = false; + } - public void OnProfileDialogOpen() - { + public void RefreshProfiles() + { + if (!_isViewActive) + return; + } - } + public void OnProfileDialogOpen() + { - public void OnProfileDialogClose() - { + } - } - #endregion + public void OnProfileDialogClose() + { - #region Event - - #endregion } + #endregion + + #region Event + + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SNTPLookupSettingsViewModel.cs b/Source/NETworkManager/ViewModels/SNTPLookupSettingsViewModel.cs index a35a0a2b55..690174185a 100644 --- a/Source/NETworkManager/ViewModels/SNTPLookupSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNTPLookupSettingsViewModel.cs @@ -10,190 +10,189 @@ using NETworkManager.Views; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SNTPLookupSettingsViewModel : ViewModelBase { - public class SNTPLookupSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private readonly IDialogCoordinator _dialogCoordinator; + private readonly IDialogCoordinator _dialogCoordinator; - private (string Server, int Port, TransportProtocol TransportProtocol) _profileDialog_NewItemsOptions = ("time.example.com", 123, TransportProtocol.TCP); + private (string Server, int Port, TransportProtocol TransportProtocol) _profileDialog_NewItemsOptions = ("time.example.com", 123, TransportProtocol.TCP); - private ICollectionView _sntpServers; - public ICollectionView SNTPServers + private ICollectionView _sntpServers; + public ICollectionView SNTPServers + { + get => _sntpServers; + set { - get => _sntpServers; - set - { - if(value == _sntpServers) - return; - - _sntpServers = value; - OnPropertyChanged(); - } + if(value == _sntpServers) + return; + + _sntpServers = value; + OnPropertyChanged(); } + } - private ServerConnectionInfoProfile _selectedSNTPServer = new(); - public ServerConnectionInfoProfile SelectedSNTPServer + private ServerConnectionInfoProfile _selectedSNTPServer = new(); + public ServerConnectionInfoProfile SelectedSNTPServer + { + get => _selectedSNTPServer; + set { - get => _selectedSNTPServer; - set - { - if (value == _selectedSNTPServer) - return; - - _selectedSNTPServer = value; - OnPropertyChanged(); - } + if (value == _selectedSNTPServer) + return; + + _selectedSNTPServer = value; + OnPropertyChanged(); } + } - private List ServerInfoProfileNames => SettingsManager.Current.SNTPLookup_SNTPServers.Select(x => x.Name).ToList(); + private List ServerInfoProfileNames => SettingsManager.Current.SNTPLookup_SNTPServers.Select(x => x.Name).ToList(); - private int _timeout; - public int Timeout - { - get => _timeout; - set - { - if (value == _timeout) - return; - - if (!_isLoading) - SettingsManager.Current.SNTPLookup_Timeout = value; - - _timeout = value; - OnPropertyChanged(); - } - } - #endregion - - #region Constructor, load settings - public SNTPLookupSettingsViewModel(IDialogCoordinator instance) + private int _timeout; + public int Timeout + { + get => _timeout; + set { - _isLoading = true; + if (value == _timeout) + return; - _dialogCoordinator = instance; + if (!_isLoading) + SettingsManager.Current.SNTPLookup_Timeout = value; - SNTPServers = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNTPLookup_SNTPServers); - SNTPServers.SortDescriptions.Add(new SortDescription(nameof(ServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); + _timeout = value; + OnPropertyChanged(); + } + } + #endregion - LoadSettings(); + #region Constructor, load settings + public SNTPLookupSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _isLoading = false; - } + _dialogCoordinator = instance; + + SNTPServers = CollectionViewSource.GetDefaultView(SettingsManager.Current.SNTPLookup_SNTPServers); + SNTPServers.SortDescriptions.Add(new SortDescription(nameof(ServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); + + LoadSettings(); + + _isLoading = false; + } + + private void LoadSettings() + { + Timeout = SettingsManager.Current.SNTPLookup_Timeout; + } + #endregion + + #region ICommand & Actions + public ICommand AddServerCommand => new RelayCommand(p => AddServerAction()); + + private void AddServerAction() + { + AddServer(); + } + + public ICommand EditServerCommand => new RelayCommand(p => EditServerAction()); + + private void EditServerAction() + { + EditServer(); + } - private void LoadSettings() + public ICommand DeleteServerCommand => new RelayCommand(p => DeleteServerAction(), DeleteServer_CanExecute); + + private bool DeleteServer_CanExecute(object obj) + { + return SNTPServers.Cast().Count() > 1; + } + + private void DeleteServerAction() + { + DeleteServer(); + } + #endregion + + #region Methods + public async Task AddServer() + { + var customDialog = new CustomDialog { - Timeout = SettingsManager.Current.SNTPLookup_Timeout; - } - #endregion + Title = Localization.Resources.Strings.AddSNTPServer + }; - #region ICommand & Actions - public ICommand AddServerCommand => new RelayCommand(p => AddServerAction()); + var viewModel = new ServerConnectionInfoProfileViewModel(instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - private void AddServerAction() + SettingsManager.Current.SNTPLookup_SNTPServers.Add(new ServerConnectionInfoProfile(instance.Name, instance.Servers)); + }, instance => { - AddServer(); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, (ServerInfoProfileNames, false, false)); + + customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) + { + DataContext = viewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - public ICommand EditServerCommand => new RelayCommand(p => EditServerAction()); + public async Task EditServer() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.EditSNTPServer + }; - private void EditServerAction() + var viewModel = new ServerConnectionInfoProfileViewModel(instance => { - EditServer(); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - public ICommand DeleteServerCommand => new RelayCommand(p => DeleteServerAction(), DeleteServer_CanExecute); + SettingsManager.Current.SNTPLookup_SNTPServers.Remove(SelectedSNTPServer); + SettingsManager.Current.SNTPLookup_SNTPServers.Add(new ServerConnectionInfoProfile(instance.Name, instance.Servers)); + }, instance => + { + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, (ServerInfoProfileNames, true, false), SelectedSNTPServer); - private bool DeleteServer_CanExecute(object obj) + customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) { - return SNTPServers.Cast().Count() > 1; - } + DataContext = viewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - private void DeleteServerAction() + public async Task DeleteServer() + { + var customDialog = new CustomDialog { - DeleteServer(); - } - #endregion + Title = Localization.Resources.Strings.DeleteSNTPServer + }; - #region Methods - public async Task AddServer() + var viewModel = new ConfirmDeleteViewModel(instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddSNTPServer - }; - - var viewModel = new ServerConnectionInfoProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.SNTPLookup_SNTPServers.Add(new ServerConnectionInfoProfile(instance.Name, instance.Servers)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, (ServerInfoProfileNames, false, false)); - - customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - public async Task EditServer() + SettingsManager.Current.SNTPLookup_SNTPServers.Remove(SelectedSNTPServer); + }, instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.EditSNTPServer - }; - - var viewModel = new ServerConnectionInfoProfileViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.SNTPLookup_SNTPServers.Remove(SelectedSNTPServer); - SettingsManager.Current.SNTPLookup_SNTPServers.Add(new ServerConnectionInfoProfile(instance.Name, instance.Servers)); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, (ServerInfoProfileNames, true, false), SelectedSNTPServer); - - customDialog.Content = new ServerConnectionInfoProfileDialog(_profileDialog_NewItemsOptions) - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, Localization.Resources.Strings.DeleteSNTPServerMessage); - public async Task DeleteServer() + customDialog.Content = new ConfirmDeleteDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.DeleteSNTPServer - }; - - var viewModel = new ConfirmDeleteViewModel(instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - SettingsManager.Current.SNTPLookup_SNTPServers.Remove(SelectedSNTPServer); - }, instance => - { - _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, Localization.Resources.Strings.DeleteSNTPServerMessage); - - customDialog.Content = new ConfirmDeleteDialog - { - DataContext = viewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + DataContext = viewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs index da7c768532..5b9c47231a 100644 --- a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs @@ -18,315 +18,314 @@ using NETworkManager.Models.Export; using NETworkManager.Views; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SNTPLookupViewModel : ViewModelBase { - public class SNTPLookupViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - public readonly int TabId; + public readonly int TabId; - private readonly bool _isLoading; + private readonly bool _isLoading; - public ICollectionView SNTPServers { get; } + public ICollectionView SNTPServers { get; } - private ServerConnectionInfoProfile _sntpServer = new(); - public ServerConnectionInfoProfile SNTPServer + private ServerConnectionInfoProfile _sntpServer = new(); + public ServerConnectionInfoProfile SNTPServer + { + get => _sntpServer; + set { - get => _sntpServer; - set - { - if (value == _sntpServer) - return; + if (value == _sntpServer) + return; - if (!_isLoading) - SettingsManager.Current.SNTPLookup_SelectedSNTPServer = value; + if (!_isLoading) + SettingsManager.Current.SNTPLookup_SelectedSNTPServer = value; - _sntpServer = value; - OnPropertyChanged(); - } + _sntpServer = value; + OnPropertyChanged(); } + } - private bool _isLookupRunning; - public bool IsLookupRunning + private bool _isLookupRunning; + public bool IsLookupRunning + { + get => _isLookupRunning; + set { - get => _isLookupRunning; - set - { - if (value == _isLookupRunning) - return; + if (value == _isLookupRunning) + return; - _isLookupRunning = value; - OnPropertyChanged(); - } + _isLookupRunning = value; + OnPropertyChanged(); } + } - private ObservableCollection _lookupResults = new(); - public ObservableCollection LookupResults + private ObservableCollection _lookupResults = new(); + public ObservableCollection LookupResults + { + get => _lookupResults; + set { - get => _lookupResults; - set - { - if (Equals(value, _lookupResults)) - return; + if (Equals(value, _lookupResults)) + return; - _lookupResults = value; - } + _lookupResults = value; } + } - public ICollectionView LookupResultsView { get; } + public ICollectionView LookupResultsView { get; } - private SNTPLookupResultInfo _selectedLookupResult; - public SNTPLookupResultInfo SelectedLookupResult + private SNTPLookupResultInfo _selectedLookupResult; + public SNTPLookupResultInfo SelectedLookupResult + { + get => _selectedLookupResult; + set { - get => _selectedLookupResult; - set - { - if (value == _selectedLookupResult) - return; + if (value == _selectedLookupResult) + return; - _selectedLookupResult = value; - OnPropertyChanged(); - } + _selectedLookupResult = value; + OnPropertyChanged(); } + } - private IList _selectedLookupResults = new ArrayList(); - public IList SelectedLookupResults + private IList _selectedLookupResults = new ArrayList(); + public IList SelectedLookupResults + { + get => _selectedLookupResults; + set { - get => _selectedLookupResults; - set - { - if (Equals(value, _selectedLookupResults)) - return; + if (Equals(value, _selectedLookupResults)) + return; - _selectedLookupResults = value; - OnPropertyChanged(); - } + _selectedLookupResults = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public SNTPLookupViewModel(IDialogCoordinator instance, int tabId) - { - _isLoading = true; + #region Contructor, load settings + public SNTPLookupViewModel(IDialogCoordinator instance, int tabId) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - TabId = tabId; + TabId = tabId; - SNTPServers = new CollectionViewSource { Source = SettingsManager.Current.SNTPLookup_SNTPServers }.View; - SNTPServers.SortDescriptions.Add(new SortDescription(nameof(ServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); - SNTPServer = SNTPServers.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.SNTPLookup_SelectedSNTPServer.Name) ?? SNTPServers.SourceCollection.Cast().First(); + SNTPServers = new CollectionViewSource { Source = SettingsManager.Current.SNTPLookup_SNTPServers }.View; + SNTPServers.SortDescriptions.Add(new SortDescription(nameof(ServerConnectionInfoProfile.Name), ListSortDirection.Ascending)); + SNTPServer = SNTPServers.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.SNTPLookup_SelectedSNTPServer.Name) ?? SNTPServers.SourceCollection.Cast().First(); - LookupResultsView = CollectionViewSource.GetDefaultView(LookupResults); - LookupResultsView.SortDescriptions.Add(new SortDescription(nameof(SNTPLookupResultInfo.Server), ListSortDirection.Ascending)); + LookupResultsView = CollectionViewSource.GetDefaultView(LookupResults); + LookupResultsView.SortDescriptions.Add(new SortDescription(nameof(SNTPLookupResultInfo.Server), ListSortDirection.Ascending)); - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { + private void LoadSettings() + { - } + } - #endregion + #endregion - #region ICommands & Actions - public ICommand LookupCommand => new RelayCommand(p => LookupAction(), Lookup_CanExecute); + #region ICommands & Actions + public ICommand LookupCommand => new RelayCommand(p => LookupAction(), Lookup_CanExecute); - private bool Lookup_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Lookup_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void LookupAction() - { - if (!IsLookupRunning) - StartLookup(); - } + private void LookupAction() + { + if (!IsLookupRunning) + StartLookup(); + } - public ICommand CopySelectedServerCommand => new RelayCommand(p => CopySelectedServerAction()); + public ICommand CopySelectedServerCommand => new RelayCommand(p => CopySelectedServerAction()); - private void CopySelectedServerAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.Server); - } + private void CopySelectedServerAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.Server); + } - public ICommand CopySelectedIPEndPointCommand => new RelayCommand(p => CopySelectedIPEndPointAction()); + public ICommand CopySelectedIPEndPointCommand => new RelayCommand(p => CopySelectedIPEndPointAction()); - private void CopySelectedIPEndPointAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.IPEndPoint); - } + private void CopySelectedIPEndPointAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.IPEndPoint); + } - public ICommand CopySelectedNetworkTimeCommand => new RelayCommand(p => CopySelectedNetworkTimeAction()); + public ICommand CopySelectedNetworkTimeCommand => new RelayCommand(p => CopySelectedNetworkTimeAction()); - private void CopySelectedNetworkTimeAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff")); - } + private void CopySelectedNetworkTimeAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.NetworkTime.ToString("yyyy.MM.dd HH:mm:ss.fff")); + } - public ICommand CopySelectedLocalStartTimeCommand => new RelayCommand(p => CopySelectedLocalStartTimeAction()); + public ICommand CopySelectedLocalStartTimeCommand => new RelayCommand(p => CopySelectedLocalStartTimeAction()); - private void CopySelectedLocalStartTimeAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff")); - } + private void CopySelectedLocalStartTimeAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.LocalStartTime.ToString("yyyy.MM.dd HH:mm:ss.fff")); + } - public ICommand CopySelectedLocalEndTimeCommand => new RelayCommand(p => CopySelectedLocalEndTimeAction()); + public ICommand CopySelectedLocalEndTimeCommand => new RelayCommand(p => CopySelectedLocalEndTimeAction()); - private void CopySelectedLocalEndTimeAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff")); - } + private void CopySelectedLocalEndTimeAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.LocalEndTime.ToString("yyyy.MM.dd HH:mm:ss.fff")); + } - public ICommand CopySelectedOffsetCommand => new RelayCommand(p => CopySelectedOffsetAction()); + public ICommand CopySelectedOffsetCommand => new RelayCommand(p => CopySelectedOffsetAction()); - private void CopySelectedOffsetAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.Offset.ToString() + " s"); - } + private void CopySelectedOffsetAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.Offset.ToString() + " s"); + } - public ICommand CopySelectedRoundTripDelayCommand => new RelayCommand(p => CopySelectedRoundTripDelayAction()); + public ICommand CopySelectedRoundTripDelayCommand => new RelayCommand(p => CopySelectedRoundTripDelayAction()); - private void CopySelectedRoundTripDelayAction() - { - ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.RoundTripDelay.ToString() + " ms"); - } + private void CopySelectedRoundTripDelayAction() + { + ClipboardHelper.SetClipboard(SelectedLookupResult.DateTime.RoundTripDelay.ToString() + " ms"); + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private async Task ExportAction() + private async Task ExportAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + Title = Localization.Resources.Strings.Export + }; - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? LookupResults : new ObservableCollection(SelectedLookupResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + try + { + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? LookupResults : new ObservableCollection(SelectedLookupResults.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - SettingsManager.Current.SNTPLookup_ExportFileType = instance.FileType; - SettingsManager.Current.SNTPLookup_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.SNTPLookup_ExportFileType, SettingsManager.Current.SNTPLookup_ExportFilePath); + SettingsManager.Current.SNTPLookup_ExportFileType = instance.FileType; + SettingsManager.Current.SNTPLookup_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.SNTPLookup_ExportFileType, SettingsManager.Current.SNTPLookup_ExportFilePath); - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - #region Methods - private void StartLookup() - { - IsStatusMessageDisplayed = false; - StatusMessage = string.Empty; + #region Methods + private void StartLookup() + { + IsStatusMessageDisplayed = false; + StatusMessage = string.Empty; - IsLookupRunning = true; + IsLookupRunning = true; - // Reset the latest results - LookupResults.Clear(); + // Reset the latest results + LookupResults.Clear(); - // Change the tab title (not nice, but it works) - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + // Change the tab title (not nice, but it works) + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); - if (window != null) + if (window != null) + { + foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) { - foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) - { - tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = SNTPServer.Name; - } + tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = SNTPServer.Name; } + } - SNTPLookupSettings settings = new() - { - Timeout = SettingsManager.Current.SNTPLookup_Timeout - }; - - SNTPLookup lookup = new(settings); + SNTPLookupSettings settings = new() + { + Timeout = SettingsManager.Current.SNTPLookup_Timeout + }; - lookup.ResultReceived += Lookup_ResultReceived; - lookup.LookupError += Lookup_LookupError; - lookup.LookupComplete += Lookup_LookupComplete; + SNTPLookup lookup = new(settings); - lookup.QueryAsync(SNTPServer.Servers, SettingsManager.Current.Network_ResolveHostnamePreferIPv4); - } - - public void OnClose() - { + lookup.ResultReceived += Lookup_ResultReceived; + lookup.LookupError += Lookup_LookupError; + lookup.LookupComplete += Lookup_LookupComplete; - } - #endregion + lookup.QueryAsync(SNTPServer.Servers, SettingsManager.Current.Network_ResolveHostnamePreferIPv4); + } + + public void OnClose() + { - #region Events - private void Lookup_ResultReceived(object sender, SNTPLookupResultArgs e) - { - var result = SNTPLookupResultInfo.Parse(e); + } + #endregion - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - LookupResults.Add(result); - })); - } + #region Events + private void Lookup_ResultReceived(object sender, SNTPLookupResultArgs e) + { + var result = SNTPLookupResultInfo.Parse(e); - private void Lookup_LookupError(object sender, SNTPLookupErrorArgs e) + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - if (!string.IsNullOrEmpty(StatusMessage)) - StatusMessage += Environment.NewLine; + LookupResults.Add(result); + })); + } - StatusMessage += e.IsDNSError ? e.ErrorMessage : $"{e.Server} ({e.IPEndPoint}) ==> {e.ErrorMessage}"; - IsStatusMessageDisplayed = true; - } + private void Lookup_LookupError(object sender, SNTPLookupErrorArgs e) + { + if (!string.IsNullOrEmpty(StatusMessage)) + StatusMessage += Environment.NewLine; - private void Lookup_LookupComplete(object sender, EventArgs e) - { - IsLookupRunning = false; - } - #endregion + StatusMessage += e.IsDNSError ? e.ErrorMessage : $"{e.Server} ({e.IPEndPoint}) ==> {e.ErrorMessage}"; + IsStatusMessageDisplayed = true; + } + + private void Lookup_LookupComplete(object sender, EventArgs e) + { + IsLookupRunning = false; } + #endregion } diff --git a/Source/NETworkManager/ViewModels/ServerConnectionInfoProfileViewModel.cs b/Source/NETworkManager/ViewModels/ServerConnectionInfoProfileViewModel.cs index bf9f9fc723..fca96af5f3 100644 --- a/Source/NETworkManager/ViewModels/ServerConnectionInfoProfileViewModel.cs +++ b/Source/NETworkManager/ViewModels/ServerConnectionInfoProfileViewModel.cs @@ -8,128 +8,127 @@ using System.Linq; using System.Diagnostics; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class ServerConnectionInfoProfileViewModel : ViewModelBase { - public class ServerConnectionInfoProfileViewModel : ViewModelBase - { - private readonly bool _isLoading; + private readonly bool _isLoading; - #region Commands - public ICommand SaveCommand { get; } + #region Commands + public ICommand SaveCommand { get; } - public ICommand CancelCommand { get; } - #endregion + public ICommand CancelCommand { get; } + #endregion - #region Variables + #region Variables - #region Helper - private List _usedNames; - public List UsedNames + #region Helper + private List _usedNames; + public List UsedNames + { + get => _usedNames; + set { - get => _usedNames; - set - { - if (value == _usedNames) - return; - - _usedNames = value; - OnPropertyChanged(); - } + if (value == _usedNames) + return; + + _usedNames = value; + OnPropertyChanged(); } + } - private bool _allowOnlyIPAddress; - public bool AllowOnlyIPAddress + private bool _allowOnlyIPAddress; + public bool AllowOnlyIPAddress + { + get => _allowOnlyIPAddress; + set { - get => _allowOnlyIPAddress; - set - { - if (value == _allowOnlyIPAddress) - return; - - _allowOnlyIPAddress = value; - OnPropertyChanged(); - } + if (value == _allowOnlyIPAddress) + return; + + _allowOnlyIPAddress = value; + OnPropertyChanged(); } + } - private bool _isEdited; - public bool IsEdited + private bool _isEdited; + public bool IsEdited + { + get => _isEdited; + set { - get => _isEdited; - set - { - if (value == _isEdited) - return; - - _isEdited = value; - OnPropertyChanged(); - } + if (value == _isEdited) + return; + + _isEdited = value; + OnPropertyChanged(); } + } - private ServerConnectionInfoProfile _currentProfile; - public ServerConnectionInfoProfile CurrentProfile + private ServerConnectionInfoProfile _currentProfile; + public ServerConnectionInfoProfile CurrentProfile + { + get => _currentProfile; + set { - get => _currentProfile; - set - { - if (value == _currentProfile) - return; - - _currentProfile = value; - OnPropertyChanged(); - } + if (value == _currentProfile) + return; + + _currentProfile = value; + OnPropertyChanged(); } - #endregion + } + #endregion - private string _name; - public string Name + private string _name; + public string Name + { + get => _name; + set { - get => _name; - set - { - if (_name == value) - return; + if (_name == value) + return; - _name = value; + _name = value; - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private List _servers; - public List Servers + private List _servers; + public List Servers + { + get => _servers; + set { - get => _servers; - set - { - if (value == _servers) - return; - - _servers = value; - OnPropertyChanged(); - } + if (value == _servers) + return; + + _servers = value; + OnPropertyChanged(); } - #endregion + } + #endregion - public ServerConnectionInfoProfileViewModel(Action saveCommand, Action cancelHandler, (List UsedNames, bool IsEdited, bool allowOnlyIPAddress) options, ServerConnectionInfoProfile info = null) - { - _isLoading = true; + public ServerConnectionInfoProfileViewModel(Action saveCommand, Action cancelHandler, (List UsedNames, bool IsEdited, bool allowOnlyIPAddress) options, ServerConnectionInfoProfile info = null) + { + _isLoading = true; - SaveCommand = new RelayCommand(p => saveCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + SaveCommand = new RelayCommand(p => saveCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - UsedNames = options.UsedNames; - AllowOnlyIPAddress = options.allowOnlyIPAddress; - IsEdited = options.IsEdited; - CurrentProfile = info ?? new ServerConnectionInfoProfile(); + UsedNames = options.UsedNames; + AllowOnlyIPAddress = options.allowOnlyIPAddress; + IsEdited = options.IsEdited; + CurrentProfile = info ?? new ServerConnectionInfoProfile(); - // Remove the current profile name from the list - if (IsEdited) - UsedNames.Remove(CurrentProfile.Name); + // Remove the current profile name from the list + if (IsEdited) + UsedNames.Remove(CurrentProfile.Name); - Name = _currentProfile.Name; - Servers = _currentProfile.Servers; + Name = _currentProfile.Name; + Servers = _currentProfile.Servers; - _isLoading = false; - } + _isLoading = false; } } diff --git a/Source/NETworkManager/ViewModels/SettingsAppearanceViewModel.cs b/Source/NETworkManager/ViewModels/SettingsAppearanceViewModel.cs index ba0ddfc3f4..0ad829995a 100644 --- a/Source/NETworkManager/ViewModels/SettingsAppearanceViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsAppearanceViewModel.cs @@ -3,141 +3,140 @@ using System.Windows.Data; using System.Linq; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsAppearanceViewModel : ViewModelBase { - public class SettingsAppearanceViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - public ICollectionView Themes { get; private set; } + public ICollectionView Themes { get; private set; } - private ThemeColorInfo _selectedTheme; - public ThemeColorInfo SelectedTheme + private ThemeColorInfo _selectedTheme; + public ThemeColorInfo SelectedTheme + { + get => _selectedTheme; + set { - get => _selectedTheme; - set - { - if (value == _selectedTheme) - return; - - if (!_isLoading && !UseCustomTheme) - { - AppearanceManager.ChangeTheme(value.Name); - SettingsManager.Current.Appearance_Theme = value.Name; - } + if (value == _selectedTheme) + return; - _selectedTheme = value; - OnPropertyChanged(); + if (!_isLoading && !UseCustomTheme) + { + AppearanceManager.ChangeTheme(value.Name); + SettingsManager.Current.Appearance_Theme = value.Name; } + + _selectedTheme = value; + OnPropertyChanged(); } + } - public ICollectionView Accents { get; private set; } + public ICollectionView Accents { get; private set; } - private AccentColorInfo _selectedAccent; - public AccentColorInfo SelectedAccent + private AccentColorInfo _selectedAccent; + public AccentColorInfo SelectedAccent + { + get => _selectedAccent; + set { - get => _selectedAccent; - set - { - if (value == _selectedAccent) - return; + if (value == _selectedAccent) + return; - if (!_isLoading && !UseCustomTheme) - { - AppearanceManager.ChangeAccent(value.Name); - SettingsManager.Current.Appearance_Accent = value.Name; - } - - _selectedAccent = value; - OnPropertyChanged(); + if (!_isLoading && !UseCustomTheme) + { + AppearanceManager.ChangeAccent(value.Name); + SettingsManager.Current.Appearance_Accent = value.Name; } + + _selectedAccent = value; + OnPropertyChanged(); } + } - private bool _useCustomTheme; - public bool UseCustomTheme + private bool _useCustomTheme; + public bool UseCustomTheme + { + get => _useCustomTheme; + set { - get => _useCustomTheme; - set - { - if (value == _useCustomTheme) - return; - - if (!_isLoading) - { - SettingsManager.Current.Appearance_UseCustomTheme = value; - AppearanceManager.Load(); - } + if (value == _useCustomTheme) + return; - _useCustomTheme = value; - OnPropertyChanged(); + if (!_isLoading) + { + SettingsManager.Current.Appearance_UseCustomTheme = value; + AppearanceManager.Load(); } + + _useCustomTheme = value; + OnPropertyChanged(); } + } - public ICollectionView CustomThemes { get; private set; } + public ICollectionView CustomThemes { get; private set; } - private ThemeInfo _selectedCustomTheme; - public ThemeInfo SelectedCustomTheme + private ThemeInfo _selectedCustomTheme; + public ThemeInfo SelectedCustomTheme + { + get => _selectedCustomTheme; + set { - get => _selectedCustomTheme; - set - { - if (value == _selectedCustomTheme) - return; + if (value == _selectedCustomTheme) + return; - if (!_isLoading && UseCustomTheme) - { - AppearanceManager.ChangeTheme(value); - SettingsManager.Current.Appearance_CustomThemeName = value.Name; - } - - _selectedCustomTheme = value; - OnPropertyChanged(); + if (!_isLoading && UseCustomTheme) + { + AppearanceManager.ChangeTheme(value); + SettingsManager.Current.Appearance_CustomThemeName = value.Name; } + + _selectedCustomTheme = value; + OnPropertyChanged(); } + } - private bool _powerShellModifyGlobalProfile; - public bool PowerShellModifyGlobalProfile + private bool _powerShellModifyGlobalProfile; + public bool PowerShellModifyGlobalProfile + { + get => _powerShellModifyGlobalProfile; + set { - get => _powerShellModifyGlobalProfile; - set - { - if (value == _powerShellModifyGlobalProfile) - return; + if (value == _powerShellModifyGlobalProfile) + return; - if (!_isLoading) - SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile = value; + if (!_isLoading) + SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile = value; - _powerShellModifyGlobalProfile = value; - OnPropertyChanged(); - } + _powerShellModifyGlobalProfile = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, LoadSettings - public SettingsAppearanceViewModel() - { - _isLoading = true; + #region Constructor, LoadSettings + public SettingsAppearanceViewModel() + { + _isLoading = true; - Themes = new CollectionViewSource { Source = AppearanceManager.Themes }.View; - Accents = new CollectionViewSource { Source = AppearanceManager.Accents }.View; - CustomThemes = new CollectionViewSource { Source = AppearanceManager.CustomThemes }.View; + Themes = new CollectionViewSource { Source = AppearanceManager.Themes }.View; + Accents = new CollectionViewSource { Source = AppearanceManager.Accents }.View; + CustomThemes = new CollectionViewSource { Source = AppearanceManager.CustomThemes }.View; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - SelectedTheme = Themes.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_Theme); - SelectedAccent = Accents.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_Accent); - UseCustomTheme = SettingsManager.Current.Appearance_UseCustomTheme; - SelectedCustomTheme = CustomThemes.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_CustomThemeName) ?? CustomThemes.Cast().FirstOrDefault(); - PowerShellModifyGlobalProfile = SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile; - } - #endregion + private void LoadSettings() + { + SelectedTheme = Themes.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_Theme); + SelectedAccent = Accents.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_Accent); + UseCustomTheme = SettingsManager.Current.Appearance_UseCustomTheme; + SelectedCustomTheme = CustomThemes.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.Appearance_CustomThemeName) ?? CustomThemes.Cast().FirstOrDefault(); + PowerShellModifyGlobalProfile = SettingsManager.Current.Appearance_PowerShellModifyGlobalProfile; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsAutostartViewModel.cs b/Source/NETworkManager/ViewModels/SettingsAutostartViewModel.cs index 2e28935162..6c6f4a61cd 100644 --- a/Source/NETworkManager/ViewModels/SettingsAutostartViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsAutostartViewModel.cs @@ -3,107 +3,106 @@ using System; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsAutostartViewModel : ViewModelBase { - public class SettingsAutostartViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading; + private readonly bool _isLoading; - private bool _startWithWindows; - public bool StartWithWindows + private bool _startWithWindows; + public bool StartWithWindows + { + get => _startWithWindows; + set { - get => _startWithWindows; - set - { - if (value == _startWithWindows) - return; - - if (!_isLoading) - EnableDisableAutostart(value); - - _startWithWindows = value; - OnPropertyChanged(); - } + if (value == _startWithWindows) + return; + + if (!_isLoading) + EnableDisableAutostart(value); + + _startWithWindows = value; + OnPropertyChanged(); } + } - private bool _configuringAutostart; - public bool ConfiguringAutostart + private bool _configuringAutostart; + public bool ConfiguringAutostart + { + get => _configuringAutostart; + set { - get => _configuringAutostart; - set - { - if (value == _configuringAutostart) - return; - - _configuringAutostart = value; - OnPropertyChanged(); - } + if (value == _configuringAutostart) + return; + + _configuringAutostart = value; + OnPropertyChanged(); } + } - private bool _startMinimizedInTray; - public bool StartMinimizedInTray + private bool _startMinimizedInTray; + public bool StartMinimizedInTray + { + get => _startMinimizedInTray; + set { - get => _startMinimizedInTray; - set - { - if (value == _startMinimizedInTray) - return; - - if (!_isLoading) - SettingsManager.Current.Autostart_StartMinimizedInTray = value; - - _startMinimizedInTray = value; - OnPropertyChanged(); - } + if (value == _startMinimizedInTray) + return; + + if (!_isLoading) + SettingsManager.Current.Autostart_StartMinimizedInTray = value; + + _startMinimizedInTray = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor - public SettingsAutostartViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Constructor + public SettingsAutostartViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } - #endregion + _isLoading = false; + } + #endregion + + #region Load settings + private void LoadSettings() + { + StartWithWindows = AutostartManager.IsEnabled; + StartMinimizedInTray = SettingsManager.Current.Autostart_StartMinimizedInTray; + } + #endregion + + #region Methods + private async Task EnableDisableAutostart(bool enable) + { + ConfiguringAutostart = true; - #region Load settings - private void LoadSettings() + try { - StartWithWindows = AutostartManager.IsEnabled; - StartMinimizedInTray = SettingsManager.Current.Autostart_StartMinimizedInTray; - } - #endregion + if (enable) + await AutostartManager.EnableAsync(); + else + await AutostartManager.DisableAsync(); - #region Methods - private async Task EnableDisableAutostart(bool enable) + // Show the user some awesome animation to indicate we are working on it :) + await Task.Delay(2000); + } + catch (Exception ex) { - ConfiguringAutostart = true; - - try - { - if (enable) - await AutostartManager.EnableAsync(); - else - await AutostartManager.DisableAsync(); - - // Show the user some awesome animation to indicate we are working on it :) - await Task.Delay(2000); - } - catch (Exception ex) - { - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); - } - - ConfiguringAutostart = false; + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog); } - #endregion + + ConfiguringAutostart = false; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsGeneralViewModel.cs b/Source/NETworkManager/ViewModels/SettingsGeneralViewModel.cs index 347a08b013..c7fa855f7a 100644 --- a/Source/NETworkManager/ViewModels/SettingsGeneralViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsGeneralViewModel.cs @@ -6,256 +6,255 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsGeneralViewModel : ViewModelBase { - public class SettingsGeneralViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private ApplicationInfo _defaultApplicationSelectedItem; - public ApplicationInfo DefaultApplicationSelectedItem + private ApplicationInfo _defaultApplicationSelectedItem; + public ApplicationInfo DefaultApplicationSelectedItem + { + get => _defaultApplicationSelectedItem; + set { - get => _defaultApplicationSelectedItem; - set - { - if (value == _defaultApplicationSelectedItem) - return; + if (value == _defaultApplicationSelectedItem) + return; - if (value != null && !_isLoading) - SettingsManager.Current.General_DefaultApplicationViewName = value.Name; + if (value != null && !_isLoading) + SettingsManager.Current.General_DefaultApplicationViewName = value.Name; - _defaultApplicationSelectedItem = value; - OnPropertyChanged(); - } + _defaultApplicationSelectedItem = value; + OnPropertyChanged(); } + } - public ICollectionView ApplicationsVisible { get; private set; } + public ICollectionView ApplicationsVisible { get; private set; } - private ApplicationInfo _visibleApplicationSelectedItem; - public ApplicationInfo VisibleApplicationSelectedItem + private ApplicationInfo _visibleApplicationSelectedItem; + public ApplicationInfo VisibleApplicationSelectedItem + { + get => _visibleApplicationSelectedItem; + set { - get => _visibleApplicationSelectedItem; - set - { - if (value == _visibleApplicationSelectedItem) - return; + if (value == _visibleApplicationSelectedItem) + return; - _visibleApplicationSelectedItem = value; + _visibleApplicationSelectedItem = value; - ValidateHideVisibleApplications(); + ValidateHideVisibleApplications(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isVisibleToHideApplicationEnabled; - public bool IsVisibleToHideApplicationEnabled + private bool _isVisibleToHideApplicationEnabled; + public bool IsVisibleToHideApplicationEnabled + { + get => _isVisibleToHideApplicationEnabled; + set { - get => _isVisibleToHideApplicationEnabled; - set - { - if (value == _isVisibleToHideApplicationEnabled) - return; + if (value == _isVisibleToHideApplicationEnabled) + return; - _isVisibleToHideApplicationEnabled = value; - OnPropertyChanged(); - } + _isVisibleToHideApplicationEnabled = value; + OnPropertyChanged(); } + } - public ICollectionView ApplicationsHidden { get; private set; } + public ICollectionView ApplicationsHidden { get; private set; } - private ApplicationInfo _hiddenApplicationSelectedItem; - public ApplicationInfo HiddenApplicationSelectedItem + private ApplicationInfo _hiddenApplicationSelectedItem; + public ApplicationInfo HiddenApplicationSelectedItem + { + get => _hiddenApplicationSelectedItem; + set { - get => _hiddenApplicationSelectedItem; - set - { - if (value == _hiddenApplicationSelectedItem) - return; + if (value == _hiddenApplicationSelectedItem) + return; - _hiddenApplicationSelectedItem = value; + _hiddenApplicationSelectedItem = value; - ValidateHideVisibleApplications(); + ValidateHideVisibleApplications(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isHideToVisibleApplicationEnabled; - public bool IsHideToVisibleApplicationEnabled + private bool _isHideToVisibleApplicationEnabled; + public bool IsHideToVisibleApplicationEnabled + { + get => _isHideToVisibleApplicationEnabled; + set { - get => _isHideToVisibleApplicationEnabled; - set - { - if (value == _isHideToVisibleApplicationEnabled) - return; + if (value == _isHideToVisibleApplicationEnabled) + return; - _isHideToVisibleApplicationEnabled = value; - OnPropertyChanged(); - } + _isHideToVisibleApplicationEnabled = value; + OnPropertyChanged(); } + } - private int _backgroundJobInterval; - public int BackgroundJobInterval + private int _backgroundJobInterval; + public int BackgroundJobInterval + { + get => _backgroundJobInterval; + set { - get => _backgroundJobInterval; - set - { - if (value == _backgroundJobInterval) - return; + if (value == _backgroundJobInterval) + return; - if (!_isLoading) - SettingsManager.Current.General_BackgroundJobInterval = value; + if (!_isLoading) + SettingsManager.Current.General_BackgroundJobInterval = value; - _backgroundJobInterval = value; - OnPropertyChanged(); - } + _backgroundJobInterval = value; + OnPropertyChanged(); } + } - private int _historyListEntries; - public int HistoryListEntries + private int _historyListEntries; + public int HistoryListEntries + { + get => _historyListEntries; + set { - get => _historyListEntries; - set - { - if (value == _historyListEntries) - return; + if (value == _historyListEntries) + return; - if (!_isLoading) - SettingsManager.Current.General_HistoryListEntries = value; + if (!_isLoading) + SettingsManager.Current.General_HistoryListEntries = value; - _historyListEntries = value; - OnPropertyChanged(); - } + _historyListEntries = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, LoadSettings - public SettingsGeneralViewModel() - { - _isLoading = true; + #region Constructor, LoadSettings + public SettingsGeneralViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - SettingsManager.Current.General_ApplicationList.CollectionChanged += General_ApplicationList_CollectionChanged; + SettingsManager.Current.General_ApplicationList.CollectionChanged += General_ApplicationList_CollectionChanged; - _isLoading = false; - } + _isLoading = false; + } - private void General_ApplicationList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) - { - ApplicationsVisible.Refresh(); - ApplicationsHidden.Refresh(); - } + private void General_ApplicationList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) + { + ApplicationsVisible.Refresh(); + ApplicationsHidden.Refresh(); + } - private void LoadSettings() + private void LoadSettings() + { + ApplicationsVisible = new CollectionViewSource { Source = SettingsManager.Current.General_ApplicationList }.View; + ApplicationsVisible.SortDescriptions.Add(new SortDescription(nameof(ApplicationInfo.Name), ListSortDirection.Ascending)); + ApplicationsVisible.Filter = o => { - ApplicationsVisible = new CollectionViewSource { Source = SettingsManager.Current.General_ApplicationList }.View; - ApplicationsVisible.SortDescriptions.Add(new SortDescription(nameof(ApplicationInfo.Name), ListSortDirection.Ascending)); - ApplicationsVisible.Filter = o => - { - if (!(o is ApplicationInfo info)) - return false; + if (!(o is ApplicationInfo info)) + return false; - return info.IsVisible; - }; + return info.IsVisible; + }; - ApplicationsHidden = new CollectionViewSource { Source = SettingsManager.Current.General_ApplicationList }.View; - ApplicationsHidden.SortDescriptions.Add(new SortDescription(nameof(ApplicationInfo.Name), ListSortDirection.Ascending)); - ApplicationsHidden.Filter = o => - { - if (!(o is ApplicationInfo info)) - return false; + ApplicationsHidden = new CollectionViewSource { Source = SettingsManager.Current.General_ApplicationList }.View; + ApplicationsHidden.SortDescriptions.Add(new SortDescription(nameof(ApplicationInfo.Name), ListSortDirection.Ascending)); + ApplicationsHidden.Filter = o => + { + if (!(o is ApplicationInfo info)) + return false; - return !info.IsVisible; - }; + return !info.IsVisible; + }; - ValidateHideVisibleApplications(); + ValidateHideVisibleApplications(); - DefaultApplicationSelectedItem = ApplicationsVisible.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.General_DefaultApplicationViewName); - BackgroundJobInterval = SettingsManager.Current.General_BackgroundJobInterval; - HistoryListEntries = SettingsManager.Current.General_HistoryListEntries; - } - #endregion + DefaultApplicationSelectedItem = ApplicationsVisible.Cast().FirstOrDefault(x => x.Name == SettingsManager.Current.General_DefaultApplicationViewName); + BackgroundJobInterval = SettingsManager.Current.General_BackgroundJobInterval; + HistoryListEntries = SettingsManager.Current.General_HistoryListEntries; + } + #endregion - #region ICommands & Actions - public ICommand VisibleToHideApplicationCommand - { - get { return new RelayCommand(p => VisibleToHideApplicationAction()); } - } + #region ICommands & Actions + public ICommand VisibleToHideApplicationCommand + { + get { return new RelayCommand(p => VisibleToHideApplicationAction()); } + } + + private void VisibleToHideApplicationAction() + { + /* + var index = 0; - private void VisibleToHideApplicationAction() + for (var i = 0; i < SettingsManager.Current.General_ApplicationList.Count; i++) { - /* - var index = 0; + if (SettingsManager.Current.General_ApplicationList[i].Name != VisibleApplicationSelectedItem.Name) + continue; - for (var i = 0; i < SettingsManager.Current.General_ApplicationList.Count; i++) - { - if (SettingsManager.Current.General_ApplicationList[i].Name != VisibleApplicationSelectedItem.Name) - continue; + index = i; - index = i; + break; + } + */ - break; - } - */ + var newDefaultApplication = DefaultApplicationSelectedItem.Name == VisibleApplicationSelectedItem.Name; - var newDefaultApplication = DefaultApplicationSelectedItem.Name == VisibleApplicationSelectedItem.Name; + // Remove and add will fire a collection changed event --> detected in MainWindow + var info = SettingsManager.Current.General_ApplicationList.First(x => VisibleApplicationSelectedItem.Name.Equals(x.Name)); - // Remove and add will fire a collection changed event --> detected in MainWindow - var info = SettingsManager.Current.General_ApplicationList.First(x => VisibleApplicationSelectedItem.Name.Equals(x.Name)); + info.IsVisible = false; - info.IsVisible = false; + SettingsManager.Current.General_ApplicationList.Remove(info); + SettingsManager.Current.General_ApplicationList.Add(info); - SettingsManager.Current.General_ApplicationList.Remove(info); - SettingsManager.Current.General_ApplicationList.Add(info); + if (newDefaultApplication) + DefaultApplicationSelectedItem = ApplicationsVisible.Cast().FirstOrDefault(); - if (newDefaultApplication) - DefaultApplicationSelectedItem = ApplicationsVisible.Cast().FirstOrDefault(); + ValidateHideVisibleApplications(); + } - ValidateHideVisibleApplications(); - } + public ICommand HideToVisibleApplicationCommand + { + get { return new RelayCommand(p => HideToVisibleApplicationAction()); } + } - public ICommand HideToVisibleApplicationCommand - { - get { return new RelayCommand(p => HideToVisibleApplicationAction()); } - } + private void HideToVisibleApplicationAction() + { + /* + var index = 0; - private void HideToVisibleApplicationAction() + for (var i = 0; i < SettingsManager.Current.General_ApplicationList.Count; i++) { - /* - var index = 0; - - for (var i = 0; i < SettingsManager.Current.General_ApplicationList.Count; i++) + if (SettingsManager.Current.General_ApplicationList[i].Name == HiddenApplicationSelectedItem.Name) { - if (SettingsManager.Current.General_ApplicationList[i].Name == HiddenApplicationSelectedItem.Name) - { - index = i; - break; - } + index = i; + break; } - */ + } + */ - // Remove and add will fire a collection changed event --> detected in MainWindow - var info = SettingsManager.Current.General_ApplicationList.First(x => HiddenApplicationSelectedItem.Name.Equals(x.Name)); + // Remove and add will fire a collection changed event --> detected in MainWindow + var info = SettingsManager.Current.General_ApplicationList.First(x => HiddenApplicationSelectedItem.Name.Equals(x.Name)); - info.IsVisible = true; + info.IsVisible = true; - SettingsManager.Current.General_ApplicationList.Remove(info); - SettingsManager.Current.General_ApplicationList.Add(info); + SettingsManager.Current.General_ApplicationList.Remove(info); + SettingsManager.Current.General_ApplicationList.Add(info); - ValidateHideVisibleApplications(); - } - #endregion + ValidateHideVisibleApplications(); + } + #endregion - #region Methods + #region Methods - private void ValidateHideVisibleApplications() - { - IsVisibleToHideApplicationEnabled = ApplicationsVisible.Cast().Count() > 1 && VisibleApplicationSelectedItem != null; - IsHideToVisibleApplicationEnabled = ApplicationsHidden.Cast().Any() && HiddenApplicationSelectedItem != null; - } - #endregion + private void ValidateHideVisibleApplications() + { + IsVisibleToHideApplicationEnabled = ApplicationsVisible.Cast().Count() > 1 && VisibleApplicationSelectedItem != null; + IsHideToVisibleApplicationEnabled = ApplicationsHidden.Cast().Any() && HiddenApplicationSelectedItem != null; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsHotKeysViewModel.cs b/Source/NETworkManager/ViewModels/SettingsHotKeysViewModel.cs index 711787f627..caee2b082e 100644 --- a/Source/NETworkManager/ViewModels/SettingsHotKeysViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsHotKeysViewModel.cs @@ -2,72 +2,71 @@ using MahApps.Metro.Controls; using NETworkManager.Utilities; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsHotKeysViewModel : ViewModelBase { - public class SettingsHotKeysViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private bool _hotKeyShowWindowEnabled; - public bool HotKeyShowWindowEnabled + private bool _hotKeyShowWindowEnabled; + public bool HotKeyShowWindowEnabled + { + get => _hotKeyShowWindowEnabled; + set { - get => _hotKeyShowWindowEnabled; - set - { - if (value == _hotKeyShowWindowEnabled) - return; - - if (!_isLoading) - { - SettingsManager.Current.HotKey_ShowWindowEnabled = value; + if (value == _hotKeyShowWindowEnabled) + return; - SettingsManager.HotKeysChanged = true; - } + if (!_isLoading) + { + SettingsManager.Current.HotKey_ShowWindowEnabled = value; - _hotKeyShowWindowEnabled = value; - OnPropertyChanged(); + SettingsManager.HotKeysChanged = true; } + + _hotKeyShowWindowEnabled = value; + OnPropertyChanged(); } + } - private HotKey _hotKeyShowWindow; - public HotKey HotKeyShowWindow + private HotKey _hotKeyShowWindow; + public HotKey HotKeyShowWindow + { + get => _hotKeyShowWindow; + set { - get => _hotKeyShowWindow; - set - { - if (Equals(value, _hotKeyShowWindow)) - return; - - if (!_isLoading && value != null) - { - SettingsManager.Current.HotKey_ShowWindowKey = (int)HotKeys.WpfKeyToFormsKeys(value.Key); - SettingsManager.Current.HotKey_ShowWindowModifier = HotKeys.GetModifierKeysSum(value.ModifierKeys); + if (Equals(value, _hotKeyShowWindow)) + return; - SettingsManager.HotKeysChanged = true; - } + if (!_isLoading && value != null) + { + SettingsManager.Current.HotKey_ShowWindowKey = (int)HotKeys.WpfKeyToFormsKeys(value.Key); + SettingsManager.Current.HotKey_ShowWindowModifier = HotKeys.GetModifierKeysSum(value.ModifierKeys); - _hotKeyShowWindow = value; - OnPropertyChanged(); + SettingsManager.HotKeysChanged = true; } + + _hotKeyShowWindow = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, LoadSettings - public SettingsHotKeysViewModel() - { - _isLoading = true; + #region Constructor, LoadSettings + public SettingsHotKeysViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - HotKeyShowWindowEnabled = SettingsManager.Current.HotKey_ShowWindowEnabled; - HotKeyShowWindow = new HotKey(HotKeys.FormsKeysToWpfKey(SettingsManager.Current.HotKey_ShowWindowKey), HotKeys.GetModifierKeysFromInt(SettingsManager.Current.HotKey_ShowWindowModifier)); - } - #endregion + private void LoadSettings() + { + HotKeyShowWindowEnabled = SettingsManager.Current.HotKey_ShowWindowEnabled; + HotKeyShowWindow = new HotKey(HotKeys.FormsKeysToWpfKey(SettingsManager.Current.HotKey_ShowWindowKey), HotKeys.GetModifierKeysFromInt(SettingsManager.Current.HotKey_ShowWindowModifier)); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsLanguageViewModel.cs b/Source/NETworkManager/ViewModels/SettingsLanguageViewModel.cs index 7e7c1cdaaa..98b7c94d04 100644 --- a/Source/NETworkManager/ViewModels/SettingsLanguageViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsLanguageViewModel.cs @@ -7,90 +7,89 @@ using System.Windows.Input; using NETworkManager.Localization; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsLanguageViewModel : ViewModelBase { - public class SettingsLanguageViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - public ICollectionView Languages { get; } + public ICollectionView Languages { get; } - private LocalizationInfo _selectedLanguage; - public LocalizationInfo SelectedLangauge + private LocalizationInfo _selectedLanguage; + public LocalizationInfo SelectedLangauge + { + get => _selectedLanguage; + set { - get => _selectedLanguage; - set - { - if (value == _selectedLanguage) - return; - - if (!_isLoading && value != null) // Don't change if the value is null (can happen when a user searchs for a language....) - { - LocalizationManager.GetInstance().Change(value); + if (value == _selectedLanguage) + return; - SettingsManager.Current.Localization_CultureCode = value.Code; - } + if (!_isLoading && value != null) // Don't change if the value is null (can happen when a user searchs for a language....) + { + LocalizationManager.GetInstance().Change(value); - _selectedLanguage = value; - OnPropertyChanged(); + SettingsManager.Current.Localization_CultureCode = value.Code; } + + _selectedLanguage = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - Languages.Refresh(); + Languages.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion + } + #endregion - #region Construtor, LoadSettings - public SettingsLanguageViewModel() - { - _isLoading = true; + #region Construtor, LoadSettings + public SettingsLanguageViewModel() + { + _isLoading = true; - Languages = CollectionViewSource.GetDefaultView(LocalizationManager.List); - Languages.SortDescriptions.Add(new SortDescription(nameof(LocalizationInfo.IsOfficial), ListSortDirection.Descending)); - Languages.SortDescriptions.Add(new SortDescription(nameof(LocalizationInfo.Name), ListSortDirection.Ascending)); + Languages = CollectionViewSource.GetDefaultView(LocalizationManager.List); + Languages.SortDescriptions.Add(new SortDescription(nameof(LocalizationInfo.IsOfficial), ListSortDirection.Descending)); + Languages.SortDescriptions.Add(new SortDescription(nameof(LocalizationInfo.Name), ListSortDirection.Ascending)); - Languages.Filter = o => - { - if (string.IsNullOrEmpty(Search)) - return true; + Languages.Filter = o => + { + if (string.IsNullOrEmpty(Search)) + return true; - if (!(o is LocalizationInfo info)) - return false; + if (!(o is LocalizationInfo info)) + return false; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Name, NativeName - return info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.NativeName.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1; - }; + // Search by: Name, NativeName + return info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.NativeName.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1; + }; - SelectedLangauge = Languages.Cast().FirstOrDefault(x => x.Code == LocalizationManager.GetInstance().Current.Code); + SelectedLangauge = Languages.Cast().FirstOrDefault(x => x.Code == LocalizationManager.GetInstance().Current.Code); - _isLoading = false; - } - #endregion + _isLoading = false; + } + #endregion - #region ICommands & Actions - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + #region ICommands & Actions + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } - #endregion - } + private void ClearSearchAction() + { + Search = string.Empty; + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsNetworkViewModel.cs b/Source/NETworkManager/ViewModels/SettingsNetworkViewModel.cs index 49b52355ad..a0d8fe2b51 100644 --- a/Source/NETworkManager/ViewModels/SettingsNetworkViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsNetworkViewModel.cs @@ -1,101 +1,100 @@ using NETworkManager.Settings; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsNetworkViewModel : ViewModelBase { - public class SettingsNetworkViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private bool _useCustomDNSServer; - public bool UseCustomDNSServer + private bool _useCustomDNSServer; + public bool UseCustomDNSServer + { + get => _useCustomDNSServer; + set { - get => _useCustomDNSServer; - set - { - if (value == _useCustomDNSServer) - return; - - if (!_isLoading) - SettingsManager.Current.Network_UseCustomDNSServer = value; - - _useCustomDNSServer = value; - OnPropertyChanged(); - } + if (value == _useCustomDNSServer) + return; + + if (!_isLoading) + SettingsManager.Current.Network_UseCustomDNSServer = value; + + _useCustomDNSServer = value; + OnPropertyChanged(); } + } - private string _customDNSServer; - public string CustomDNSServer + private string _customDNSServer; + public string CustomDNSServer + { + get => _customDNSServer; + set { - get => _customDNSServer; - set - { - if (value == _customDNSServer) - return; - - if (!_isLoading) - SettingsManager.Current.Network_CustomDNSServer = value.Replace(" ", ""); - - _customDNSServer = value; - OnPropertyChanged(); - } + if (value == _customDNSServer) + return; + + if (!_isLoading) + SettingsManager.Current.Network_CustomDNSServer = value.Replace(" ", ""); + + _customDNSServer = value; + OnPropertyChanged(); } + } - private bool _resolveHostnamePreferIPv4; - public bool ResolveHostnamePreferIPv4 + private bool _resolveHostnamePreferIPv4; + public bool ResolveHostnamePreferIPv4 + { + get => _resolveHostnamePreferIPv4; + set { - get => _resolveHostnamePreferIPv4; - set - { - if (value == _resolveHostnamePreferIPv4) - return; - - if (!_isLoading) - SettingsManager.Current.Network_ResolveHostnamePreferIPv4 = value; - - _resolveHostnamePreferIPv4 = value; - OnPropertyChanged(); - } + if (value == _resolveHostnamePreferIPv4) + return; + + if (!_isLoading) + SettingsManager.Current.Network_ResolveHostnamePreferIPv4 = value; + + _resolveHostnamePreferIPv4 = value; + OnPropertyChanged(); } + } - private bool _resolveHostnamePreferIPv6; - public bool ResolveHostnamePreferIPv6 + private bool _resolveHostnamePreferIPv6; + public bool ResolveHostnamePreferIPv6 + { + get => _resolveHostnamePreferIPv6; + set { - get => _resolveHostnamePreferIPv6; - set - { - if (value == _resolveHostnamePreferIPv6) - return; - - _resolveHostnamePreferIPv6 = value; - OnPropertyChanged(); - } + if (value == _resolveHostnamePreferIPv6) + return; + + _resolveHostnamePreferIPv6 = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, LoadSettings - public SettingsNetworkViewModel() - { - _isLoading = true; + #region Constructor, LoadSettings + public SettingsNetworkViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - UseCustomDNSServer = SettingsManager.Current.Network_UseCustomDNSServer; + private void LoadSettings() + { + UseCustomDNSServer = SettingsManager.Current.Network_UseCustomDNSServer; - if (SettingsManager.Current.Network_CustomDNSServer != null) - CustomDNSServer = string.Join("; ", SettingsManager.Current.Network_CustomDNSServer); + if (SettingsManager.Current.Network_CustomDNSServer != null) + CustomDNSServer = string.Join("; ", SettingsManager.Current.Network_CustomDNSServer); - if (SettingsManager.Current.Network_ResolveHostnamePreferIPv4) - ResolveHostnamePreferIPv4 = true; - else - ResolveHostnamePreferIPv6 = true; - } - #endregion + if (SettingsManager.Current.Network_ResolveHostnamePreferIPv4) + ResolveHostnamePreferIPv4 = true; + else + ResolveHostnamePreferIPv6 = true; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsProfilesViewModel.cs b/Source/NETworkManager/ViewModels/SettingsProfilesViewModel.cs index c96e20ba40..4e182bb823 100644 --- a/Source/NETworkManager/ViewModels/SettingsProfilesViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsProfilesViewModel.cs @@ -10,304 +10,303 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsProfilesViewModel : ViewModelBase { - public class SettingsProfilesViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - public Action CloseAction { get; set; } - - private string _location; - public string Location + public Action CloseAction { get; set; } + + private string _location; + public string Location + { + get => _location; + set { - get => _location; - set - { - if (value == _location) - return; + if (value == _location) + return; - _location = value; - OnPropertyChanged(); - } + _location = value; + OnPropertyChanged(); } - - private ICollectionView _profileFiles; - public ICollectionView ProfileFiles + } + + private ICollectionView _profileFiles; + public ICollectionView ProfileFiles + { + get => _profileFiles; + set { - get => _profileFiles; - set - { - if (value == _profileFiles) - return; + if (value == _profileFiles) + return; - _profileFiles = value; - OnPropertyChanged(); - } + _profileFiles = value; + OnPropertyChanged(); } + } - private ProfileFileInfo _selectedProfileFile; - public ProfileFileInfo SelectedProfileFile + private ProfileFileInfo _selectedProfileFile; + public ProfileFileInfo SelectedProfileFile + { + get => _selectedProfileFile; + set { - get => _selectedProfileFile; - set - { - if (Equals(value, _selectedProfileFile)) - return; + if (Equals(value, _selectedProfileFile)) + return; - _selectedProfileFile = value; - OnPropertyChanged(); - } + _selectedProfileFile = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, LoadSettings - public SettingsProfilesViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, LoadSettings + public SettingsProfilesViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - ProfileFiles = new CollectionViewSource { Source = ProfileManager.ProfileFiles }.View; - ProfileFiles.SortDescriptions.Add(new SortDescription(nameof(ProfileFileInfo.Name), ListSortDirection.Ascending)); + ProfileFiles = new CollectionViewSource { Source = ProfileManager.ProfileFiles }.View; + ProfileFiles.SortDescriptions.Add(new SortDescription(nameof(ProfileFileInfo.Name), ListSortDirection.Ascending)); - LoadSettings(); - } + LoadSettings(); + } - private void LoadSettings() - { - Location = ProfileManager.GetProfilesFolderLocation(); - } - #endregion + private void LoadSettings() + { + Location = ProfileManager.GetProfilesFolderLocation(); + } + #endregion - #region ICommands & Actions + #region ICommands & Actions - public ICommand OpenLocationCommand => new RelayCommand(p => OpenLocationAction()); + public ICommand OpenLocationCommand => new RelayCommand(p => OpenLocationAction()); - private static void OpenLocationAction() - { - Process.Start("explorer.exe", ProfileManager.GetProfilesFolderLocation()); - } - - public ICommand AddProfileFileCommand => new RelayCommand(p => AddProfileFileAction()); + private static void OpenLocationAction() + { + Process.Start("explorer.exe", ProfileManager.GetProfilesFolderLocation()); + } + + public ICommand AddProfileFileCommand => new RelayCommand(p => AddProfileFileAction()); - private async void AddProfileFileAction() + private async void AddProfileFileAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.AddProfileFile - }; - - var profileFileViewModel = new ProfileFileViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - ProfileManager.CreateEmptyProfileFile(instance.Name); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); + Title = Localization.Resources.Strings.AddProfileFile + }; - customDialog.Content = new ProfileFileDialog - { - DataContext = profileFileViewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + var profileFileViewModel = new ProfileFileViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - public ICommand EditProfileFileCommand => new RelayCommand(p => EditProfileFileAction()); + ProfileManager.CreateEmptyProfileFile(instance.Name); + }, async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - private async void EditProfileFileAction() + customDialog.Content = new ProfileFileDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.EditProfileFile - }; + DataContext = profileFileViewModel + }; - var profileFileViewModel = new ProfileFileViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - ProfileManager.RenameProfileFile(SelectedProfileFile, instance.Name); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, SelectedProfileFile); + public ICommand EditProfileFileCommand => new RelayCommand(p => EditProfileFileAction()); - customDialog.Content = new ProfileFileDialog - { - DataContext = profileFileViewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + private async void EditProfileFileAction() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.EditProfileFile + }; - public ICommand DeleteProfileFileCommand => new RelayCommand(p => DeleteProfileFileAction(), DeleteProfileFile_CanExecute); + var profileFileViewModel = new ProfileFileViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - private bool DeleteProfileFile_CanExecute(object obj) + ProfileManager.RenameProfileFile(SelectedProfileFile, instance.Name); + }, async instance => { - return ProfileFiles.Cast().Count() > 1; - } + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, SelectedProfileFile); - private async void DeleteProfileFileAction() + customDialog.Content = new ProfileFileDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.DeleteProfileFile - }; + DataContext = profileFileViewModel + }; - var confirmDeleteViewModel = new ConfirmDeleteViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - ProfileManager.DeleteProfileFile(SelectedProfileFile); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }, Localization.Resources.Strings.DeleteProfileFileMessage); + public ICommand DeleteProfileFileCommand => new RelayCommand(p => DeleteProfileFileAction(), DeleteProfileFile_CanExecute); - customDialog.Content = new ConfirmDeleteDialog - { - DataContext = confirmDeleteViewModel - }; - - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + private bool DeleteProfileFile_CanExecute(object obj) + { + return ProfileFiles.Cast().Count() > 1; + } - public ICommand EnableEncryptionCommand => new RelayCommand(p => EnableEncryptionAction()); + private async void DeleteProfileFileAction() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.DeleteProfileFile + }; - private async void EnableEncryptionAction() + var confirmDeleteViewModel = new ConfirmDeleteViewModel(async instance => { - var settings = AppearanceManager.MetroDialog; + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - settings.NegativeButtonText = Localization.Resources.Strings.Cancel; - settings.DefaultButtonFocus = MessageDialogResult.Affirmative; + ProfileManager.DeleteProfileFile(SelectedProfileFile); + }, async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }, Localization.Resources.Strings.DeleteProfileFileMessage); - if (await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Disclaimer, Localization.Resources.Strings.ProfileEncryptionDisclaimer, MessageDialogStyle.AffirmativeAndNegative) == MessageDialogResult.Affirmative) - { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.SetMasterPassword - }; + customDialog.Content = new ConfirmDeleteDialog + { + DataContext = confirmDeleteViewModel + }; - var credentialsSetPasswordViewModel = new CredentialsSetPasswordViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - - try - { - ProfileManager.EnableEncryption(SelectedProfileFile, instance.Password); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.EncryptionError, $"{Localization.Resources.Strings.EncryptionErrorMessage}\n\n{ex.Message}", MessageDialogStyle.Affirmative, settings); - } - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - customDialog.Content = new CredentialsSetPasswordDialog - { - DataContext = credentialsSetPasswordViewModel - }; + public ICommand EnableEncryptionCommand => new RelayCommand(p => EnableEncryptionAction()); - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - } + private async void EnableEncryptionAction() + { + var settings = AppearanceManager.MetroDialog; - public ICommand ChangeMasterPasswordCommand => new RelayCommand(p => ChangeMasterPasswordAction()); + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + settings.NegativeButtonText = Localization.Resources.Strings.Cancel; + settings.DefaultButtonFocus = MessageDialogResult.Affirmative; - private async void ChangeMasterPasswordAction() + if (await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Disclaimer, Localization.Resources.Strings.ProfileEncryptionDisclaimer, MessageDialogStyle.AffirmativeAndNegative) == MessageDialogResult.Affirmative) { var customDialog = new CustomDialog { - Title = Localization.Resources.Strings.ChangeMasterPassword + Title = Localization.Resources.Strings.SetMasterPassword }; - var credentialsPasswordViewModel = new CredentialsChangePasswordViewModel(async instance => + var credentialsSetPasswordViewModel = new CredentialsSetPasswordViewModel(async instance => { await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); try { - ProfileManager.ChangeMasterPassword(SelectedProfileFile, instance.Password, instance.NewPassword); - } - catch (System.Security.Cryptography.CryptographicException) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.WrongPassword, Localization.Resources.Strings.WrongPasswordDecryptionFailedMessage, MessageDialogStyle.Affirmative, settings); + ProfileManager.EnableEncryption(SelectedProfileFile, instance.Password); } catch (Exception ex) { var settings = AppearanceManager.MetroDialog; settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.DecryptionError, $"{Localization.Resources.Strings.DecryptionErrorMessage}\n\n{ex.Message}", MessageDialogStyle.Affirmative, settings); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.EncryptionError, $"{Localization.Resources.Strings.EncryptionErrorMessage}\n\n{ex.Message}", MessageDialogStyle.Affirmative, settings); } - }, async instance => { await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }); - customDialog.Content = new CredentialsChangePasswordDialog + customDialog.Content = new CredentialsSetPasswordDialog { - DataContext = credentialsPasswordViewModel + DataContext = credentialsSetPasswordViewModel }; await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); } + } - public ICommand DisableEncryptionCommand => new RelayCommand(p => DisableEncryptionAction()); + public ICommand ChangeMasterPasswordCommand => new RelayCommand(p => ChangeMasterPasswordAction()); - private async void DisableEncryptionAction() + private async void ChangeMasterPasswordAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog + Title = Localization.Resources.Strings.ChangeMasterPassword + }; + + var credentialsPasswordViewModel = new CredentialsChangePasswordViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + + try { - Title = Localization.Resources.Strings.MasterPassword - }; + ProfileManager.ChangeMasterPassword(SelectedProfileFile, instance.Password, instance.NewPassword); + } + catch (System.Security.Cryptography.CryptographicException) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - var credentialsPasswordViewModel = new CredentialsPasswordViewModel(async instance => + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.WrongPassword, Localization.Resources.Strings.WrongPasswordDecryptionFailedMessage, MessageDialogStyle.Affirmative, settings); + } + catch (Exception ex) { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - try - { - ProfileManager.DisableEncryption(SelectedProfileFile, instance.Password); - } - catch (System.Security.Cryptography.CryptographicException) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.DecryptionError, $"{Localization.Resources.Strings.DecryptionErrorMessage}\n\n{ex.Message}", MessageDialogStyle.Affirmative, settings); + } - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.WrongPassword, Localization.Resources.Strings.WrongPasswordDecryptionFailedMessage, MessageDialogStyle.Affirmative, settings); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + }, async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.DecryptionError, $"{Localization.Resources.Strings.DecryptionErrorMessage}\n\n{ex.Message}", MessageDialogStyle.Affirmative, settings); - } - }, async instance => + customDialog.Content = new CredentialsChangePasswordDialog + { + DataContext = credentialsPasswordViewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + public ICommand DisableEncryptionCommand => new RelayCommand(p => DisableEncryptionAction()); + + private async void DisableEncryptionAction() + { + var customDialog = new CustomDialog + { + Title = Localization.Resources.Strings.MasterPassword + }; + + var credentialsPasswordViewModel = new CredentialsPasswordViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + + try { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - }); + ProfileManager.DisableEncryption(SelectedProfileFile, instance.Password); + } + catch (System.Security.Cryptography.CryptographicException) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - customDialog.Content = new CredentialsPasswordDialog + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.WrongPassword, Localization.Resources.Strings.WrongPasswordDecryptionFailedMessage, MessageDialogStyle.Affirmative, settings); + } + catch (Exception ex) { - DataContext = credentialsPasswordViewModel - }; + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.DecryptionError, $"{Localization.Resources.Strings.DecryptionErrorMessage}\n\n{ex.Message}", MessageDialogStyle.Affirmative, settings); + } + }, async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + }); + + customDialog.Content = new CredentialsPasswordDialog + { + DataContext = credentialsPasswordViewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsSettingsViewModel.cs b/Source/NETworkManager/ViewModels/SettingsSettingsViewModel.cs index 322b7a5803..5e506bd3ac 100644 --- a/Source/NETworkManager/ViewModels/SettingsSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsSettingsViewModel.cs @@ -5,73 +5,72 @@ using System.Diagnostics; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsSettingsViewModel : ViewModelBase { - public class SettingsSettingsViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - public Action CloseAction { get; set; } + public Action CloseAction { get; set; } - private string _location; - public string Location + private string _location; + public string Location + { + get => _location; + set { - get => _location; - set - { - if (value == _location) - return; - - _location = value; - OnPropertyChanged(); - } + if (value == _location) + return; + + _location = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, LoadSettings - public SettingsSettingsViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, LoadSettings + public SettingsSettingsViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - LoadSettings(); - } + LoadSettings(); + } - private void LoadSettings() - { - Location = SettingsManager.GetSettingsFolderLocation(); - } - #endregion + private void LoadSettings() + { + Location = SettingsManager.GetSettingsFolderLocation(); + } + #endregion - #region ICommands & Actions - public ICommand OpenLocationCommand => new RelayCommand(p => OpenLocationAction()); + #region ICommands & Actions + public ICommand OpenLocationCommand => new RelayCommand(p => OpenLocationAction()); - private static void OpenLocationAction() - { - Process.Start("explorer.exe", SettingsManager.GetSettingsFolderLocation()); - } + private static void OpenLocationAction() + { + Process.Start("explorer.exe", SettingsManager.GetSettingsFolderLocation()); + } - public ICommand ResetSettingsCommand => new RelayCommand(p => ResetSettingsAction()); + public ICommand ResetSettingsCommand => new RelayCommand(p => ResetSettingsAction()); - public async void ResetSettingsAction() - { - var settings = AppearanceManager.MetroDialog; + public async void ResetSettingsAction() + { + var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.Reset; - settings.NegativeButtonText = Localization.Resources.Strings.Cancel; + settings.AffirmativeButtonText = Localization.Resources.Strings.Reset; + settings.NegativeButtonText = Localization.Resources.Strings.Cancel; - settings.DefaultButtonFocus = MessageDialogResult.Affirmative; + settings.DefaultButtonFocus = MessageDialogResult.Affirmative; - if (await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.ResetSettingsQuestion, Localization.Resources.Strings.SettingsAreResetAndApplicationWillBeRestartedMessage, MessageDialogStyle.AffirmativeAndNegative, settings) != MessageDialogResult.Affirmative) - return; + if (await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.ResetSettingsQuestion, Localization.Resources.Strings.SettingsAreResetAndApplicationWillBeRestartedMessage, MessageDialogStyle.AffirmativeAndNegative, settings) != MessageDialogResult.Affirmative) + return; - SettingsManager.InitDefault(); + SettingsManager.InitDefault(); - // Restart the application - ConfigurationManager.Current.Restart = true; - ConfigurationManager.Current.DisableSaveSettings = true; - CloseAction(); - } - #endregion + // Restart the application + ConfigurationManager.Current.Restart = true; + ConfigurationManager.Current.DisableSaveSettings = true; + CloseAction(); } + #endregion } diff --git a/Source/NETworkManager/ViewModels/SettingsStatusViewModel.cs b/Source/NETworkManager/ViewModels/SettingsStatusViewModel.cs index 675fa3b2c9..6b4535e2af 100644 --- a/Source/NETworkManager/ViewModels/SettingsStatusViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsStatusViewModel.cs @@ -1,82 +1,80 @@ using NETworkManager.Settings; -using NETworkManager.Utilities; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsStatusViewModel : ViewModelBase { - public class SettingsStatusViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private bool _showWindowOnNetworkChange; - public bool ShowWindowOnNetworkChange + private bool _showWindowOnNetworkChange; + public bool ShowWindowOnNetworkChange + { + get => _showWindowOnNetworkChange; + set { - get => _showWindowOnNetworkChange; - set - { - if (value == _showWindowOnNetworkChange) - return; - - if (!_isLoading) - SettingsManager.Current.Status_ShowWindowOnNetworkChange = value; - - _showWindowOnNetworkChange = value; - OnPropertyChanged(); - } + if (value == _showWindowOnNetworkChange) + return; + + if (!_isLoading) + SettingsManager.Current.Status_ShowWindowOnNetworkChange = value; + + _showWindowOnNetworkChange = value; + OnPropertyChanged(); } + } - private string _ipAddressToDetectLocalIPAddressBasedOnRouting; - public string IPAddressToDetectLocalIPAddressBasedOnRouting + private string _ipAddressToDetectLocalIPAddressBasedOnRouting; + public string IPAddressToDetectLocalIPAddressBasedOnRouting + { + get => _ipAddressToDetectLocalIPAddressBasedOnRouting; + set { - get => _ipAddressToDetectLocalIPAddressBasedOnRouting; - set - { - if (value == _ipAddressToDetectLocalIPAddressBasedOnRouting) - return; - - if (!_isLoading) - SettingsManager.Current.Status_IPAddressToDetectLocalIPAddressBasedOnRouting = value; - - _ipAddressToDetectLocalIPAddressBasedOnRouting = value; - OnPropertyChanged(); - } + if (value == _ipAddressToDetectLocalIPAddressBasedOnRouting) + return; + + if (!_isLoading) + SettingsManager.Current.Status_IPAddressToDetectLocalIPAddressBasedOnRouting = value; + + _ipAddressToDetectLocalIPAddressBasedOnRouting = value; + OnPropertyChanged(); } + } - private int _windowCloseTime; - public int WindowCloseTime + private int _windowCloseTime; + public int WindowCloseTime + { + get => _windowCloseTime; + set { - get => _windowCloseTime; - set - { - if (value == _windowCloseTime) - return; - - if (!_isLoading) - SettingsManager.Current.Status_WindowCloseTime = value; - - _windowCloseTime = value; - OnPropertyChanged(); - } + if (value == _windowCloseTime) + return; + + if (!_isLoading) + SettingsManager.Current.Status_WindowCloseTime = value; + + _windowCloseTime = value; + OnPropertyChanged(); } + } - #endregion + #endregion - #region Contructor, load settings - public SettingsStatusViewModel() - { - _isLoading = true; + #region Contructor, load settings + public SettingsStatusViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ShowWindowOnNetworkChange = SettingsManager.Current.Status_ShowWindowOnNetworkChange; - IPAddressToDetectLocalIPAddressBasedOnRouting = SettingsManager.Current.Status_IPAddressToDetectLocalIPAddressBasedOnRouting; - WindowCloseTime = SettingsManager.Current.Status_WindowCloseTime; - } - #endregion + private void LoadSettings() + { + ShowWindowOnNetworkChange = SettingsManager.Current.Status_ShowWindowOnNetworkChange; + IPAddressToDetectLocalIPAddressBasedOnRouting = SettingsManager.Current.Status_IPAddressToDetectLocalIPAddressBasedOnRouting; + WindowCloseTime = SettingsManager.Current.Status_WindowCloseTime; } -} \ No newline at end of file + #endregion +} diff --git a/Source/NETworkManager/ViewModels/SettingsUpdateViewModel.cs b/Source/NETworkManager/ViewModels/SettingsUpdateViewModel.cs index 4519ca7351..577288de5f 100644 --- a/Source/NETworkManager/ViewModels/SettingsUpdateViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsUpdateViewModel.cs @@ -1,62 +1,61 @@ using NETworkManager.Settings; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsUpdateViewModel : ViewModelBase { - public class SettingsUpdateViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private bool _checkForUpdatesAtStartup; - public bool CheckForUpdatesAtStartup + private bool _checkForUpdatesAtStartup; + public bool CheckForUpdatesAtStartup + { + get => _checkForUpdatesAtStartup; + set { - get => _checkForUpdatesAtStartup; - set - { - if (value == _checkForUpdatesAtStartup) - return; - - if (!_isLoading) - SettingsManager.Current.Update_CheckForUpdatesAtStartup = value; - - _checkForUpdatesAtStartup = value; - OnPropertyChanged(); - } - } + if (value == _checkForUpdatesAtStartup) + return; - private bool _checkForPreReleases; - public bool CheckForPreReleases - { - get => _checkForPreReleases; - set - { - if (value == _checkForPreReleases) - return; - - if (!_isLoading) - SettingsManager.Current.Update_CheckForPreReleases = value; - - _checkForPreReleases = value; - OnPropertyChanged(); - } + if (!_isLoading) + SettingsManager.Current.Update_CheckForUpdatesAtStartup = value; + + _checkForUpdatesAtStartup = value; + OnPropertyChanged(); } - #endregion + } - #region Constructor, LoadSettings - public SettingsUpdateViewModel() + private bool _checkForPreReleases; + public bool CheckForPreReleases + { + get => _checkForPreReleases; + set { - _isLoading = true; + if (value == _checkForPreReleases) + return; - LoadSettings(); + if (!_isLoading) + SettingsManager.Current.Update_CheckForPreReleases = value; - _isLoading = false; + _checkForPreReleases = value; + OnPropertyChanged(); } + } + #endregion - private void LoadSettings() - { - CheckForUpdatesAtStartup = SettingsManager.Current.Update_CheckForUpdatesAtStartup; - CheckForPreReleases = SettingsManager.Current.Update_CheckForPreReleases; - } - #endregion + #region Constructor, LoadSettings + public SettingsUpdateViewModel() + { + _isLoading = true; + + LoadSettings(); + + _isLoading = false; + } + + private void LoadSettings() + { + CheckForUpdatesAtStartup = SettingsManager.Current.Update_CheckForUpdatesAtStartup; + CheckForPreReleases = SettingsManager.Current.Update_CheckForPreReleases; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsViewModel.cs b/Source/NETworkManager/ViewModels/SettingsViewModel.cs index 6e13662609..8bdfe8d645 100644 --- a/Source/NETworkManager/ViewModels/SettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsViewModel.cs @@ -12,331 +12,330 @@ using NETworkManager.Utilities; using NETworkManager.Views; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsViewModel : ViewModelBase { - public class SettingsViewModel : ViewModelBase - { - #region Variables - private int _selectedTabIndex; + #region Variables + private int _selectedTabIndex; - public int SelectedTabIndex + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; - - _selectedTabIndex = value; - OnPropertyChanged(); - } + if (value == _selectedTabIndex) + return; + + _selectedTabIndex = value; + OnPropertyChanged(); } + } - public ICollectionView SettingsViews { get; private set; } + public ICollectionView SettingsViews { get; private set; } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - SettingsViews.Refresh(); + SettingsViews.Refresh(); - // Show note when there was nothing found - SearchNothingFound = !SettingsViews.Cast().Any(); + // Show note when there was nothing found + SearchNothingFound = !SettingsViews.Cast().Any(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _searchNothingFound; - public bool SearchNothingFound + private bool _searchNothingFound; + public bool SearchNothingFound + { + get => _searchNothingFound; + set { - get => _searchNothingFound; - set - { - if (value == _searchNothingFound) - return; - - _searchNothingFound = value; - OnPropertyChanged(); - } - } + if (value == _searchNothingFound) + return; - private UserControl _settingsContent; - public UserControl SettingsContent - { - get => _settingsContent; - set - { - if (Equals(value, _settingsContent)) - return; - - _settingsContent = value; - OnPropertyChanged(); - } + _searchNothingFound = value; + OnPropertyChanged(); } + } - private SettingsViewInfo _selectedSettingsView; - public SettingsViewInfo SelectedSettingsView + private UserControl _settingsContent; + public UserControl SettingsContent + { + get => _settingsContent; + set { - get => _selectedSettingsView; - set - { - if (value == _selectedSettingsView) - return; - - if (value != null) - ChangeSettingsContent(value); - - _selectedSettingsView = value; - OnPropertyChanged(); - } + if (Equals(value, _settingsContent)) + return; + + _settingsContent = value; + OnPropertyChanged(); } + } - private SettingsGeneralView _settingsGerneralView; - private SettingsWindowView _settingsWindowView; - private SettingsAppearanceView _settingsApperanceView; - private SettingsLanguageView _settingsLanguageView; - private SettingsNetworkView _settingsNetworkView; - private SettingsStatusView _settingsStatusView; - private SettingsHotKeysView _settingsHotKeysView; - private SettingsAutostartView _settingsAutostartView; - private SettingsUpdateView _settingsUpdateView; - private SettingsSettingsView _settingsSettingsView; - private SettingsProfilesView _settingsProfilesView; - private DashboardSettingsView _dashboardSettingsView; - private IPScannerSettingsView _ipScannerSettingsView; - private PortScannerSettingsView _portScannerSettingsView; - private PingMonitorSettingsView _pingMonitorSettingsView; - private TracerouteSettingsView _tracerouteSettingsView; - private DNSLookupSettingsView _dnsLookupSettingsViewModel; - private RemoteDesktopSettingsView _remoteDesktopSettingsView; - private PowerShellSettingsView _powerShellSettingsView; - private PuTTYSettingsView _puTTYSettingsView; - private AWSSessionManagerSettingsView _awsSessionManagerSettingsView; - private TigerVNCSettingsView _tigerVNCSettingsView; - private SNMPSettingsView _snmpSettingsView; - private SNTPLookupSettingsView _sntpLookupSettingsView; - private WakeOnLANSettingsView _wakeOnLANSettingsView; - //private WhoisSettingsView _whoisSettingsView; - private BitCalculatorSettingsView _bitCalculatorSettingsView; - #endregion - - #region Contructor, load settings - public SettingsViewModel(ApplicationName applicationName) + private SettingsViewInfo _selectedSettingsView; + public SettingsViewInfo SelectedSettingsView + { + get => _selectedSettingsView; + set { - LoadSettings(); + if (value == _selectedSettingsView) + return; - ChangeSettingsView(applicationName); + if (value != null) + ChangeSettingsContent(value); + + _selectedSettingsView = value; + OnPropertyChanged(); } + } - private void LoadSettings() - { - SettingsViews = new CollectionViewSource { Source = SettingsViewManager.List }.View; - SettingsViews.GroupDescriptions.Add(new PropertyGroupDescription(nameof(SettingsViewInfo.Group))); - SettingsViews.SortDescriptions.Add(new SortDescription(nameof(SettingsViewInfo.Name), ListSortDirection.Ascending)); - SettingsViews.Filter = o => - { - if (string.IsNullOrEmpty(Search)) - return true; + private SettingsGeneralView _settingsGerneralView; + private SettingsWindowView _settingsWindowView; + private SettingsAppearanceView _settingsApperanceView; + private SettingsLanguageView _settingsLanguageView; + private SettingsNetworkView _settingsNetworkView; + private SettingsStatusView _settingsStatusView; + private SettingsHotKeysView _settingsHotKeysView; + private SettingsAutostartView _settingsAutostartView; + private SettingsUpdateView _settingsUpdateView; + private SettingsSettingsView _settingsSettingsView; + private SettingsProfilesView _settingsProfilesView; + private DashboardSettingsView _dashboardSettingsView; + private IPScannerSettingsView _ipScannerSettingsView; + private PortScannerSettingsView _portScannerSettingsView; + private PingMonitorSettingsView _pingMonitorSettingsView; + private TracerouteSettingsView _tracerouteSettingsView; + private DNSLookupSettingsView _dnsLookupSettingsViewModel; + private RemoteDesktopSettingsView _remoteDesktopSettingsView; + private PowerShellSettingsView _powerShellSettingsView; + private PuTTYSettingsView _puTTYSettingsView; + private AWSSessionManagerSettingsView _awsSessionManagerSettingsView; + private TigerVNCSettingsView _tigerVNCSettingsView; + private SNMPSettingsView _snmpSettingsView; + private SNTPLookupSettingsView _sntpLookupSettingsView; + private WakeOnLANSettingsView _wakeOnLANSettingsView; + //private WhoisSettingsView _whoisSettingsView; + private BitCalculatorSettingsView _bitCalculatorSettingsView; + #endregion + + #region Contructor, load settings + public SettingsViewModel(ApplicationName applicationName) + { + LoadSettings(); - if (o is not SettingsViewInfo info) - return false; + ChangeSettingsView(applicationName); + } - var regex = new Regex(@" |-"); + private void LoadSettings() + { + SettingsViews = new CollectionViewSource { Source = SettingsViewManager.List }.View; + SettingsViews.GroupDescriptions.Add(new PropertyGroupDescription(nameof(SettingsViewInfo.Group))); + SettingsViews.SortDescriptions.Add(new SortDescription(nameof(SettingsViewInfo.Name), ListSortDirection.Ascending)); + SettingsViews.Filter = o => + { + if (string.IsNullOrEmpty(Search)) + return true; - var search = regex.Replace(Search, ""); + if (o is not SettingsViewInfo info) + return false; - // Search by TranslatedName and Name - return regex.Replace(SettingsViewNameTranslator.GetInstance().Translate(info.Name), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || (regex.Replace(info.Name.ToString(), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; - } - #endregion + var regex = new Regex(@" |-"); - #region ICommands & Actions - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + var search = regex.Replace(Search, ""); - private void ClearSearchAction() - { - Search = string.Empty; - } - #endregion + // Search by TranslatedName and Name + return regex.Replace(SettingsViewNameTranslator.GetInstance().Translate(info.Name), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || (regex.Replace(info.Name.ToString(), "").IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; + } + #endregion - #region Methods - public void ChangeSettingsView(ApplicationName applicationName) - { - // Don't change the view, if the user has filtered the settings... - if (!string.IsNullOrEmpty(Search)) - return; + #region ICommands & Actions + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - if (Enum.GetNames(typeof(SettingsViewName)).Contains(applicationName.ToString()) && ApplicationName.None.ToString() != applicationName.ToString()) - SelectedSettingsView = SettingsViews.SourceCollection.Cast().FirstOrDefault(x => x.Name.ToString() == applicationName.ToString()); - else - SelectedSettingsView = SettingsViews.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsViewName.General); - } + private void ClearSearchAction() + { + Search = string.Empty; + } + #endregion + + #region Methods + public void ChangeSettingsView(ApplicationName applicationName) + { + // Don't change the view, if the user has filtered the settings... + if (!string.IsNullOrEmpty(Search)) + return; + + if (Enum.GetNames(typeof(SettingsViewName)).Contains(applicationName.ToString()) && ApplicationName.None.ToString() != applicationName.ToString()) + SelectedSettingsView = SettingsViews.SourceCollection.Cast().FirstOrDefault(x => x.Name.ToString() == applicationName.ToString()); + else + SelectedSettingsView = SettingsViews.SourceCollection.Cast().FirstOrDefault(x => x.Name == SettingsViewName.General); + } - private void ChangeSettingsContent(SettingsViewInfo settingsViewInfo) + private void ChangeSettingsContent(SettingsViewInfo settingsViewInfo) + { + switch (settingsViewInfo.Name) { - switch (settingsViewInfo.Name) - { - case SettingsViewName.General: - _settingsGerneralView ??= new SettingsGeneralView(); - - SettingsContent = _settingsGerneralView; - break; - case SettingsViewName.Window: - _settingsWindowView ??= new SettingsWindowView(); - - SettingsContent = _settingsWindowView; - break; - case SettingsViewName.Appearance: - _settingsApperanceView ??= new SettingsAppearanceView(); - - SettingsContent = _settingsApperanceView; - break; - case SettingsViewName.Language: - _settingsLanguageView ??= new SettingsLanguageView(); - - SettingsContent = _settingsLanguageView; - break; - case SettingsViewName.Network: - _settingsNetworkView ??= new SettingsNetworkView(); - - SettingsContent = _settingsNetworkView; - break; - case SettingsViewName.Status: - _settingsStatusView ??= new SettingsStatusView(); - - SettingsContent = _settingsStatusView; - break; - case SettingsViewName.HotKeys: - _settingsHotKeysView ??= new SettingsHotKeysView(); - - SettingsContent = _settingsHotKeysView; - break; - case SettingsViewName.Autostart: - _settingsAutostartView ??= new SettingsAutostartView(); - - SettingsContent = _settingsAutostartView; - break; - case SettingsViewName.Update: - _settingsUpdateView ??= new SettingsUpdateView(); - - SettingsContent = _settingsUpdateView; - break; - case SettingsViewName.Settings: - _settingsSettingsView ??= new SettingsSettingsView(); - - // Save settings - _settingsSettingsView.OnVisible(); - - SettingsContent = _settingsSettingsView; - break; - case SettingsViewName.Profiles: - _settingsProfilesView ??= new SettingsProfilesView(); - - SettingsContent = _settingsProfilesView; - break; - case SettingsViewName.Dashboard: - _dashboardSettingsView ??= new DashboardSettingsView(); - - SettingsContent = _dashboardSettingsView; - break; - case SettingsViewName.IPScanner: - _ipScannerSettingsView ??= new IPScannerSettingsView(); - - SettingsContent = _ipScannerSettingsView; - break; - case SettingsViewName.PortScanner: - _portScannerSettingsView ??= new PortScannerSettingsView(); - - SettingsContent = _portScannerSettingsView; - break; - case SettingsViewName.PingMonitor: - _pingMonitorSettingsView ??= new PingMonitorSettingsView(); - - SettingsContent = _pingMonitorSettingsView; - break; - case SettingsViewName.Traceroute: - _tracerouteSettingsView ??= new TracerouteSettingsView(); - - SettingsContent = _tracerouteSettingsView; - break; - case SettingsViewName.DNSLookup: - _dnsLookupSettingsViewModel ??= new DNSLookupSettingsView(); - - SettingsContent = _dnsLookupSettingsViewModel; - break; - case SettingsViewName.RemoteDesktop: - _remoteDesktopSettingsView ??= new RemoteDesktopSettingsView(); - - SettingsContent = _remoteDesktopSettingsView; - break; - case SettingsViewName.PowerShell: - _powerShellSettingsView ??= new PowerShellSettingsView(); - - SettingsContent = _powerShellSettingsView; - break; - case SettingsViewName.PuTTY: - _puTTYSettingsView ??= new PuTTYSettingsView(); - - SettingsContent = _puTTYSettingsView; - break; - case SettingsViewName.AWSSessionManager: - _awsSessionManagerSettingsView ??= new AWSSessionManagerSettingsView(); - - SettingsContent = _awsSessionManagerSettingsView; - break; - case SettingsViewName.TigerVNC: - _tigerVNCSettingsView ??= new TigerVNCSettingsView(); - - SettingsContent = _tigerVNCSettingsView; - break; - case SettingsViewName.SNMP: - _snmpSettingsView ??= new SNMPSettingsView(); - - SettingsContent = _snmpSettingsView; - break; - case SettingsViewName.SNTPLookup: - _sntpLookupSettingsView ??= new SNTPLookupSettingsView(); - - SettingsContent = _sntpLookupSettingsView; - break; - case SettingsViewName.WakeOnLAN: - _wakeOnLANSettingsView ??= new WakeOnLANSettingsView(); - - SettingsContent = _wakeOnLANSettingsView; - break; - /* - case SettingsViewName.Whois: - _whoisSettingsView ??= new WhoisSettingsView(); - - SettingsContent = _whoisSettingsView; - break; - */ - case SettingsViewName.BitCalculator: - _bitCalculatorSettingsView ??= new BitCalculatorSettingsView(); - - SettingsContent = _bitCalculatorSettingsView; - break; - } + case SettingsViewName.General: + _settingsGerneralView ??= new SettingsGeneralView(); + + SettingsContent = _settingsGerneralView; + break; + case SettingsViewName.Window: + _settingsWindowView ??= new SettingsWindowView(); + + SettingsContent = _settingsWindowView; + break; + case SettingsViewName.Appearance: + _settingsApperanceView ??= new SettingsAppearanceView(); + + SettingsContent = _settingsApperanceView; + break; + case SettingsViewName.Language: + _settingsLanguageView ??= new SettingsLanguageView(); + + SettingsContent = _settingsLanguageView; + break; + case SettingsViewName.Network: + _settingsNetworkView ??= new SettingsNetworkView(); + + SettingsContent = _settingsNetworkView; + break; + case SettingsViewName.Status: + _settingsStatusView ??= new SettingsStatusView(); + + SettingsContent = _settingsStatusView; + break; + case SettingsViewName.HotKeys: + _settingsHotKeysView ??= new SettingsHotKeysView(); + + SettingsContent = _settingsHotKeysView; + break; + case SettingsViewName.Autostart: + _settingsAutostartView ??= new SettingsAutostartView(); + + SettingsContent = _settingsAutostartView; + break; + case SettingsViewName.Update: + _settingsUpdateView ??= new SettingsUpdateView(); + + SettingsContent = _settingsUpdateView; + break; + case SettingsViewName.Settings: + _settingsSettingsView ??= new SettingsSettingsView(); + + // Save settings + _settingsSettingsView.OnVisible(); + + SettingsContent = _settingsSettingsView; + break; + case SettingsViewName.Profiles: + _settingsProfilesView ??= new SettingsProfilesView(); + + SettingsContent = _settingsProfilesView; + break; + case SettingsViewName.Dashboard: + _dashboardSettingsView ??= new DashboardSettingsView(); + + SettingsContent = _dashboardSettingsView; + break; + case SettingsViewName.IPScanner: + _ipScannerSettingsView ??= new IPScannerSettingsView(); + + SettingsContent = _ipScannerSettingsView; + break; + case SettingsViewName.PortScanner: + _portScannerSettingsView ??= new PortScannerSettingsView(); + + SettingsContent = _portScannerSettingsView; + break; + case SettingsViewName.PingMonitor: + _pingMonitorSettingsView ??= new PingMonitorSettingsView(); + + SettingsContent = _pingMonitorSettingsView; + break; + case SettingsViewName.Traceroute: + _tracerouteSettingsView ??= new TracerouteSettingsView(); + + SettingsContent = _tracerouteSettingsView; + break; + case SettingsViewName.DNSLookup: + _dnsLookupSettingsViewModel ??= new DNSLookupSettingsView(); + + SettingsContent = _dnsLookupSettingsViewModel; + break; + case SettingsViewName.RemoteDesktop: + _remoteDesktopSettingsView ??= new RemoteDesktopSettingsView(); + + SettingsContent = _remoteDesktopSettingsView; + break; + case SettingsViewName.PowerShell: + _powerShellSettingsView ??= new PowerShellSettingsView(); + + SettingsContent = _powerShellSettingsView; + break; + case SettingsViewName.PuTTY: + _puTTYSettingsView ??= new PuTTYSettingsView(); + + SettingsContent = _puTTYSettingsView; + break; + case SettingsViewName.AWSSessionManager: + _awsSessionManagerSettingsView ??= new AWSSessionManagerSettingsView(); + + SettingsContent = _awsSessionManagerSettingsView; + break; + case SettingsViewName.TigerVNC: + _tigerVNCSettingsView ??= new TigerVNCSettingsView(); + + SettingsContent = _tigerVNCSettingsView; + break; + case SettingsViewName.SNMP: + _snmpSettingsView ??= new SNMPSettingsView(); + + SettingsContent = _snmpSettingsView; + break; + case SettingsViewName.SNTPLookup: + _sntpLookupSettingsView ??= new SNTPLookupSettingsView(); + + SettingsContent = _sntpLookupSettingsView; + break; + case SettingsViewName.WakeOnLAN: + _wakeOnLANSettingsView ??= new WakeOnLANSettingsView(); + + SettingsContent = _wakeOnLANSettingsView; + break; + /* + case SettingsViewName.Whois: + _whoisSettingsView ??= new WhoisSettingsView(); + + SettingsContent = _whoisSettingsView; + break; + */ + case SettingsViewName.BitCalculator: + _bitCalculatorSettingsView ??= new BitCalculatorSettingsView(); + + SettingsContent = _bitCalculatorSettingsView; + break; } + } - public DocumentationIdentifier GetDocumentationIdentifier() + public DocumentationIdentifier GetDocumentationIdentifier() + { + return SelectedTabIndex switch { - return SelectedTabIndex switch - { - 0 => DocumentationManager.GetIdentifierBySettingsName(SelectedSettingsView.Name), - 1 => DocumentationIdentifier.Profiles, - _ => DocumentationIdentifier.Default, - }; - } - #endregion + 0 => DocumentationManager.GetIdentifierBySettingsName(SelectedSettingsView.Name), + 1 => DocumentationIdentifier.Profiles, + _ => DocumentationIdentifier.Default, + }; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SettingsWindowViewModel.cs b/Source/NETworkManager/ViewModels/SettingsWindowViewModel.cs index dc2cee1068..9d9da7caed 100644 --- a/Source/NETworkManager/ViewModels/SettingsWindowViewModel.cs +++ b/Source/NETworkManager/ViewModels/SettingsWindowViewModel.cs @@ -1,134 +1,133 @@ using NETworkManager.Settings; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SettingsWindowViewModel : ViewModelBase { - public class SettingsWindowViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private bool _minimizeInsteadOfTerminating; - public bool MinimizeInsteadOfTerminating + private bool _minimizeInsteadOfTerminating; + public bool MinimizeInsteadOfTerminating + { + get => _minimizeInsteadOfTerminating; + set { - get => _minimizeInsteadOfTerminating; - set - { - if (value == _minimizeInsteadOfTerminating) - return; - - if (!_isLoading) - SettingsManager.Current.Window_MinimizeInsteadOfTerminating = value; - - _minimizeInsteadOfTerminating = value; - OnPropertyChanged(); - } - } + if (value == _minimizeInsteadOfTerminating) + return; - private bool _minimizeToTrayInsteadOfTaskbar; - public bool MinimizeToTrayInsteadOfTaskbar - { - get => _minimizeToTrayInsteadOfTaskbar; - set - { - if (value == _minimizeToTrayInsteadOfTaskbar) - return; - - if (!_isLoading) - SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar = value; - - _minimizeToTrayInsteadOfTaskbar = value; - OnPropertyChanged(); - } + if (!_isLoading) + SettingsManager.Current.Window_MinimizeInsteadOfTerminating = value; + + _minimizeInsteadOfTerminating = value; + OnPropertyChanged(); } + } - private bool _confirmClose; - public bool ConfirmClose + private bool _minimizeToTrayInsteadOfTaskbar; + public bool MinimizeToTrayInsteadOfTaskbar + { + get => _minimizeToTrayInsteadOfTaskbar; + set { - get => _confirmClose; - set - { - if (value == _confirmClose) - return; - - if (!_isLoading) - SettingsManager.Current.Window_ConfirmClose = value; - - OnPropertyChanged(); - _confirmClose = value; - } + if (value == _minimizeToTrayInsteadOfTaskbar) + return; + + if (!_isLoading) + SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar = value; + + _minimizeToTrayInsteadOfTaskbar = value; + OnPropertyChanged(); } + } - private bool _multipleInstances; - public bool MultipleInstances + private bool _confirmClose; + public bool ConfirmClose + { + get => _confirmClose; + set { - get => _multipleInstances; - set - { - if (value == _multipleInstances) - return; - - if (!_isLoading) - SettingsManager.Current.Window_MultipleInstances = value; - - OnPropertyChanged(); - _multipleInstances = value; - } + if (value == _confirmClose) + return; + + if (!_isLoading) + SettingsManager.Current.Window_ConfirmClose = value; + + OnPropertyChanged(); + _confirmClose = value; } + } - private bool _alwaysShowIconInTray; - public bool AlwaysShowIconInTray + private bool _multipleInstances; + public bool MultipleInstances + { + get => _multipleInstances; + set { - get => _alwaysShowIconInTray; - set - { - if (value == _alwaysShowIconInTray) - return; - - if (!_isLoading) - SettingsManager.Current.TrayIcon_AlwaysShowIcon = value; - - _alwaysShowIconInTray = value; - OnPropertyChanged(); - } + if (value == _multipleInstances) + return; + + if (!_isLoading) + SettingsManager.Current.Window_MultipleInstances = value; + + OnPropertyChanged(); + _multipleInstances = value; } + } - private bool _splashScreenEnabled; - public bool SplashScreenEnabled + private bool _alwaysShowIconInTray; + public bool AlwaysShowIconInTray + { + get => _alwaysShowIconInTray; + set { - get => _splashScreenEnabled; - set - { - if (value == _splashScreenEnabled) - return; - - if (!_isLoading) - SettingsManager.Current.SplashScreen_Enabled = value; - - _splashScreenEnabled = value; - OnPropertyChanged(); - } + if (value == _alwaysShowIconInTray) + return; + + if (!_isLoading) + SettingsManager.Current.TrayIcon_AlwaysShowIcon = value; + + _alwaysShowIconInTray = value; + OnPropertyChanged(); } - #endregion + } - #region Constructor, LoadSettings - public SettingsWindowViewModel() + private bool _splashScreenEnabled; + public bool SplashScreenEnabled + { + get => _splashScreenEnabled; + set { - _isLoading = true; + if (value == _splashScreenEnabled) + return; - LoadSettings(); + if (!_isLoading) + SettingsManager.Current.SplashScreen_Enabled = value; - _isLoading = false; + _splashScreenEnabled = value; + OnPropertyChanged(); } + } + #endregion - private void LoadSettings() - { - MinimizeInsteadOfTerminating = SettingsManager.Current.Window_MinimizeInsteadOfTerminating; - ConfirmClose = SettingsManager.Current.Window_ConfirmClose; - MultipleInstances = SettingsManager.Current.Window_MultipleInstances; - MinimizeToTrayInsteadOfTaskbar = SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar; - AlwaysShowIconInTray = SettingsManager.Current.TrayIcon_AlwaysShowIcon; - SplashScreenEnabled = SettingsManager.Current.SplashScreen_Enabled; - } - #endregion + #region Constructor, LoadSettings + public SettingsWindowViewModel() + { + _isLoading = true; + + LoadSettings(); + + _isLoading = false; + } + + private void LoadSettings() + { + MinimizeInsteadOfTerminating = SettingsManager.Current.Window_MinimizeInsteadOfTerminating; + ConfirmClose = SettingsManager.Current.Window_ConfirmClose; + MultipleInstances = SettingsManager.Current.Window_MultipleInstances; + MinimizeToTrayInsteadOfTaskbar = SettingsManager.Current.Window_MinimizeToTrayInsteadOfTaskbar; + AlwaysShowIconInTray = SettingsManager.Current.TrayIcon_AlwaysShowIcon; + SplashScreenEnabled = SettingsManager.Current.SplashScreen_Enabled; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs index aba761f88d..7b7e4092c7 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorCalculatorViewModel.cs @@ -9,117 +9,116 @@ using MahApps.Metro.Controls; using NETworkManager.Models.Network; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SubnetCalculatorCalculatorViewModel : ViewModelBase { - public class SubnetCalculatorCalculatorViewModel : ViewModelBase + #region Variables + private string _subnet; + public string Subnet { - #region Variables - private string _subnet; - public string Subnet + get => _subnet; + set { - get => _subnet; - set - { - if (value == _subnet) - return; - - _subnet = value; - OnPropertyChanged(); - } + if (value == _subnet) + return; + + _subnet = value; + OnPropertyChanged(); } + } - public ICollectionView SubnetHistoryView { get; } + public ICollectionView SubnetHistoryView { get; } - private bool _isCalculationRunning; - public bool IsCalculationRunning + private bool _isCalculationRunning; + public bool IsCalculationRunning + { + get => _isCalculationRunning; + set { - get => _isCalculationRunning; - set - { - if (value == _isCalculationRunning) - return; - - _isCalculationRunning = value; - OnPropertyChanged(); - } + if (value == _isCalculationRunning) + return; + + _isCalculationRunning = value; + OnPropertyChanged(); } + } - private bool _isResultVisible; - public bool IsResultVisible + private bool _isResultVisible; + public bool IsResultVisible + { + get => _isResultVisible; + set { - get => _isResultVisible; - set - { - if (value == _isResultVisible) - return; + if (value == _isResultVisible) + return; - _isResultVisible = value; - OnPropertyChanged(); - } + _isResultVisible = value; + OnPropertyChanged(); } + } - private IPNetworkInfo _result; - public IPNetworkInfo Result + private IPNetworkInfo _result; + public IPNetworkInfo Result + { + get => _result; + set { - get => _result; - set - { - if(value== _result) - return; - - _result = value; - OnPropertyChanged(); - } - } - #endregion + if(value== _result) + return; - #region Constructor, load settings - public SubnetCalculatorCalculatorViewModel() - { - SubnetHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory); + _result = value; + OnPropertyChanged(); } - #endregion + } + #endregion + + #region Constructor, load settings + public SubnetCalculatorCalculatorViewModel() + { + SubnetHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory); + } + #endregion - #region ICommands - public ICommand CalculateCommand => new RelayCommand(p => CalcualateAction(), Calculate_CanExecute); + #region ICommands + public ICommand CalculateCommand => new RelayCommand(p => CalcualateAction(), Calculate_CanExecute); - private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void CalcualateAction() - { - Calculate(); - } - #endregion + private void CalcualateAction() + { + Calculate(); + } + #endregion - #region Methods - private void Calculate() - { - IsCalculationRunning = true; + #region Methods + private void Calculate() + { + IsCalculationRunning = true; - var subnet = Subnet.Trim(); + var subnet = Subnet.Trim(); - Result = new IPNetworkInfo(IPNetwork.Parse(subnet)); + Result = new IPNetworkInfo(IPNetwork.Parse(subnet)); - IsResultVisible = true; + IsResultVisible = true; - AddSubnetToHistory(subnet); + AddSubnetToHistory(subnet); - IsCalculationRunning = false; - } + IsCalculationRunning = false; + } - private void AddSubnetToHistory(string subnet) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); + private void AddSubnetToHistory(string subnet) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory.Clear(); - OnPropertyChanged(nameof(Subnet)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory.Clear(); + OnPropertyChanged(nameof(Subnet)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory.Add(x)); - } - #endregion + // Fill with the new items + list.ForEach(x => SettingsManager.Current.SubnetCalculator_Calculator_SubnetHistory.Add(x)); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorHostViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorHostViewModel.cs index 8e9d989596..f82bc04726 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorHostViewModel.cs @@ -1,22 +1,21 @@ -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SubnetCalculatorHostViewModel : ViewModelBase { - public class SubnetCalculatorHostViewModel : ViewModelBase - { - private bool _isViewActive = true; + private bool _isViewActive = true; - public SubnetCalculatorHostViewModel() - { + public SubnetCalculatorHostViewModel() + { - } + } - public void OnViewVisible() - { - _isViewActive = true; - } + public void OnViewVisible() + { + _isViewActive = true; + } - public void OnViewHide() - { - _isViewActive = false; - } + public void OnViewHide() + { + _isViewActive = false; } } diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs index 672ce6b513..8a6b7e6962 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs @@ -18,328 +18,327 @@ using NETworkManager.Views; using System.Text.RegularExpressions; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SubnetCalculatorSubnettingViewModel : ViewModelBase { - public class SubnetCalculatorSubnettingViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private string _subnet; - public string Subnet + private string _subnet; + public string Subnet + { + get => _subnet; + set { - get => _subnet; - set - { - if (value == _subnet) - return; + if (value == _subnet) + return; - _subnet = value; - OnPropertyChanged(); - } + _subnet = value; + OnPropertyChanged(); } + } - public ICollectionView SubnetHistoryView { get; } + public ICollectionView SubnetHistoryView { get; } - private string _newSubnetmaskOrCIDR; - public string NewSubnetmaskOrCIDR + private string _newSubnetmaskOrCIDR; + public string NewSubnetmaskOrCIDR + { + get => _newSubnetmaskOrCIDR; + set { - get => _newSubnetmaskOrCIDR; - set - { - if (value == _newSubnetmaskOrCIDR) - return; + if (value == _newSubnetmaskOrCIDR) + return; - _newSubnetmaskOrCIDR = value; - OnPropertyChanged(); - } + _newSubnetmaskOrCIDR = value; + OnPropertyChanged(); } + } - public ICollectionView NewSubnetmaskOrCIDRHistoryView { get; } + public ICollectionView NewSubnetmaskOrCIDRHistoryView { get; } - private bool _isCalculationRunning; - public bool IsCalculationRunning + private bool _isCalculationRunning; + public bool IsCalculationRunning + { + get => _isCalculationRunning; + set { - get => _isCalculationRunning; - set - { - if (value == _isCalculationRunning) - return; + if (value == _isCalculationRunning) + return; - _isCalculationRunning = value; - OnPropertyChanged(); - } + _isCalculationRunning = value; + OnPropertyChanged(); } + } - private bool _isResultVisible; - public bool IsResultVisible + private bool _isResultVisible; + public bool IsResultVisible + { + get => _isResultVisible; + set { - get => _isResultVisible; - set - { - if (value == _isResultVisible) - return; + if (value == _isResultVisible) + return; - _isResultVisible = value; - OnPropertyChanged(); - } + _isResultVisible = value; + OnPropertyChanged(); } + } - private ObservableCollection _subnetsResult = new(); - public ObservableCollection SubnetsResult + private ObservableCollection _subnetsResult = new(); + public ObservableCollection SubnetsResult + { + get => _subnetsResult; + set { - get => _subnetsResult; - set - { - if (value == _subnetsResult) - return; + if (value == _subnetsResult) + return; - _subnetsResult = value; - OnPropertyChanged(); - } + _subnetsResult = value; + OnPropertyChanged(); } + } - public ICollectionView SubnetsResultsView { get; } + public ICollectionView SubnetsResultsView { get; } - private IPNetworkInfo _selectedSubnetResult; - public IPNetworkInfo SelectedSubnetResult + private IPNetworkInfo _selectedSubnetResult; + public IPNetworkInfo SelectedSubnetResult + { + get => _selectedSubnetResult; + set { - get => _selectedSubnetResult; - set - { - if (value == _selectedSubnetResult) - return; + if (value == _selectedSubnetResult) + return; - _selectedSubnetResult = value; - OnPropertyChanged(); - } + _selectedSubnetResult = value; + OnPropertyChanged(); } + } - private IList _selectedSubnetResults = new ArrayList(); - public IList SelectedSubnetResults + private IList _selectedSubnetResults = new ArrayList(); + public IList SelectedSubnetResults + { + get => _selectedSubnetResults; + set { - get => _selectedSubnetResults; - set - { - if (Equals(value, _selectedSubnetResults)) - return; + if (Equals(value, _selectedSubnetResults)) + return; - _selectedSubnetResults = value; - OnPropertyChanged(); - } + _selectedSubnetResults = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public SubnetCalculatorSubnettingViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public SubnetCalculatorSubnettingViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - // Set collection view - SubnetHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory); - NewSubnetmaskOrCIDRHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory); + // Set collection view + SubnetHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory); + NewSubnetmaskOrCIDRHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory); - // Result view - SubnetsResultsView = CollectionViewSource.GetDefaultView(SubnetsResult); - } - #endregion + // Result view + SubnetsResultsView = CollectionViewSource.GetDefaultView(SubnetsResult); + } + #endregion - #region ICommands & Actions - public ICommand CalculateCommand => new RelayCommand(p => CalculateAction(), Calculate_CanExecute); + #region ICommands & Actions + public ICommand CalculateCommand => new RelayCommand(p => CalculateAction(), Calculate_CanExecute); - private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void CalculateAction() - { - Calculate(); - } + private void CalculateAction() + { + Calculate(); + } - public ICommand CopySelectedNetworkAddressCommand => new RelayCommand(p => CopySelectedNetworkAddressAction()); + public ICommand CopySelectedNetworkAddressCommand => new RelayCommand(p => CopySelectedNetworkAddressAction()); - private void CopySelectedNetworkAddressAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.Network.ToString()); - } + private void CopySelectedNetworkAddressAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.Network.ToString()); + } - public ICommand CopySelectedBroadcastCommand => new RelayCommand(p => CopySelectedBroadcastAction()); + public ICommand CopySelectedBroadcastCommand => new RelayCommand(p => CopySelectedBroadcastAction()); - private void CopySelectedBroadcastAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.Broadcast.ToString()); - } + private void CopySelectedBroadcastAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.Broadcast.ToString()); + } - public ICommand CopySelectedIPAddressesCommand => new RelayCommand(p => CopySelectedIPAddressesAction()); + public ICommand CopySelectedIPAddressesCommand => new RelayCommand(p => CopySelectedIPAddressesAction()); - private void CopySelectedIPAddressesAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.Total.ToString()); - } + private void CopySelectedIPAddressesAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.Total.ToString()); + } - public ICommand CopySelectedSubnetmaskCommand => new RelayCommand(p => CopySelectedSubnetmaskAction()); + public ICommand CopySelectedSubnetmaskCommand => new RelayCommand(p => CopySelectedSubnetmaskAction()); - private void CopySelectedSubnetmaskAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.Netmask.ToString()); - } + private void CopySelectedSubnetmaskAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.Netmask.ToString()); + } - public ICommand CopySelectedCIDRCommand => new RelayCommand(p => CopySelectedCIDRAction()); + public ICommand CopySelectedCIDRCommand => new RelayCommand(p => CopySelectedCIDRAction()); - private void CopySelectedCIDRAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.Cidr.ToString()); - } + private void CopySelectedCIDRAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.Cidr.ToString()); + } - public ICommand CopySelectedFirstIPAddressCommand => new RelayCommand(p => CopySelectedFirstIPAddressAction()); + public ICommand CopySelectedFirstIPAddressCommand => new RelayCommand(p => CopySelectedFirstIPAddressAction()); - private void CopySelectedFirstIPAddressAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.FirstUsable.ToString()); - } + private void CopySelectedFirstIPAddressAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.FirstUsable.ToString()); + } - public ICommand CopySelectedLastIPAddressCommand => new RelayCommand(p => CopySelectedLastIPAddressAction()); + public ICommand CopySelectedLastIPAddressCommand => new RelayCommand(p => CopySelectedLastIPAddressAction()); - private void CopySelectedLastIPAddressAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.LastUsable.ToString()); - } + private void CopySelectedLastIPAddressAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.LastUsable.ToString()); + } - public ICommand CopySelectedHostCommand => new RelayCommand(p => CopySelectedHostAction()); + public ICommand CopySelectedHostCommand => new RelayCommand(p => CopySelectedHostAction()); - private void CopySelectedHostAction() - { - ClipboardHelper.SetClipboard(SelectedSubnetResult.Usable.ToString()); - } + private void CopySelectedHostAction() + { + ClipboardHelper.SetClipboard(SelectedSubnetResult.Usable.ToString()); + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private async Task ExportAction() + private async Task ExportAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + Title = Localization.Resources.Strings.Export + }; - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? SubnetsResult : new ObservableCollection(SelectedSubnetResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + try + { + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? SubnetsResult : new ObservableCollection(SelectedSubnetResults.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - SettingsManager.Current.SubnetCalculator_Subnetting_ExportFileType = instance.FileType; - SettingsManager.Current.SubnetCalculator_Subnetting_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.SubnetCalculator_Subnetting_ExportFileType, SettingsManager.Current.SubnetCalculator_Subnetting_ExportFilePath); + SettingsManager.Current.SubnetCalculator_Subnetting_ExportFileType = instance.FileType; + SettingsManager.Current.SubnetCalculator_Subnetting_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.SubnetCalculator_Subnetting_ExportFileType, SettingsManager.Current.SubnetCalculator_Subnetting_ExportFilePath); - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - #region Methods - private async Task Calculate() - { - IsCalculationRunning = true; + #region Methods + private async Task Calculate() + { + IsCalculationRunning = true; - SubnetsResult.Clear(); + SubnetsResult.Clear(); - var subnet = Subnet.Trim(); - var newSubnetmaskOrCidr = NewSubnetmaskOrCIDR.Trim(); + var subnet = Subnet.Trim(); + var newSubnetmaskOrCidr = NewSubnetmaskOrCIDR.Trim(); - var ipNetwork = IPNetwork.Parse(Subnet.Trim()); + var ipNetwork = IPNetwork.Parse(Subnet.Trim()); - byte newCidr = 0; + byte newCidr = 0; - // Support subnetmask like 255.255.255.0 - if (Regex.IsMatch(newSubnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) - newCidr = Convert.ToByte(Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(newSubnetmaskOrCidr))); - else - newCidr = Convert.ToByte(newSubnetmaskOrCidr.TrimStart('/')); + // Support subnetmask like 255.255.255.0 + if (Regex.IsMatch(newSubnetmaskOrCidr, RegexHelper.SubnetmaskRegex)) + newCidr = Convert.ToByte(Subnetmask.ConvertSubnetmaskToCidr(IPAddress.Parse(newSubnetmaskOrCidr))); + else + newCidr = Convert.ToByte(newSubnetmaskOrCidr.TrimStart('/')); - // Ask the user if there is a large calculation... - var baseCidr = ipNetwork.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128; + // Ask the user if there is a large calculation... + var baseCidr = ipNetwork.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ? 32 : 128; - if (65535 < Math.Pow(2, baseCidr - ipNetwork.Cidr) / Math.Pow(2, (baseCidr - newCidr))) - { - var settings = AppearanceManager.MetroDialog; + if (65535 < Math.Pow(2, baseCidr - ipNetwork.Cidr) / Math.Pow(2, (baseCidr - newCidr))) + { + var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.Continue; - settings.NegativeButtonText = Localization.Resources.Strings.Cancel; + settings.AffirmativeButtonText = Localization.Resources.Strings.Continue; + settings.NegativeButtonText = Localization.Resources.Strings.Cancel; - settings.DefaultButtonFocus = MessageDialogResult.Affirmative; + settings.DefaultButtonFocus = MessageDialogResult.Affirmative; - if (await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.AreYouSure, Localization.Resources.Strings.TheProcessCanTakeUpSomeTimeAndResources, MessageDialogStyle.AffirmativeAndNegative, settings) != MessageDialogResult.Affirmative) - { - IsCalculationRunning = false; + if (await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.AreYouSure, Localization.Resources.Strings.TheProcessCanTakeUpSomeTimeAndResources, MessageDialogStyle.AffirmativeAndNegative, settings) != MessageDialogResult.Affirmative) + { + IsCalculationRunning = false; - return; - } + return; } + } - // This still slows the application / freezes the ui... there are to many updates to the ui thread... - await Task.Run(() => + // This still slows the application / freezes the ui... there are to many updates to the ui thread... + await Task.Run(() => + { + foreach (var network in ipNetwork.Subnet(newCidr)) { - foreach (var network in ipNetwork.Subnet(newCidr)) - { - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - SubnetsResult.Add(new IPNetworkInfo(network)); - })); - } - }); + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate + { + SubnetsResult.Add(new IPNetworkInfo(network)); + })); + } + }); - IsResultVisible = true; + IsResultVisible = true; - AddSubnetToHistory(subnet); - AddNewSubnetmaskOrCIDRToHistory(newSubnetmaskOrCidr); + AddSubnetToHistory(subnet); + AddNewSubnetmaskOrCIDRToHistory(newSubnetmaskOrCidr); - IsCalculationRunning = false; - } + IsCalculationRunning = false; + } - private void AddSubnetToHistory(string subnet) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); + private void AddSubnetToHistory(string subnet) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory.Clear(); - OnPropertyChanged(nameof(Subnet)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory.Clear(); + OnPropertyChanged(nameof(Subnet)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.SubnetCalculator_Subnetting_SubnetHistory.Add(x)); + } - private void AddNewSubnetmaskOrCIDRToHistory(string newSubnetmaskOrCIDR) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.ToList(), newSubnetmaskOrCIDR, SettingsManager.Current.General_HistoryListEntries); + private void AddNewSubnetmaskOrCIDRToHistory(string newSubnetmaskOrCIDR) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.ToList(), newSubnetmaskOrCIDR, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.Clear(); - OnPropertyChanged(nameof(NewSubnetmaskOrCIDR)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.Clear(); + OnPropertyChanged(nameof(NewSubnetmaskOrCIDR)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.SubnetCalculator_Subnetting_NewSubnetmaskOrCIDRHistory.Add(x)); + } - public void OnShutdown() - { + public void OnShutdown() + { - } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs index feab10871f..2f3c5ee75c 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorWideSubnetViewModel.cs @@ -10,162 +10,161 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.Models.Network; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class SubnetCalculatorWideSubnetViewModel : ViewModelBase { - public class SubnetCalculatorWideSubnetViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private string _subnet1; - public string Subnet1 + private string _subnet1; + public string Subnet1 + { + get => _subnet1; + set { - get => _subnet1; - set - { - if (value == _subnet1) - return; - - _subnet1 = value; - OnPropertyChanged(); - } + if (value == _subnet1) + return; + + _subnet1 = value; + OnPropertyChanged(); } + } - public ICollectionView Subnet1HistoryView { get; } + public ICollectionView Subnet1HistoryView { get; } - private string _subnet2; - public string Subnet2 + private string _subnet2; + public string Subnet2 + { + get => _subnet2; + set { - get => _subnet2; - set - { - if (value == _subnet2) - return; - - _subnet2 = value; - OnPropertyChanged(); - } + if (value == _subnet2) + return; + + _subnet2 = value; + OnPropertyChanged(); } + } - public ICollectionView Subnet2HistoryView { get; } + public ICollectionView Subnet2HistoryView { get; } - private bool _isCalculationRunning; - public bool IsCalculationRunning + private bool _isCalculationRunning; + public bool IsCalculationRunning + { + get => _isCalculationRunning; + set { - get => _isCalculationRunning; - set - { - if (value == _isCalculationRunning) - return; - - _isCalculationRunning = value; - OnPropertyChanged(); - } + if (value == _isCalculationRunning) + return; + + _isCalculationRunning = value; + OnPropertyChanged(); } + } - private bool _isResultVisible; - public bool IsResultVisible + private bool _isResultVisible; + public bool IsResultVisible + { + get => _isResultVisible; + set { - get => _isResultVisible; - set - { - if (value == _isResultVisible) - return; + if (value == _isResultVisible) + return; - _isResultVisible = value; - OnPropertyChanged(); - } + _isResultVisible = value; + OnPropertyChanged(); } + } - private IPNetworkInfo _result; - public IPNetworkInfo Result + private IPNetworkInfo _result; + public IPNetworkInfo Result + { + get => _result; + set { - get => _result; - set - { - if (value == _result) - return; - - _result = value; - OnPropertyChanged(); - } + if (value == _result) + return; + + _result = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public SubnetCalculatorWideSubnetViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public SubnetCalculatorWideSubnetViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - // Set collection view - Subnet1HistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1); - Subnet2HistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2); - } - #endregion + // Set collection view + Subnet1HistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1); + Subnet2HistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2); + } + #endregion - #region ICommands & Actions - public ICommand CalculateCommand => new RelayCommand(p => CalculateAction(), Calculate_CanExecute); + #region ICommands & Actions + public ICommand CalculateCommand => new RelayCommand(p => CalculateAction(), Calculate_CanExecute); - private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Calculate_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void CalculateAction() - { - Calculate(); - } - #endregion + private void CalculateAction() + { + Calculate(); + } + #endregion - #region Methods - private void Calculate() - { - IsCalculationRunning = true; + #region Methods + private void Calculate() + { + IsCalculationRunning = true; - var subnet1 = Subnet1.Trim(); - var subnet2 = Subnet2.Trim(); + var subnet1 = Subnet1.Trim(); + var subnet2 = Subnet2.Trim(); - var ipNetwork1 = IPNetwork.Parse(subnet1); - var ipNetwork2 = IPNetwork.Parse(subnet2); + var ipNetwork1 = IPNetwork.Parse(subnet1); + var ipNetwork2 = IPNetwork.Parse(subnet2); - Result = new IPNetworkInfo(IPNetwork.WideSubnet(new[] { ipNetwork1, ipNetwork2 })); + Result = new IPNetworkInfo(IPNetwork.WideSubnet(new[] { ipNetwork1, ipNetwork2 })); - IsResultVisible = true; + IsResultVisible = true; - AddSubnet1ToHistory(subnet1); - AddSubnet2ToHistory(subnet2); + AddSubnet1ToHistory(subnet1); + AddSubnet2ToHistory(subnet2); - IsCalculationRunning = false; - } + IsCalculationRunning = false; + } - private void AddSubnet1ToHistory(string subnet) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); + private void AddSubnet1ToHistory(string subnet) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1.Clear(); - OnPropertyChanged(nameof(Subnet1)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1.Clear(); + OnPropertyChanged(nameof(Subnet1)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet1.Add(x)); + } - private void AddSubnet2ToHistory(string subnet) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); + private void AddSubnet2ToHistory(string subnet) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2.ToList(), subnet, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2.Clear(); - OnPropertyChanged(nameof(Subnet2)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2.Clear(); + OnPropertyChanged(nameof(Subnet2)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.SubnetCalculator_WideSubnet_Subnet2.Add(x)); + } - public void OnShutdown() - { + public void OnShutdown() + { - } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/TigerVNCConnectViewModel.cs b/Source/NETworkManager/ViewModels/TigerVNCConnectViewModel.cs index abbf3bf071..00970f69bf 100644 --- a/Source/NETworkManager/ViewModels/TigerVNCConnectViewModel.cs +++ b/Source/NETworkManager/ViewModels/TigerVNCConnectViewModel.cs @@ -6,62 +6,61 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class TigerVNCConnectViewModel : ViewModelBase { - public class TigerVNCConnectViewModel : ViewModelBase - { - public ICommand ConnectCommand { get; } - public ICommand CancelCommand { get; } + public ICommand ConnectCommand { get; } + public ICommand CancelCommand { get; } - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; + if (value == _host) + return; - _host = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } - - public ICollectionView HostHistoryView { get; } + } + + public ICollectionView HostHistoryView { get; } - private int _port; - public int Port + private int _port; + public int Port + { + get => _port; + set { - get => _port; - set - { - if (value == _port) - return; + if (value == _port) + return; - _port = value; - OnPropertyChanged(); - } + _port = value; + OnPropertyChanged(); } + } - public ICollectionView PortHistoryView { get; } - - public TigerVNCConnectViewModel(Action connectCommand, Action cancelHandler, string host = null) - { - ConnectCommand = new RelayCommand(p => connectCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + public ICollectionView PortHistoryView { get; } + + public TigerVNCConnectViewModel(Action connectCommand, Action cancelHandler, string host = null) + { + ConnectCommand = new RelayCommand(p => connectCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - if (!string.IsNullOrEmpty(host)) - Host = host; - - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.TigerVNC_HostHistory); - PortHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.TigerVNC_PortHistory); + if (!string.IsNullOrEmpty(host)) + Host = host; + + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.TigerVNC_HostHistory); + PortHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.TigerVNC_PortHistory); - LoadSettings(); - } + LoadSettings(); + } - private void LoadSettings() - { - Port = SettingsManager.Current.TigerVNC_Port; - } + private void LoadSettings() + { + Port = SettingsManager.Current.TigerVNC_Port; } } diff --git a/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs b/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs index f0ad5e0e44..93c7beec88 100644 --- a/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/TigerVNCHostViewModel.cs @@ -21,494 +21,493 @@ using System.Threading.Tasks; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class TigerVNCHostViewModel : ViewModelBase, IProfileManager { - public class TigerVNCHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private bool _isConfigured; - public bool IsConfigured + private bool _isConfigured; + public bool IsConfigured + { + get => _isConfigured; + set { - get => _isConfigured; - set - { - if (value == _isConfigured) - return; + if (value == _isConfigured) + return; - _isConfigured = value; - OnPropertyChanged(); - } + _isConfigured = value; + OnPropertyChanged(); } + } - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } + } - #region Profiles + #region Profiles - public ICollectionView Profiles { get; } + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.TigerVNC_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.TigerVNC_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.TigerVNC_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.TigerVNC_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public TigerVNCHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public TigerVNCHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - CheckSettings(); + CheckSettings(); - InterTabClient = new DragablzInterTabClient(ApplicationName.TigerVNC); + InterTabClient = new DragablzInterTabClient(ApplicationName.TigerVNC); - TabItems = new ObservableCollection(); + TabItems = new ObservableCollection(); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.TigerVNC_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.TigerVNC_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.TigerVNC_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.TigerVNC_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, TigerVNC_Host - return info.TigerVNC_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.TigerVNC_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, TigerVNC_Host + return info.TigerVNC_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.TigerVNC_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.TigerVNC_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.TigerVNC_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += Current_PropertyChanged; + SettingsManager.Current.PropertyChanged += Current_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - if (e.PropertyName == nameof(SettingsInfo.TigerVNC_ApplicationFilePath)) - CheckSettings(); - } + private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(SettingsInfo.TigerVNC_ApplicationFilePath)) + CheckSettings(); + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.TigerVNC_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.TigerVNC_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.TigerVNC_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.TigerVNC_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.TigerVNC_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.TigerVNC_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ItemActionCallback CloseItemCommand => CloseItemAction; + #region ICommand & Actions + public ItemActionCallback CloseItemCommand => CloseItemAction; - private void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as TigerVNCControl)?.CloseTab(); - } + private void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as TigerVNCControl)?.CloseTab(); + } - public ICommand TigerVNC_ReconnectCommand => new RelayCommand(TigerVNC_ReconnectAction); + public ICommand TigerVNC_ReconnectCommand => new RelayCommand(TigerVNC_ReconnectAction); - private void TigerVNC_ReconnectAction(object view) + private void TigerVNC_ReconnectAction(object view) + { + if (view is TigerVNCControl control) { - if (view is TigerVNCControl control) - { - if (control.ReconnectCommand.CanExecute(null)) - control.ReconnectCommand.Execute(null); - } + if (control.ReconnectCommand.CanExecute(null)) + control.ReconnectCommand.Execute(null); } + } - public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); + public ICommand ConnectCommand => new RelayCommand(p => ConnectAction(), Connect_CanExecute); - private bool Connect_CanExecute(object obj) => IsConfigured; + private bool Connect_CanExecute(object obj) => IsConfigured; - private void ConnectAction() - { - Connect(); - } + private void ConnectAction() + { + Connect(); + } - public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); + public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); - private bool ConnectProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool ConnectProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ConnectProfileAction() - { - ConnectProfile(); - } + private void ConnectProfileAction() + { + ConnectProfile(); + } - public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); + public ICommand ConnectProfileExternalCommand => new RelayCommand(p => ConnectProfileExternalAction()); - private void ConnectProfileExternalAction() - { - ConnectProfileExternal(); - } + private void ConnectProfileExternalAction() + { + ConnectProfileExternal(); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.TigerVNC); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.TigerVNC); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); + public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); - private static void OpenSettingsAction() - { - EventSystem.RedirectToSettings(); - } - #endregion + private static void OpenSettingsAction() + { + EventSystem.RedirectToSettings(); + } + #endregion + + #region Methods + private void CheckSettings() + { + IsConfigured = !string.IsNullOrEmpty(SettingsManager.Current.TigerVNC_ApplicationFilePath) && File.Exists(SettingsManager.Current.TigerVNC_ApplicationFilePath); + } - #region Methods - private void CheckSettings() + private async Task Connect(string host = null) + { + var customDialog = new CustomDialog { - IsConfigured = !string.IsNullOrEmpty(SettingsManager.Current.TigerVNC_ApplicationFilePath) && File.Exists(SettingsManager.Current.TigerVNC_ApplicationFilePath); - } + Title = Localization.Resources.Strings.Connect + }; - private async Task Connect(string host = null) + var connectViewModel = new TigerVNCConnectViewModel(async instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Connect - }; + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - var connectViewModel = new TigerVNCConnectViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - - // Create profile info - var info = new TigerVNCSessionInfo - { - Host = instance.Host, - Port = instance.Port - }; - - // Add to history - // Note: The history can only be updated after the values have been read. - // Otherwise, in some cases, incorrect values are taken over. - AddHostToHistory(instance.Host); - AddPortToHistory(instance.Port); - - // Connect - Connect(info); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - }, host); - - customDialog.Content = new TigerVNCConnectDialog + // Create profile info + var info = new TigerVNCSessionInfo { - DataContext = connectViewModel + Host = instance.Host, + Port = instance.Port }; - ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + // Add to history + // Note: The history can only be updated after the values have been read. + // Otherwise, in some cases, incorrect values are taken over. + AddHostToHistory(instance.Host); + AddPortToHistory(instance.Port); - private void ConnectProfile() - { - Connect(NETworkManager.Profiles.Application.TigerVNC.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); - } + // Connect + Connect(info); + }, async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; + }, host); - private void ConnectProfileExternal() + customDialog.Content = new TigerVNCConnectDialog { - Process.Start(new ProcessStartInfo() - { - FileName = SettingsManager.Current.TigerVNC_ApplicationFilePath, - Arguments = TigerVNC.BuildCommandLine(NETworkManager.Profiles.Application.TigerVNC.CreateSessionInfo(SelectedProfile)) - }); - } + DataContext = connectViewModel + }; + + ConfigurationManager.Current.IsDialogOpen = true; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - private void Connect(TigerVNCSessionInfo sessionInfo, string header = null) + private void ConnectProfile() + { + Connect(NETworkManager.Profiles.Application.TigerVNC.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); + } + + private void ConnectProfileExternal() + { + Process.Start(new ProcessStartInfo() { - sessionInfo.ApplicationFilePath = SettingsManager.Current.TigerVNC_ApplicationFilePath; + FileName = SettingsManager.Current.TigerVNC_ApplicationFilePath, + Arguments = TigerVNC.BuildCommandLine(NETworkManager.Profiles.Application.TigerVNC.CreateSessionInfo(SelectedProfile)) + }); + } - TabItems.Add(new DragablzTabItem(header ?? sessionInfo.Host, new TigerVNCControl(sessionInfo))); + private void Connect(TigerVNCSessionInfo sessionInfo, string header = null) + { + sessionInfo.ApplicationFilePath = SettingsManager.Current.TigerVNC_ApplicationFilePath; - SelectedTabIndex = TabItems.Count - 1; - } + TabItems.Add(new DragablzTabItem(header ?? sessionInfo.Host, new TigerVNCControl(sessionInfo))); - public void AddTab(string host) - { - Connect(host); - } + SelectedTabIndex = TabItems.Count - 1; + } - // Modify history list - private static void AddHostToHistory(string host) - { - if (string.IsNullOrEmpty(host)) - return; + public void AddTab(string host) + { + Connect(host); + } - SettingsManager.Current.TigerVNC_HostHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.TigerVNC_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); - } + // Modify history list + private static void AddHostToHistory(string host) + { + if (string.IsNullOrEmpty(host)) + return; - private static void AddPortToHistory(int port) - { - if (port == 0) - return; + SettingsManager.Current.TigerVNC_HostHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.TigerVNC_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries)); + } - SettingsManager.Current.TigerVNC_PortHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.TigerVNC_PortHistory.ToList(), port, SettingsManager.Current.General_HistoryListEntries)); - } + private static void AddPortToHistory(int port) + { + if (port == 0) + return; + + SettingsManager.Current.TigerVNC_PortHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.TigerVNC_PortHistory.ToList(), port, SettingsManager.Current.General_HistoryListEntries)); + } - private void StartDelayedSearch() + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void OnViewVisible() - { - _isViewActive = true; + _canProfileWidthChange = true; + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - ConfigurationManager.Current.IsDialogOpen = true; - } + Profiles.Refresh(); + })); + } - public void OnProfileDialogClose() - { - ConfigurationManager.Current.IsDialogOpen = false; - } - #endregion + public void OnProfileDialogOpen() + { + ConfigurationManager.Current.IsDialogOpen = true; + } - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + public void OnProfileDialogClose() + { + ConfigurationManager.Current.IsDialogOpen = false; + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/TigerVNCSettingsViewModel.cs b/Source/NETworkManager/ViewModels/TigerVNCSettingsViewModel.cs index 92a7000111..1ef94d002a 100644 --- a/Source/NETworkManager/ViewModels/TigerVNCSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/TigerVNCSettingsViewModel.cs @@ -8,131 +8,130 @@ using System.Threading.Tasks; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class TigerVNCSettingsViewModel : ViewModelBase { - public class TigerVNCSettingsViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - - private readonly bool _isLoading; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + + private readonly bool _isLoading; - private string _applicationFilePath; - public string ApplicationFilePath + private string _applicationFilePath; + public string ApplicationFilePath + { + get => _applicationFilePath; + set { - get => _applicationFilePath; - set - { - if (value == _applicationFilePath) - return; + if (value == _applicationFilePath) + return; - if (!_isLoading) - SettingsManager.Current.TigerVNC_ApplicationFilePath = value; + if (!_isLoading) + SettingsManager.Current.TigerVNC_ApplicationFilePath = value; - IsConfigured = !string.IsNullOrEmpty(value); + IsConfigured = !string.IsNullOrEmpty(value); - _applicationFilePath = value; - OnPropertyChanged(); - } + _applicationFilePath = value; + OnPropertyChanged(); } + } - private bool _isConfigured; - public bool IsConfigured + private bool _isConfigured; + public bool IsConfigured + { + get => _isConfigured; + set { - get => _isConfigured; - set - { - if (value == _isConfigured) - return; - - _isConfigured = value; - OnPropertyChanged(); - } + if (value == _isConfigured) + return; + + _isConfigured = value; + OnPropertyChanged(); } - - private int _port; - public int Port + } + + private int _port; + public int Port + { + get => _port; + set { - get => _port; - set - { - if (value == _port) - return; - - if (!_isLoading) - SettingsManager.Current.TigerVNC_Port = value; - - _port = value; - OnPropertyChanged(); - } + if (value == _port) + return; + + if (!_isLoading) + SettingsManager.Current.TigerVNC_Port = value; + + _port = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public TigerVNCSettingsViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Contructor, load settings + public TigerVNCSettingsViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ApplicationFilePath = SettingsManager.Current.TigerVNC_ApplicationFilePath; - IsConfigured = File.Exists(ApplicationFilePath); - Port = SettingsManager.Current.TigerVNC_Port; - } - #endregion + private void LoadSettings() + { + ApplicationFilePath = SettingsManager.Current.TigerVNC_ApplicationFilePath; + IsConfigured = File.Exists(ApplicationFilePath); + Port = SettingsManager.Current.TigerVNC_Port; + } + #endregion - #region ICommands & Actions - public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); + #region ICommands & Actions + public ICommand BrowseFileCommand => new RelayCommand(p => BrowseFileAction()); - private void BrowseFileAction() + private void BrowseFileAction() + { + var openFileDialog = new System.Windows.Forms.OpenFileDialog { - var openFileDialog = new System.Windows.Forms.OpenFileDialog - { - Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter - }; + Filter = GlobalStaticConfiguration.ApplicationFileExtensionFilter + }; - if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) - ApplicationFilePath = openFileDialog.FileName; - } + if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) + ApplicationFilePath = openFileDialog.FileName; + } - public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); + public ICommand ConfigureCommand => new RelayCommand(p => ConfigureAction()); - private void ConfigureAction() - { - Configure(); - } - #endregion + private void ConfigureAction() + { + Configure(); + } + #endregion - #region Methods - private async Task Configure() + #region Methods + private async Task Configure() + { + try { - try - { - Process.Start(SettingsManager.Current.TigerVNC_ApplicationFilePath); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); - } + Process.Start(SettingsManager.Current.TigerVNC_ApplicationFilePath); } - - public void SetFilePathFromDragDrop(string filePath) + catch (Exception ex) { - ApplicationFilePath = filePath; + var settings = AppearanceManager.MetroDialog; + + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - OnPropertyChanged(nameof(ApplicationFilePath)); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, ex.Message, MessageDialogStyle.Affirmative, settings); } - #endregion } + + public void SetFilePathFromDragDrop(string filePath) + { + ApplicationFilePath = filePath; + + OnPropertyChanged(nameof(ApplicationFilePath)); + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs index dbc13d0ef5..87b1370796 100644 --- a/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteHostViewModel.cs @@ -16,369 +16,368 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class TracerouteHostViewModel : ViewModelBase, IProfileManager { - public class TracerouteHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private int _tabId; + private int _tabId; - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } - - #region Profiles - public ICollectionView Profiles { get; } + } + + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.Traceroute_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.Traceroute_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.Traceroute_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.Traceroute_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion - - #region Constructor, load settings - public TracerouteHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + } + #endregion + #endregion + + #region Constructor, load settings + public TracerouteHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - InterTabClient = new DragablzInterTabClient(ApplicationName.Traceroute); + InterTabClient = new DragablzInterTabClient(ApplicationName.Traceroute); - TabItems = new ObservableCollection - { - new DragablzTabItem(Localization.Resources.Strings.NewTab, new TracerouteView(_tabId), _tabId) - }; - - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + TabItems = new ObservableCollection + { + new DragablzTabItem(Localization.Resources.Strings.NewTab, new TracerouteView(_tabId), _tabId) + }; + + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.Traceroute_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.Traceroute_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.Traceroute_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.Traceroute_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, Traceroute_Host - return info.Traceroute_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.Traceroute_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, Traceroute_Host + return info.Traceroute_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.Traceroute_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.Traceroute_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.Traceroute_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.Traceroute_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.Traceroute_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.Traceroute_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.Traceroute_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.Traceroute_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.Traceroute_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); + #region ICommand & Actions + public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); - private void AddTabAction() - { - AddTab(); - } + private void AddTabAction() + { + AddTab(); + } - public ICommand TraceProfileCommand => new RelayCommand(p => TraceProfileAction(), TraceProfile_CanExecute); + public ICommand TraceProfileCommand => new RelayCommand(p => TraceProfileAction(), TraceProfile_CanExecute); - private bool TraceProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool TraceProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void TraceProfileAction() - { - AddTab(SelectedProfile); - } + private void TraceProfileAction() + { + AddTab(SelectedProfile); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.Traceroute); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.Traceroute); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ItemActionCallback CloseItemCommand => CloseItemAction; + public ItemActionCallback CloseItemCommand => CloseItemAction; - public void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as TracerouteView)?.CloseTab(); - } - #endregion + public void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as TracerouteView)?.CloseTab(); + } + #endregion - #region Methods - private void StartDelayedSearch() + #region Methods + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } - if (dueToChangedSize) + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; + + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void AddTab(string host = null) - { - _tabId++; + _canProfileWidthChange = true; + } - TabItems.Add(new DragablzTabItem(host ?? Localization.Resources.Strings.NewTab, new TracerouteView(_tabId, host), _tabId)); + public void AddTab(string host = null) + { + _tabId++; - SelectedTabIndex = TabItems.Count - 1; - } + TabItems.Add(new DragablzTabItem(host ?? Localization.Resources.Strings.NewTab, new TracerouteView(_tabId, host), _tabId)); - public void AddTab(ProfileInfo profile) - { - AddTab(profile.Traceroute_Host); - } + SelectedTabIndex = TabItems.Count - 1; + } - public void OnViewVisible() - { - _isViewActive = true; + public void AddTab(ProfileInfo profile) + { + AddTab(profile.Traceroute_Host); + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Profiles.Refresh(); + })); + } - } + public void OnProfileDialogOpen() + { - public void OnProfileDialogClose() - { + } - } - #endregion + public void OnProfileDialogClose() + { - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/TracerouteSettingsViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteSettingsViewModel.cs index 1ac602a35f..ce7f1b165f 100644 --- a/Source/NETworkManager/ViewModels/TracerouteSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteSettingsViewModel.cs @@ -1,98 +1,97 @@ using NETworkManager.Settings; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class TracerouteSettingsViewModel : ViewModelBase { - public class TracerouteSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private int _maximumHops; - public int MaximumHops + private int _maximumHops; + public int MaximumHops + { + get => _maximumHops; + set { - get => _maximumHops; - set - { - if (value == _maximumHops) - return; - - if (!_isLoading) - SettingsManager.Current.Traceroute_MaximumHops = value; - - _maximumHops = value; - OnPropertyChanged(); - } - } + if (value == _maximumHops) + return; - private int _timeout; - public int Timeout - { - get => _timeout; - set - { - if (value == _timeout) - return; - - if (!_isLoading) - SettingsManager.Current.Traceroute_Timeout = value; - - _timeout = value; - OnPropertyChanged(); - } - } + if (!_isLoading) + SettingsManager.Current.Traceroute_MaximumHops = value; - private int _buffer; - public int Buffer - { - get => _buffer; - set - { - if (value == _buffer) - return; - - if (!_isLoading) - SettingsManager.Current.Traceroute_Buffer = value; - - _buffer = value; - OnPropertyChanged(); - } + _maximumHops = value; + OnPropertyChanged(); } + } - private bool _resolveHostname; - public bool ResolveHostname + private int _timeout; + public int Timeout + { + get => _timeout; + set { - get => _resolveHostname; - set - { - if (value == _resolveHostname) - return; - - if (!_isLoading) - SettingsManager.Current.Traceroute_ResolveHostname = value; - - _resolveHostname = value; - OnPropertyChanged(); - } + if (value == _timeout) + return; + + if (!_isLoading) + SettingsManager.Current.Traceroute_Timeout = value; + + _timeout = value; + OnPropertyChanged(); } - #endregion + } - #region Constructor, load settings - public TracerouteSettingsViewModel() + private int _buffer; + public int Buffer + { + get => _buffer; + set { - _isLoading = true; + if (value == _buffer) + return; - LoadSettings(); + if (!_isLoading) + SettingsManager.Current.Traceroute_Buffer = value; - _isLoading = false; + _buffer = value; + OnPropertyChanged(); } + } - private void LoadSettings() + private bool _resolveHostname; + public bool ResolveHostname + { + get => _resolveHostname; + set { - MaximumHops = SettingsManager.Current.Traceroute_MaximumHops; - Timeout = SettingsManager.Current.Traceroute_Timeout; - Buffer = SettingsManager.Current.Traceroute_Buffer; - ResolveHostname = SettingsManager.Current.Traceroute_ResolveHostname; + if (value == _resolveHostname) + return; + + if (!_isLoading) + SettingsManager.Current.Traceroute_ResolveHostname = value; + + _resolveHostname = value; + OnPropertyChanged(); } - #endregion } + #endregion + + #region Constructor, load settings + public TracerouteSettingsViewModel() + { + _isLoading = true; + + LoadSettings(); + + _isLoading = false; + } + + private void LoadSettings() + { + MaximumHops = SettingsManager.Current.Traceroute_MaximumHops; + Timeout = SettingsManager.Current.Traceroute_Timeout; + Buffer = SettingsManager.Current.Traceroute_Buffer; + ResolveHostname = SettingsManager.Current.Traceroute_ResolveHostname; + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs index 88db67d9c0..612618e5f6 100644 --- a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs @@ -23,455 +23,454 @@ using NETworkManager.Models.EventSystem; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class TracerouteViewModel : ViewModelBase { - public class TracerouteViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private CancellationTokenSource _cancellationTokenSource; + private CancellationTokenSource _cancellationTokenSource; - public readonly int TabId; - private bool _firstLoad = true; + public readonly int TabId; + private bool _firstLoad = true; - private readonly bool _isLoading; + private readonly bool _isLoading; - private string _host; - public string Host + private string _host; + public string Host + { + get => _host; + set { - get => _host; - set - { - if (value == _host) - return; + if (value == _host) + return; - _host = value; - OnPropertyChanged(); - } + _host = value; + OnPropertyChanged(); } + } - public ICollectionView HostHistoryView { get; } + public ICollectionView HostHistoryView { get; } - private bool _isRunning; - public bool IsRunning + private bool _isRunning; + public bool IsRunning + { + get => _isRunning; + set { - get => _isRunning; - set - { - if (value == _isRunning) - return; + if (value == _isRunning) + return; - _isRunning = value; - OnPropertyChanged(); - } + _isRunning = value; + OnPropertyChanged(); } + } - private bool _cancelTrace; - public bool CancelTrace + private bool _cancelTrace; + public bool CancelTrace + { + get => _cancelTrace; + set { - get => _cancelTrace; - set - { - if (value == _cancelTrace) - return; + if (value == _cancelTrace) + return; - _cancelTrace = value; - OnPropertyChanged(); - } + _cancelTrace = value; + OnPropertyChanged(); } + } - private ObservableCollection _traceResults = new ObservableCollection(); - public ObservableCollection TraceResults + private ObservableCollection _traceResults = new ObservableCollection(); + public ObservableCollection TraceResults + { + get => _traceResults; + set { - get => _traceResults; - set - { - if (Equals(value, _traceResults)) - return; + if (Equals(value, _traceResults)) + return; - _traceResults = value; - } + _traceResults = value; } + } - public ICollectionView TraceResultsView { get; } + public ICollectionView TraceResultsView { get; } - private TracerouteHopInfo _selectedTraceResult; - public TracerouteHopInfo SelectedTraceResult + private TracerouteHopInfo _selectedTraceResult; + public TracerouteHopInfo SelectedTraceResult + { + get => _selectedTraceResult; + set { - get => _selectedTraceResult; - set - { - if (value == _selectedTraceResult) - return; + if (value == _selectedTraceResult) + return; - _selectedTraceResult = value; - OnPropertyChanged(); - } + _selectedTraceResult = value; + OnPropertyChanged(); } + } - private IList _selectedTraceResults = new ArrayList(); - public IList SelectedTraceResults + private IList _selectedTraceResults = new ArrayList(); + public IList SelectedTraceResults + { + get => _selectedTraceResults; + set { - get => _selectedTraceResults; - set - { - if (Equals(value, _selectedTraceResults)) - return; + if (Equals(value, _selectedTraceResults)) + return; - _selectedTraceResults = value; - OnPropertyChanged(); - } + _selectedTraceResults = value; + OnPropertyChanged(); } + } - public bool ResolveHostname => SettingsManager.Current.Traceroute_ResolveHostname; + public bool ResolveHostname => SettingsManager.Current.Traceroute_ResolveHostname; - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public TracerouteViewModel(IDialogCoordinator instance, int tabId, string host) - { - _isLoading = true; + #region Constructor, load settings + public TracerouteViewModel(IDialogCoordinator instance, int tabId, string host) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - TabId = tabId; - Host = host; + TabId = tabId; + Host = host; - // Set collection view - HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Traceroute_HostHistory); + // Set collection view + HostHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Traceroute_HostHistory); - // Result view - TraceResultsView = CollectionViewSource.GetDefaultView(TraceResults); - TraceResultsView.SortDescriptions.Add(new SortDescription(nameof(TracerouteHopInfo.Hop), ListSortDirection.Ascending)); + // Result view + TraceResultsView = CollectionViewSource.GetDefaultView(TraceResults); + TraceResultsView.SortDescriptions.Add(new SortDescription(nameof(TracerouteHopInfo.Hop), ListSortDirection.Ascending)); - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += Current_PropertyChanged; + SettingsManager.Current.PropertyChanged += Current_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - public void OnLoaded() - { - if (!_firstLoad) - return; + public void OnLoaded() + { + if (!_firstLoad) + return; - if (!string.IsNullOrEmpty(Host)) - StartTrace(); + if (!string.IsNullOrEmpty(Host)) + StartTrace(); - _firstLoad = false; - } + _firstLoad = false; + } - private void LoadSettings() - { + private void LoadSettings() + { - } - #endregion + } + #endregion - #region ICommands & Actions - public ICommand TraceCommand => new RelayCommand(p => TraceAction(), Trace_CanExecute); + #region ICommands & Actions + public ICommand TraceCommand => new RelayCommand(p => TraceAction(), Trace_CanExecute); - private bool Trace_CanExecute(object paramter) => System.Windows.Application.Current.MainWindow != null && !((MetroWindow)System.Windows.Application.Current.MainWindow).IsAnyDialogOpen; + private bool Trace_CanExecute(object paramter) => System.Windows.Application.Current.MainWindow != null && !((MetroWindow)System.Windows.Application.Current.MainWindow).IsAnyDialogOpen; - private void TraceAction() - { - if (IsRunning) - StopTrace(); - else - StartTrace(); - } + private void TraceAction() + { + if (IsRunning) + StopTrace(); + else + StartTrace(); + } - public ICommand RedirectDataToApplicationCommand => new RelayCommand(RedirectDataToApplicationAction); + public ICommand RedirectDataToApplicationCommand => new RelayCommand(RedirectDataToApplicationAction); - private void RedirectDataToApplicationAction(object name) - { - if (name is not string appName) - return; + private void RedirectDataToApplicationAction(object name) + { + if (name is not string appName) + return; - if (!Enum.TryParse(appName, out ApplicationName app)) - return; + if (!Enum.TryParse(appName, out ApplicationName app)) + return; - var host = !string.IsNullOrEmpty(SelectedTraceResult.Hostname) ? SelectedTraceResult.Hostname : SelectedTraceResult.IPAddress.ToString(); + var host = !string.IsNullOrEmpty(SelectedTraceResult.Hostname) ? SelectedTraceResult.Hostname : SelectedTraceResult.IPAddress.ToString(); - EventSystem.RedirectToApplication(app, host); - } + EventSystem.RedirectToApplication(app, host); + } - public ICommand PerformDNSLookupIPAddressCommand => new RelayCommand(p => PerformDNSLookupIPAddressAction()); + public ICommand PerformDNSLookupIPAddressCommand => new RelayCommand(p => PerformDNSLookupIPAddressAction()); - private void PerformDNSLookupIPAddressAction() - { - EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedTraceResult.IPAddress.ToString()); - } + private void PerformDNSLookupIPAddressAction() + { + EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedTraceResult.IPAddress.ToString()); + } - public ICommand PerformDNSLookupHostnameCommand => new RelayCommand(p => PerformDNSLookupHostnameAction()); + public ICommand PerformDNSLookupHostnameCommand => new RelayCommand(p => PerformDNSLookupHostnameAction()); - private void PerformDNSLookupHostnameAction() - { - EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedTraceResult.Hostname); - } + private void PerformDNSLookupHostnameAction() + { + EventSystem.RedirectToApplication(ApplicationName.DNSLookup, SelectedTraceResult.Hostname); + } - public ICommand CopySelectedHopCommand => new RelayCommand(p => CopySelectedHopAction()); + public ICommand CopySelectedHopCommand => new RelayCommand(p => CopySelectedHopAction()); - private void CopySelectedHopAction() - { - ClipboardHelper.SetClipboard(SelectedTraceResult.Hop.ToString()); - } + private void CopySelectedHopAction() + { + ClipboardHelper.SetClipboard(SelectedTraceResult.Hop.ToString()); + } - public ICommand CopySelectedTime1Command => new RelayCommand(p => CopySelectedTime1Action()); + public ICommand CopySelectedTime1Command => new RelayCommand(p => CopySelectedTime1Action()); - private void CopySelectedTime1Action() - { - ClipboardHelper.SetClipboard(SelectedTraceResult.Time1.ToString(CultureInfo.CurrentCulture)); - } + private void CopySelectedTime1Action() + { + ClipboardHelper.SetClipboard(SelectedTraceResult.Time1.ToString(CultureInfo.CurrentCulture)); + } - public ICommand CopySelectedTime2Command => new RelayCommand(p => CopySelectedTime2Action()); + public ICommand CopySelectedTime2Command => new RelayCommand(p => CopySelectedTime2Action()); - private void CopySelectedTime2Action() - { - ClipboardHelper.SetClipboard(SelectedTraceResult.Time2.ToString(CultureInfo.CurrentCulture)); - } + private void CopySelectedTime2Action() + { + ClipboardHelper.SetClipboard(SelectedTraceResult.Time2.ToString(CultureInfo.CurrentCulture)); + } - public ICommand CopySelectedTime3Command => new RelayCommand(p => CopySelectedTime3Action()); + public ICommand CopySelectedTime3Command => new RelayCommand(p => CopySelectedTime3Action()); - private void CopySelectedTime3Action() - { - ClipboardHelper.SetClipboard(SelectedTraceResult.Time3.ToString(CultureInfo.CurrentCulture)); - } + private void CopySelectedTime3Action() + { + ClipboardHelper.SetClipboard(SelectedTraceResult.Time3.ToString(CultureInfo.CurrentCulture)); + } - public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); + public ICommand CopySelectedIPAddressCommand => new RelayCommand(p => CopySelectedIPAddressAction()); - private void CopySelectedIPAddressAction() - { - ClipboardHelper.SetClipboard(SelectedTraceResult.IPAddress.ToString()); - } + private void CopySelectedIPAddressAction() + { + ClipboardHelper.SetClipboard(SelectedTraceResult.IPAddress.ToString()); + } - public ICommand CopySelectedHostnameCommand => new RelayCommand(p => CopySelectedHostnameAction()); + public ICommand CopySelectedHostnameCommand => new RelayCommand(p => CopySelectedHostnameAction()); - private void CopySelectedHostnameAction() - { - ClipboardHelper.SetClipboard(SelectedTraceResult.Hostname); - } + private void CopySelectedHostnameAction() + { + ClipboardHelper.SetClipboard(SelectedTraceResult.Hostname); + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private void ExportAction() - { - Export(); - } - #endregion + private void ExportAction() + { + Export(); + } + #endregion - #region Methods - private void StopTrace() - { - CancelTrace = true; - _cancellationTokenSource.Cancel(); - } + #region Methods + private void StopTrace() + { + CancelTrace = true; + _cancellationTokenSource.Cancel(); + } - private async Task StartTrace() - { - IsStatusMessageDisplayed = false; - IsRunning = true; + private async Task StartTrace() + { + IsStatusMessageDisplayed = false; + IsRunning = true; - TraceResults.Clear(); + TraceResults.Clear(); - // Change the tab title (not nice, but it works) - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + // Change the tab title (not nice, but it works) + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); - if (window != null) + if (window != null) + { + foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) { - foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) - { - tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Host; - } + tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Host; } + } - _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) - { - StatusMessage = DNSClientHelper.FormatDNSClientResultError(Host, dnsResult); - IsStatusMessageDisplayed = true; - IsRunning = false; - return; - } + _cancellationTokenSource = new CancellationTokenSource(); - ipAddress = dnsResult.Value; - } + // 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); - try + if (dnsResult.HasError) { - var traceroute = new Traceroute(new TracerouteOptions - { - Timeout = SettingsManager.Current.Traceroute_Timeout, - Buffer = new byte[SettingsManager.Current.Traceroute_Buffer], - MaximumHops = SettingsManager.Current.Traceroute_MaximumHops, - DontFragment = true, - ResolveHostname = SettingsManager.Current.Traceroute_ResolveHostname - }); - - 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 - { - StatusMessage = ex.Message; + StatusMessage = DNSClientHelper.FormatDNSClientResultError(Host, dnsResult); IsStatusMessageDisplayed = true; IsRunning = false; + return; } + + ipAddress = dnsResult.Value; } - - private void UserHasCanceled() + + try { - CancelTrace = false; + var traceroute = new Traceroute(new TracerouteOptions + { + Timeout = SettingsManager.Current.Traceroute_Timeout, + Buffer = new byte[SettingsManager.Current.Traceroute_Buffer], + MaximumHops = SettingsManager.Current.Traceroute_MaximumHops, + DontFragment = true, + ResolveHostname = SettingsManager.Current.Traceroute_ResolveHostname + }); + + 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 + { + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; IsRunning = false; } + } + + private void UserHasCanceled() + { + CancelTrace = false; + IsRunning = false; + } - private async Task Export() + private async Task Export() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + Title = Localization.Resources.Strings.Export + }; - var exportViewModel = new ExportViewModel(async instance => + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + + try + { + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? TraceResults : new ObservableCollection(SelectedTraceResults.Cast().ToArray())); + } + catch (Exception ex) { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? TraceResults : new ObservableCollection(SelectedTraceResults.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + SettingsManager.Current.Traceroute_ExportFileType = instance.FileType; + SettingsManager.Current.Traceroute_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Traceroute_ExportFileType, SettingsManager.Current.Traceroute_ExportFilePath); - SettingsManager.Current.Traceroute_ExportFileType = instance.FileType; - SettingsManager.Current.Traceroute_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.Traceroute_ExportFileType, SettingsManager.Current.Traceroute_ExportFilePath); + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + private void AddHostToHistory(string host) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.Traceroute_HostHistory.ToList(), host, SettingsManager.Current.General_HistoryListEntries); - 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 - // 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)); + } - // Fill with the new items - list.ForEach(x => SettingsManager.Current.Traceroute_HostHistory.Add(x)); - } + public void OnClose() + { + if (IsRunning) + StopTrace(); + } + #endregion - public void OnClose() - { - if (IsRunning) - StopTrace(); - } - #endregion + #region Events + private void Traceroute_HopReceived(object sender, TracerouteHopReceivedArgs e) + { + var tracerouteInfo = TracerouteHopInfo.Parse(e); - #region Events - private void Traceroute_HopReceived(object sender, TracerouteHopReceivedArgs e) + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - var tracerouteInfo = TracerouteHopInfo.Parse(e); - - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - //lock (TraceResults) - TraceResults.Add(tracerouteInfo); - })); - } + //lock (TraceResults) + TraceResults.Add(tracerouteInfo); + })); + } - private void Traceroute_MaximumHopsReached(object sender, MaximumHopsReachedArgs e) - { - StatusMessage = string.Format(Localization.Resources.Strings.MaximumNumberOfHopsReached, e.Hops); - IsStatusMessageDisplayed = true; - IsRunning = false; - } - - private void Traceroute_UserHasCanceled(object sender, EventArgs e) - { - CancelTrace = false; - IsRunning = false; + private void Traceroute_MaximumHopsReached(object sender, MaximumHopsReachedArgs e) + { + StatusMessage = string.Format(Localization.Resources.Strings.MaximumNumberOfHopsReached, e.Hops); + IsStatusMessageDisplayed = true; + IsRunning = false; + } + + private void Traceroute_UserHasCanceled(object sender, EventArgs e) + { + CancelTrace = false; + IsRunning = false; - StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; - IsStatusMessageDisplayed = true; - } + StatusMessage = Localization.Resources.Strings.CanceledByUserMessage; + IsStatusMessageDisplayed = true; + } - private void Traceroute_TraceError(object sender, TracerouteErrorArgs e) - { - IsRunning = false; + private void Traceroute_TraceError(object sender, TracerouteErrorArgs e) + { + IsRunning = false; - StatusMessage = e.ErrorMessage; - IsStatusMessageDisplayed = true; - } + StatusMessage = e.ErrorMessage; + IsStatusMessageDisplayed = true; + } - private void Traceroute_TraceComplete(object sender, EventArgs e) - { - IsRunning = false; - } + private void Traceroute_TraceComplete(object sender, EventArgs e) + { + IsRunning = false; + } - private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) { - switch (e.PropertyName) - { - case nameof(SettingsInfo.Traceroute_ResolveHostname): - OnPropertyChanged(nameof(ResolveHostname)); - break; - } + case nameof(SettingsInfo.Traceroute_ResolveHostname): + OnPropertyChanged(nameof(ResolveHostname)); + break; } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ViewModelBase.cs b/Source/NETworkManager/ViewModels/ViewModelBase.cs index 05753e1f9c..4f8d6cda36 100644 --- a/Source/NETworkManager/ViewModels/ViewModelBase.cs +++ b/Source/NETworkManager/ViewModels/ViewModelBase.cs @@ -1,15 +1,14 @@ using System.ComponentModel; using System.Runtime.CompilerServices; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public abstract class ViewModelBase : INotifyPropertyChanged { - public abstract class ViewModelBase : INotifyPropertyChanged - { - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } diff --git a/Source/NETworkManager/ViewModels/WakeOnLANSettingsViewModel.cs b/Source/NETworkManager/ViewModels/WakeOnLANSettingsViewModel.cs index 94190b9f36..d9ba5a70e4 100644 --- a/Source/NETworkManager/ViewModels/WakeOnLANSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/WakeOnLANSettingsViewModel.cs @@ -1,45 +1,44 @@ using NETworkManager.Settings; using NETworkManager.Utilities; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WakeOnLANSettingsViewModel : ViewModelBase { - public class WakeOnLANSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; + #region Variables + private readonly bool _isLoading; - private int _defaultPort; - public int DefaultPort + private int _defaultPort; + public int DefaultPort + { + get => _defaultPort; + set { - get => _defaultPort; - set - { - if (value == _defaultPort) - return; - - if (!_isLoading) - SettingsManager.Current.WakeOnLAN_Port = value; - - _defaultPort = value; - OnPropertyChanged(); - } + if (value == _defaultPort) + return; + + if (!_isLoading) + SettingsManager.Current.WakeOnLAN_Port = value; + + _defaultPort = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public WakeOnLANSettingsViewModel() - { - _isLoading = true; + #region Constructor, load settings + public WakeOnLANSettingsViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - DefaultPort = SettingsManager.Current.WakeOnLAN_Port; - } - #endregion + private void LoadSettings() + { + DefaultPort = SettingsManager.Current.WakeOnLAN_Port; } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs b/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs index a0752861e8..d56021b1f6 100644 --- a/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs +++ b/Source/NETworkManager/ViewModels/WakeOnLANViewModel.cs @@ -17,462 +17,461 @@ using NETworkManager.Models; using Amazon.EC2.Model; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WakeOnLANViewModel : ViewModelBase, IProfileManager { - public class WakeOnLANViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private bool _isSending; - public bool IsSending + private bool _isSending; + public bool IsSending + { + get => _isSending; + set { - get => _isSending; - set - { - if (value == _isSending) - return; + if (value == _isSending) + return; - _isSending = value; - OnPropertyChanged(); - } + _isSending = value; + OnPropertyChanged(); } - public ICollectionView MACAddressHistoryView { get; } + } + public ICollectionView MACAddressHistoryView { get; } - private string _macAddress; - public string MACAddress + private string _macAddress; + public string MACAddress + { + get => _macAddress; + set { - get => _macAddress; - set - { - if (value == _macAddress) - return; + if (value == _macAddress) + return; - _macAddress = value; - OnPropertyChanged(); - } + _macAddress = value; + OnPropertyChanged(); } + } - public ICollectionView BroadcastHistoryView { get; } + public ICollectionView BroadcastHistoryView { get; } - private string _broadcast; - public string Broadcast + private string _broadcast; + public string Broadcast + { + get => _broadcast; + set { - get => _broadcast; - set - { - if (value == _broadcast) - return; + if (value == _broadcast) + return; - _broadcast = value; - OnPropertyChanged(); - } + _broadcast = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile; - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile; + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; - - if (value != null && !IsSending) - { - MACAddress = value.WakeOnLAN_MACAddress; - Broadcast = value.WakeOnLAN_Broadcast; - } + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); + if (value != null && !IsSending) + { + MACAddress = value.WakeOnLAN_MACAddress; + Broadcast = value.WakeOnLAN_Broadcast; } + + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.WakeOnLAN_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.WakeOnLAN_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.WakeOnLAN_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.WakeOnLAN_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public WakeOnLANViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public WakeOnLANViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - MACAddressHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.WakeOnLan_MACAddressHistory); - BroadcastHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.WakeOnLan_BroadcastHistory); + MACAddressHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.WakeOnLan_MACAddressHistory); + BroadcastHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.WakeOnLan_BroadcastHistory); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (o is not ProfileInfo info) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (o is not ProfileInfo info) + return false; - if (string.IsNullOrEmpty(Search)) - return info.WakeOnLAN_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.WakeOnLAN_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.WakeOnLAN_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.WakeOnLAN_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, WakeOnLAN_MACAddress - return info.WakeOnLAN_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.WakeOnLAN_MACAddress.Replace("-", "").Replace(":", "").IndexOf(search.Replace("-", "").Replace(":", ""), StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, WakeOnLAN_MACAddress + return info.WakeOnLAN_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.WakeOnLAN_MACAddress.Replace("-", "").Replace(":", "").IndexOf(search.Replace("-", "").Replace(":", ""), StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.WakeOnLAN_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.WakeOnLAN_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.WakeOnLAN_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.WakeOnLAN_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.WakeOnLAN_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.WakeOnLAN_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.WakeOnLAN_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.WakeOnLAN_ProfileWidth; + } + #endregion - #region ICommands & Actions - public ICommand WakeUpCommand => new RelayCommand(p => WakeUpAction(), WakeUpAction_CanExecute); + #region ICommands & Actions + public ICommand WakeUpCommand => new RelayCommand(p => WakeUpAction(), WakeUpAction_CanExecute); - private bool WakeUpAction_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool WakeUpAction_CanExecute(object parameter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void WakeUpAction() + private void WakeUpAction() + { + var info = new WakeOnLANInfo { - var info = new WakeOnLANInfo - { - MagicPacket = WakeOnLAN.CreateMagicPacket(MACAddress), - Broadcast = IPAddress.Parse(Broadcast), - Port = SettingsManager.Current.WakeOnLAN_Port - }; + MagicPacket = WakeOnLAN.CreateMagicPacket(MACAddress), + Broadcast = IPAddress.Parse(Broadcast), + Port = SettingsManager.Current.WakeOnLAN_Port + }; - AddMACAddressToHistory(MACAddress); - AddBroadcastToHistory(Broadcast); + AddMACAddressToHistory(MACAddress); + AddBroadcastToHistory(Broadcast); - WakeUp(info); - } + WakeUp(info); + } - public ICommand WakeUpProfileCommand => new RelayCommand(p => WakeUpProfileAction()); + public ICommand WakeUpProfileCommand => new RelayCommand(p => WakeUpProfileAction()); - private void WakeUpProfileAction() - { - WakeUp(NETworkManager.Profiles.Application.WakeOnLAN.CreateInfo(SelectedProfile)); - } + private void WakeUpProfileAction() + { + WakeUp(NETworkManager.Profiles.Application.WakeOnLAN.CreateInfo(SelectedProfile)); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.WakeOnLAN); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.WakeOnLAN); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } - #endregion + private void ClearSearchAction() + { + Search = string.Empty; + } + #endregion - #region Methods - private async Task WakeUp(WakeOnLANInfo info) + #region Methods + private async Task WakeUp(WakeOnLANInfo info) + { + IsStatusMessageDisplayed = false; + IsSending = true; + + try { - IsStatusMessageDisplayed = false; - IsSending = true; - - try - { - WakeOnLAN.Send(info); + WakeOnLAN.Send(info); - await Task.Delay(2000); // Make the user happy, let him see a reload animation (and he cannot spam the send command) + await Task.Delay(2000); // Make the user happy, let him see a reload animation (and he cannot spam the send command) - StatusMessage = Localization.Resources.Strings.MagicPacketSentMessage; - IsStatusMessageDisplayed = true; - } - catch (Exception ex) - { - StatusMessage = ex.Message; - IsStatusMessageDisplayed = true; - } + StatusMessage = Localization.Resources.Strings.MagicPacketSentMessage; + IsStatusMessageDisplayed = true; + } + catch (Exception ex) + { + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; + } - IsSending = false; - } + IsSending = false; + } - private void AddMACAddressToHistory(string macAddress) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.WakeOnLan_MACAddressHistory.ToList(), macAddress, SettingsManager.Current.General_HistoryListEntries); + private void AddMACAddressToHistory(string macAddress) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.WakeOnLan_MACAddressHistory.ToList(), macAddress, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.WakeOnLan_MACAddressHistory.Clear(); - OnPropertyChanged(nameof(MACAddress)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.WakeOnLan_MACAddressHistory.Clear(); + OnPropertyChanged(nameof(MACAddress)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.WakeOnLan_MACAddressHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.WakeOnLan_MACAddressHistory.Add(x)); + } - private void AddBroadcastToHistory(string broadcast) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.WakeOnLan_BroadcastHistory.ToList(), broadcast, SettingsManager.Current.General_HistoryListEntries); + private void AddBroadcastToHistory(string broadcast) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.WakeOnLan_BroadcastHistory.ToList(), broadcast, SettingsManager.Current.General_HistoryListEntries); - // Clear the old items - SettingsManager.Current.WakeOnLan_BroadcastHistory.Clear(); - OnPropertyChanged(nameof(Broadcast)); // Raise property changed again, after the collection has been cleared + // Clear the old items + SettingsManager.Current.WakeOnLan_BroadcastHistory.Clear(); + OnPropertyChanged(nameof(Broadcast)); // Raise property changed again, after the collection has been cleared - // Fill with the new items - list.ForEach(x => SettingsManager.Current.WakeOnLan_BroadcastHistory.Add(x)); - } + // Fill with the new items + list.ForEach(x => SettingsManager.Current.WakeOnLan_BroadcastHistory.Add(x)); + } - private void StartDelayedSearch() + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void OnViewVisible() - { - _isViewActive = true; + _canProfileWidthChange = true; + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Profiles.Refresh(); + })); + } - } + public void OnProfileDialogOpen() + { - public void OnProfileDialogClose() - { + } - } - #endregion + public void OnProfileDialogClose() + { - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } diff --git a/Source/NETworkManager/ViewModels/WebConsoleConnectViewModel.cs b/Source/NETworkManager/ViewModels/WebConsoleConnectViewModel.cs index ef7705cceb..254712bb71 100644 --- a/Source/NETworkManager/ViewModels/WebConsoleConnectViewModel.cs +++ b/Source/NETworkManager/ViewModels/WebConsoleConnectViewModel.cs @@ -5,42 +5,41 @@ using System.Windows.Data; using System.Windows.Input; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WebConsoleConnectViewModel : ViewModelBase { - public class WebConsoleConnectViewModel : ViewModelBase - { - public ICommand ConnectCommand { get; } - public ICommand CancelCommand { get; } + public ICommand ConnectCommand { get; } + public ICommand CancelCommand { get; } - private string _url; - public string Url + private string _url; + public string Url + { + get => _url; + set { - get => _url; - set - { - if (value == _url) - return; - - _url = value; - OnPropertyChanged(); - } + if (value == _url) + return; + + _url = value; + OnPropertyChanged(); } - - public ICollectionView UrlHistoryView { get; } + } + + public ICollectionView UrlHistoryView { get; } - public WebConsoleConnectViewModel(Action connectCommand, Action cancelHandler) - { - ConnectCommand = new RelayCommand(p => connectCommand(this)); - CancelCommand = new RelayCommand(p => cancelHandler(this)); + public WebConsoleConnectViewModel(Action connectCommand, Action cancelHandler) + { + ConnectCommand = new RelayCommand(p => connectCommand(this)); + CancelCommand = new RelayCommand(p => cancelHandler(this)); - UrlHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.WebConsole_UrlHistory); + UrlHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.WebConsole_UrlHistory); - LoadSettings(); - } + LoadSettings(); + } - private void LoadSettings() - { + private void LoadSettings() + { - } } } diff --git a/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs b/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs index c0ff2b2822..1ff3dedbf2 100644 --- a/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/WebConsoleHostViewModel.cs @@ -20,472 +20,471 @@ using System.Threading.Tasks; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WebConsoleHostViewModel : ViewModelBase, IProfileManager { - public class WebConsoleHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - /// - /// Private variable for . - /// - private bool _isRuntimeAvailable; + /// + /// Private variable for . + /// + private bool _isRuntimeAvailable; - /// - /// Variable indicates if the Edge WebView2 runtime is available. - /// - public bool IsRuntimeAvailable + /// + /// Variable indicates if the Edge WebView2 runtime is available. + /// + public bool IsRuntimeAvailable + { + get => _isRuntimeAvailable; + set { - get => _isRuntimeAvailable; - set - { - if (value == _isRuntimeAvailable) - return; + if (value == _isRuntimeAvailable) + return; - _isRuntimeAvailable = value; - OnPropertyChanged(); - } + _isRuntimeAvailable = value; + OnPropertyChanged(); } + } - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.WebConsole_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.WebConsole_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.WebConsole_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.WebConsole_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor, load settings - public WebConsoleHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor, load settings + public WebConsoleHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - try - { - string version = CoreWebView2Environment.GetAvailableBrowserVersionString(); - IsRuntimeAvailable = true; - } - catch (WebView2RuntimeNotFoundException) - { - IsRuntimeAvailable = false; - } + try + { + string version = CoreWebView2Environment.GetAvailableBrowserVersionString(); + IsRuntimeAvailable = true; + } + catch (WebView2RuntimeNotFoundException) + { + IsRuntimeAvailable = false; + } - InterTabClient = new DragablzInterTabClient(ApplicationName.WebConsole); + InterTabClient = new DragablzInterTabClient(ApplicationName.WebConsole); - TabItems = new ObservableCollection(); + TabItems = new ObservableCollection(); - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.WebConsole_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.WebConsole_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.WebConsole_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.WebConsole_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, WebConsole_Url - return info.WebConsole_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.WebConsole_Url.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, WebConsole_Url + return info.WebConsole_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.WebConsole_Url.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.WebConsole_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.WebConsole_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - SettingsManager.Current.PropertyChanged += Current_PropertyChanged; + SettingsManager.Current.PropertyChanged += Current_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - } + private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.WebConsole_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.WebConsole_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.WebConsole_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.WebConsole_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.WebConsole_ProfileWidth; - } - #endregion + _tempProfileWidth = SettingsManager.Current.WebConsole_ProfileWidth; + } + #endregion - #region ICommand & Actions - public ItemActionCallback CloseItemCommand => CloseItemAction; + #region ICommand & Actions + public ItemActionCallback CloseItemCommand => CloseItemAction; - private void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as WebConsoleControl)?.CloseTab(); - } + private void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as WebConsoleControl)?.CloseTab(); + } - public ICommand WebConsole_RefreshCommand => new RelayCommand(WebConsole_RefreshAction); + public ICommand WebConsole_RefreshCommand => new RelayCommand(WebConsole_RefreshAction); - private void WebConsole_RefreshAction(object view) + private void WebConsole_RefreshAction(object view) + { + if (view is WebConsoleControl control) { - if (view is WebConsoleControl control) - { - if (control.ReloadCommand.CanExecute(null)) - control.ReloadCommand.Execute(null); - } + if (control.ReloadCommand.CanExecute(null)) + control.ReloadCommand.Execute(null); } + } - public ICommand ConnectCommand => new RelayCommand(p => ConnectAction()); + public ICommand ConnectCommand => new RelayCommand(p => ConnectAction()); - private void ConnectAction() - { - Connect(); - } + private void ConnectAction() + { + Connect(); + } - public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); + public ICommand ConnectProfileCommand => new RelayCommand(p => ConnectProfileAction(), ConnectProfile_CanExecute); - private bool ConnectProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool ConnectProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void ConnectProfileAction() - { - ConnectProfile(); - } + private void ConnectProfileAction() + { + ConnectProfile(); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.WebConsole); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.WebConsole); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); + public ICommand OpenSettingsCommand => new RelayCommand(p => OpenSettingsAction()); - private static void OpenSettingsAction() - { - EventSystem.RedirectToSettings(); - } + private static void OpenSettingsAction() + { + EventSystem.RedirectToSettings(); + } - public ICommand OpenWebsiteCommand => new RelayCommand(OpenWebsiteAction); + public ICommand OpenWebsiteCommand => new RelayCommand(OpenWebsiteAction); - private static void OpenWebsiteAction(object url) + private static void OpenWebsiteAction(object url) + { + ExternalProcessStarter.OpenUrl((string)url); + } + #endregion + + #region Methods + private async Task Connect() + { + var customDialog = new CustomDialog { - ExternalProcessStarter.OpenUrl((string)url); - } - #endregion + Title = Localization.Resources.Strings.Connect + }; - #region Methods - private async Task Connect() + var connectViewModel = new WebConsoleConnectViewModel(async instance => { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Connect - }; + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; - var connectViewModel = new WebConsoleConnectViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - - // Create profile info - var info = new WebConsoleSessionInfo - { - Url = instance.Url - }; - - // Add to history - // Note: The history can only be updated after the values have been read. - // Otherwise, in some cases, incorrect values are taken over. - AddUrlToHistory(instance.Url); - - Connect(info); - }, async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - ConfigurationManager.Current.IsDialogOpen = false; - }); - - customDialog.Content = new WebConsoleConnectDialog + // Create profile info + var info = new WebConsoleSessionInfo { - DataContext = connectViewModel + Url = instance.Url }; - ConfigurationManager.Current.IsDialogOpen = true; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + // Add to history + // Note: The history can only be updated after the values have been read. + // Otherwise, in some cases, incorrect values are taken over. + AddUrlToHistory(instance.Url); - private void ConnectProfile() - { - Connect(NETworkManager.Profiles.Application.WebConsole.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); - } + Connect(info); + }, async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + ConfigurationManager.Current.IsDialogOpen = false; + }); - private void Connect(WebConsoleSessionInfo sessionInfo, string header = null) + customDialog.Content = new WebConsoleConnectDialog { - TabItems.Add(new DragablzTabItem(header ?? sessionInfo.Url, new WebConsoleControl(sessionInfo))); + DataContext = connectViewModel + }; - SelectedTabIndex = TabItems.Count - 1; - } + ConfigurationManager.Current.IsDialogOpen = true; + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } - // Modify history list - private static void AddUrlToHistory(string url) - { - if (string.IsNullOrEmpty(url)) - return; + private void ConnectProfile() + { + Connect(NETworkManager.Profiles.Application.WebConsole.CreateSessionInfo(SelectedProfile), SelectedProfile.Name); + } - SettingsManager.Current.WebConsole_UrlHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.WebConsole_UrlHistory.ToList(), url, SettingsManager.Current.General_HistoryListEntries)); - } + private void Connect(WebConsoleSessionInfo sessionInfo, string header = null) + { + TabItems.Add(new DragablzTabItem(header ?? sessionInfo.Url, new WebConsoleControl(sessionInfo))); + + SelectedTabIndex = TabItems.Count - 1; + } - private void StartDelayedSearch() + // Modify history list + private static void AddUrlToHistory(string url) + { + if (string.IsNullOrEmpty(url)) + return; + + SettingsManager.Current.WebConsole_UrlHistory = new ObservableCollection(ListHelper.Modify(SettingsManager.Current.WebConsole_UrlHistory.ToList(), url, SettingsManager.Current.General_HistoryListEntries)); + } + + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } + + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - RefreshProfiles(); + RefreshProfiles(); - IsSearching = false; - } + IsSearching = false; + } - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - public void OnViewVisible() - { - _isViewActive = true; + _canProfileWidthChange = true; + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { - ConfigurationManager.Current.IsDialogOpen = true; - } + Profiles.Refresh(); + })); + } - public void OnProfileDialogClose() - { - ConfigurationManager.Current.IsDialogOpen = false; - } - #endregion + public void OnProfileDialogOpen() + { + ConfigurationManager.Current.IsDialogOpen = true; + } - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + public void OnProfileDialogClose() + { + ConfigurationManager.Current.IsDialogOpen = false; + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs b/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs index 6f2dd140cc..4c31d358b7 100644 --- a/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/WhoisHostViewModel.cs @@ -16,366 +16,365 @@ using NETworkManager.Models; using System.Collections.Generic; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WhoisHostViewModel : ViewModelBase, IProfileManager { - public class WhoisHostViewModel : ViewModelBase, IProfileManager - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + private readonly DispatcherTimer _searchDispatcherTimer = new DispatcherTimer(); - public IInterTabClient InterTabClient { get; } - public ObservableCollection TabItems { get; } + public IInterTabClient InterTabClient { get; } + public ObservableCollection TabItems { get; } - private readonly bool _isLoading = true; - private bool _isViewActive = true; + private readonly bool _isLoading = true; + private bool _isViewActive = true; - private int _tabId; + private int _tabId; - private int _selectedTabIndex; - public int SelectedTabIndex + private int _selectedTabIndex; + public int SelectedTabIndex + { + get => _selectedTabIndex; + set { - get => _selectedTabIndex; - set - { - if (value == _selectedTabIndex) - return; + if (value == _selectedTabIndex) + return; - _selectedTabIndex = value; - OnPropertyChanged(); - } + _selectedTabIndex = value; + OnPropertyChanged(); } + } - #region Profiles - public ICollectionView Profiles { get; } + #region Profiles + public ICollectionView Profiles { get; } - private ProfileInfo _selectedProfile = new ProfileInfo(); - public ProfileInfo SelectedProfile + private ProfileInfo _selectedProfile = new ProfileInfo(); + public ProfileInfo SelectedProfile + { + get => _selectedProfile; + set { - get => _selectedProfile; - set - { - if (value == _selectedProfile) - return; + if (value == _selectedProfile) + return; - _selectedProfile = value; - OnPropertyChanged(); - } + _selectedProfile = value; + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - StartDelayedSearch(); + StartDelayedSearch(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _isSearching; - public bool IsSearching + private bool _isSearching; + public bool IsSearching + { + get => _isSearching; + set { - get => _isSearching; - set - { - if (value == _isSearching) - return; + if (value == _isSearching) + return; - _isSearching = value; - OnPropertyChanged(); - } + _isSearching = value; + OnPropertyChanged(); } + } - private bool _canProfileWidthChange = true; - private double _tempProfileWidth; + private bool _canProfileWidthChange = true; + private double _tempProfileWidth; - private bool _expandProfileView; - public bool ExpandProfileView + private bool _expandProfileView; + public bool ExpandProfileView + { + get => _expandProfileView; + set { - get => _expandProfileView; - set - { - if (value == _expandProfileView) - return; + if (value == _expandProfileView) + return; - if (!_isLoading) - SettingsManager.Current.Whois_ExpandProfileView = value; + if (!_isLoading) + SettingsManager.Current.Whois_ExpandProfileView = value; - _expandProfileView = value; + _expandProfileView = value; - if (_canProfileWidthChange) - ResizeProfile(false); + if (_canProfileWidthChange) + ResizeProfile(false); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private GridLength _profileWidth; - public GridLength ProfileWidth + private GridLength _profileWidth; + public GridLength ProfileWidth + { + get => _profileWidth; + set { - get => _profileWidth; - set - { - if (value == _profileWidth) - return; + if (value == _profileWidth) + return; - if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed - SettingsManager.Current.Whois_ProfileWidth = value.Value; + if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix) // Do not save the size when collapsed + SettingsManager.Current.Whois_ProfileWidth = value.Value; - _profileWidth = value; + _profileWidth = value; - if (_canProfileWidthChange) - ResizeProfile(true); + if (_canProfileWidthChange) + ResizeProfile(true); - OnPropertyChanged(); - } + OnPropertyChanged(); } - #endregion - #endregion + } + #endregion + #endregion - #region Constructor - public WhoisHostViewModel(IDialogCoordinator instance) - { - _dialogCoordinator = instance; + #region Constructor + public WhoisHostViewModel(IDialogCoordinator instance) + { + _dialogCoordinator = instance; - InterTabClient = new DragablzInterTabClient(ApplicationName.Whois); + InterTabClient = new DragablzInterTabClient(ApplicationName.Whois); - TabItems = new ObservableCollection - { - new DragablzTabItem(Localization.Resources.Strings.NewTab, new WhoisView (_tabId), _tabId) - }; - - Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; - Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); - Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); - Profiles.Filter = o => - { - if (!(o is ProfileInfo info)) - return false; + TabItems = new ObservableCollection + { + new DragablzTabItem(Localization.Resources.Strings.NewTab, new WhoisView (_tabId), _tabId) + }; + + Profiles = new CollectionViewSource { Source = ProfileManager.Groups.SelectMany(x => x.Profiles) }.View; + Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending)); + Profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending)); + Profiles.Filter = o => + { + if (!(o is ProfileInfo info)) + return false; - if (string.IsNullOrEmpty(Search)) - return info.Whois_Enabled; + if (string.IsNullOrEmpty(Search)) + return info.Whois_Enabled; - var search = Search.Trim(); + var search = Search.Trim(); - // Search by: Tag=xxx (exact match, ignore case) - /* - if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) - return !string.IsNullOrEmpty(info.Tags) && info.Whois_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); - */ + // Search by: Tag=xxx (exact match, ignore case) + /* + if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase)) + return !string.IsNullOrEmpty(info.Tags) && info.Whois_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)); + */ - // Search by: Name, Whois_Domain - return info.Whois_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.Whois_Domain.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - }; + // Search by: Name, Whois_Domain + return info.Whois_Enabled && (info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 || info.Whois_Domain.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + }; - // This will select the first entry as selected item... - SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.Whois_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); + // This will select the first entry as selected item... + SelectedProfile = Profiles.SourceCollection.Cast().Where(x => x.Whois_Enabled).OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault(); - ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; + ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated; - _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; - _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; + _searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan; + _searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { - ExpandProfileView = SettingsManager.Current.Whois_ExpandProfileView; + private void LoadSettings() + { + ExpandProfileView = SettingsManager.Current.Whois_ExpandProfileView; - ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.Whois_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); + ProfileWidth = ExpandProfileView ? new GridLength(SettingsManager.Current.Whois_ProfileWidth) : new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - _tempProfileWidth = SettingsManager.Current.Whois_ProfileWidth; - } + _tempProfileWidth = SettingsManager.Current.Whois_ProfileWidth; + } - #endregion + #endregion - #region ICommand & Actions - public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); + #region ICommand & Actions + public ICommand AddTabCommand => new RelayCommand(p => AddTabAction()); - private void AddTabAction() - { - AddTab(); - } + private void AddTabAction() + { + AddTab(); + } - public ICommand QueryProfileCommand => new RelayCommand(p => QueryProfileAction(), QueryProfile_CanExecute); + public ICommand QueryProfileCommand => new RelayCommand(p => QueryProfileAction(), QueryProfile_CanExecute); - private bool QueryProfile_CanExecute(object obj) - { - return !IsSearching && SelectedProfile != null; - } + private bool QueryProfile_CanExecute(object obj) + { + return !IsSearching && SelectedProfile != null; + } - private void QueryProfileAction() - { - AddTab(SelectedProfile.Whois_Domain); - } + private void QueryProfileAction() + { + AddTab(SelectedProfile.Whois_Domain); + } - public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); + public ICommand AddProfileCommand => new RelayCommand(p => AddProfileAction()); - private void AddProfileAction() - { - ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.Whois); - } + private void AddProfileAction() + { + ProfileDialogManager.ShowAddProfileDialog(this, _dialogCoordinator, null, null, ApplicationName.Whois); + } - private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; + private bool ModifyProfile_CanExecute(object obj) => SelectedProfile != null && !SelectedProfile.IsDynamic; - public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); + public ICommand EditProfileCommand => new RelayCommand(p => EditProfileAction(), ModifyProfile_CanExecute); - private void EditProfileAction() - { - ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void EditProfileAction() + { + ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); + public ICommand CopyAsProfileCommand => new RelayCommand(p => CopyAsProfileAction(), ModifyProfile_CanExecute); - private void CopyAsProfileAction() - { - ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); - } + private void CopyAsProfileAction() + { + ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile); + } - public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); + public ICommand DeleteProfileCommand => new RelayCommand(p => DeleteProfileAction(), ModifyProfile_CanExecute); - private void DeleteProfileAction() - { - ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); - } + private void DeleteProfileAction() + { + ProfileDialogManager.ShowDeleteProfileDialog(this, _dialogCoordinator, new List { SelectedProfile }); + } - public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); + public ICommand EditGroupCommand => new RelayCommand(EditGroupAction); - private void EditGroupAction(object group) - { - ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); - } + private void EditGroupAction(object group) + { + ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString())); + } - public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); + public ICommand ClearSearchCommand => new RelayCommand(p => ClearSearchAction()); - private void ClearSearchAction() - { - Search = string.Empty; - } + private void ClearSearchAction() + { + Search = string.Empty; + } - public ItemActionCallback CloseItemCommand => CloseItemAction; + public ItemActionCallback CloseItemCommand => CloseItemAction; - private static void CloseItemAction(ItemActionCallbackArgs args) - { - ((args.DragablzItem.Content as DragablzTabItem)?.View as WhoisView)?.CloseTab(); - } - #endregion + private static void CloseItemAction(ItemActionCallbackArgs args) + { + ((args.DragablzItem.Content as DragablzTabItem)?.View as WhoisView)?.CloseTab(); + } + #endregion - #region Methods - private void StartDelayedSearch() + #region Methods + private void StartDelayedSearch() + { + if (!IsSearching) { - if (!IsSearching) - { - IsSearching = true; + IsSearching = true; - _searchDispatcherTimer.Start(); - } - else - { - _searchDispatcherTimer.Stop(); - _searchDispatcherTimer.Start(); - } + _searchDispatcherTimer.Start(); } - - private void StopDelayedSearch() + else { _searchDispatcherTimer.Stop(); + _searchDispatcherTimer.Start(); + } + } - RefreshProfiles(); + private void StopDelayedSearch() + { + _searchDispatcherTimer.Stop(); - IsSearching = false; - } + RefreshProfiles(); - private void ResizeProfile(bool dueToChangedSize) - { - _canProfileWidthChange = false; + IsSearching = false; + } + + private void ResizeProfile(bool dueToChangedSize) + { + _canProfileWidthChange = false; - if (dueToChangedSize) + if (dueToChangedSize) + { + ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + } + else + { + if (ExpandProfileView) { - ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) > GlobalStaticConfiguration.FloatPointFix; + ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); } else { - if (ExpandProfileView) - { - ProfileWidth = Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) < GlobalStaticConfiguration.FloatPointFix ? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded) : new GridLength(_tempProfileWidth); - } - else - { - _tempProfileWidth = ProfileWidth.Value; - ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); - } + _tempProfileWidth = ProfileWidth.Value; + ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed); } - - _canProfileWidthChange = true; } - private void AddTab(string domain = null) - { - _tabId++; + _canProfileWidthChange = true; + } - TabItems.Add(new DragablzTabItem(domain ?? Localization.Resources.Strings.NewTab, new WhoisView(_tabId, domain), _tabId)); + private void AddTab(string domain = null) + { + _tabId++; - SelectedTabIndex = TabItems.Count - 1; - } + TabItems.Add(new DragablzTabItem(domain ?? Localization.Resources.Strings.NewTab, new WhoisView(_tabId, domain), _tabId)); - public void OnViewVisible() - { - _isViewActive = true; + SelectedTabIndex = TabItems.Count - 1; + } - RefreshProfiles(); - } + public void OnViewVisible() + { + _isViewActive = true; - public void OnViewHide() - { - _isViewActive = false; - } + RefreshProfiles(); + } - public void RefreshProfiles() - { - if (!_isViewActive) - return; + public void OnViewHide() + { + _isViewActive = false; + } - Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate - { - Profiles.Refresh(); - })); - } + public void RefreshProfiles() + { + if (!_isViewActive) + return; - public void OnProfileDialogOpen() + Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate { + Profiles.Refresh(); + })); + } - } + public void OnProfileDialogOpen() + { - public void OnProfileDialogClose() - { + } - } - #endregion + public void OnProfileDialogClose() + { - #region Event - private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) - { - RefreshProfiles(); - } + } + #endregion - private void SearchDispatcherTimer_Tick(object sender, EventArgs e) - { - StopDelayedSearch(); - } - #endregion + #region Event + private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e) + { + RefreshProfiles(); + } + + private void SearchDispatcherTimer_Tick(object sender, EventArgs e) + { + StopDelayedSearch(); } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/WhoisSettingsViewModel.cs b/Source/NETworkManager/ViewModels/WhoisSettingsViewModel.cs index c9976fed90..017ecc657a 100644 --- a/Source/NETworkManager/ViewModels/WhoisSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/WhoisSettingsViewModel.cs @@ -1,30 +1,29 @@ using NETworkManager.Settings; using NETworkManager.Utilities; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WhoisSettingsViewModel : ViewModelBase { - public class WhoisSettingsViewModel : ViewModelBase - { - #region Variables - private readonly bool _isLoading; - - - #endregion + #region Variables + private readonly bool _isLoading; + + + #endregion - #region Contructor, load settings - public WhoisSettingsViewModel() - { - _isLoading = true; + #region Contructor, load settings + public WhoisSettingsViewModel() + { + _isLoading = true; - LoadSettings(); + LoadSettings(); - _isLoading = false; - } + _isLoading = false; + } - private void LoadSettings() - { + private void LoadSettings() + { - } - #endregion } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/WhoisViewModel.cs b/Source/NETworkManager/ViewModels/WhoisViewModel.cs index 10c637c515..3475c6b6c7 100644 --- a/Source/NETworkManager/ViewModels/WhoisViewModel.cs +++ b/Source/NETworkManager/ViewModels/WhoisViewModel.cs @@ -16,245 +16,244 @@ using NETworkManager.Views; using System.Threading.Tasks; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WhoisViewModel : ViewModelBase { - public class WhoisViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; - - public readonly int TabId; - private bool _firstLoad = true; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; + + public readonly int TabId; + private bool _firstLoad = true; - private readonly bool _isLoading; + private readonly bool _isLoading; - private string _domain; - public string Domain + private string _domain; + public string Domain + { + get => _domain; + set { - get => _domain; - set - { - if (value == _domain) - return; + if (value == _domain) + return; - _domain = value; - OnPropertyChanged(); - } + _domain = value; + OnPropertyChanged(); } + } - public ICollectionView WebsiteUriHistoryView { get; } + public ICollectionView WebsiteUriHistoryView { get; } - private bool _isWhoisRunning; - public bool IsWhoisRunning + private bool _isWhoisRunning; + public bool IsWhoisRunning + { + get => _isWhoisRunning; + set { - get => _isWhoisRunning; - set - { - if (value == _isWhoisRunning) - return; + if (value == _isWhoisRunning) + return; - _isWhoisRunning = value; - OnPropertyChanged(); - } + _isWhoisRunning = value; + OnPropertyChanged(); } + } - private string _whoisResult; - public string WhoisResult + private string _whoisResult; + public string WhoisResult + { + get => _whoisResult; + set { - get => _whoisResult; - set - { - if (value == _whoisResult) - return; + if (value == _whoisResult) + return; - _whoisResult = value; - OnPropertyChanged(); - } + _whoisResult = value; + OnPropertyChanged(); } + } - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Contructor, load settings - public WhoisViewModel(IDialogCoordinator instance ,int tabId, string domain) - { - _isLoading = true; + #region Contructor, load settings + public WhoisViewModel(IDialogCoordinator instance ,int tabId, string domain) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - TabId = tabId; - Domain = domain; + TabId = tabId; + Domain = domain; - // Set collection view - WebsiteUriHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Whois_DomainHistory); + // Set collection view + WebsiteUriHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.Whois_DomainHistory); - LoadSettings(); + LoadSettings(); - // Detect if settings have changed... - SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + // Detect if settings have changed... + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; - _isLoading = false; - } + _isLoading = false; + } - public void OnLoaded() - { - if (!_firstLoad) - return; + public void OnLoaded() + { + if (!_firstLoad) + return; - if (!string.IsNullOrEmpty(Domain)) - Query(); + if (!string.IsNullOrEmpty(Domain)) + Query(); - _firstLoad = false; - } + _firstLoad = false; + } - private void LoadSettings() - { + private void LoadSettings() + { - } - #endregion + } + #endregion - #region ICommands & Actions - public ICommand QueryCommand => new RelayCommand(p => QueryAction(), Query_CanExecute); + #region ICommands & Actions + public ICommand QueryCommand => new RelayCommand(p => QueryAction(), Query_CanExecute); - private bool Query_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; + private bool Query_CanExecute(object paramter) => Application.Current.MainWindow != null && !((MetroWindow)Application.Current.MainWindow).IsAnyDialogOpen; - private void QueryAction() - { - Query(); - } + private void QueryAction() + { + Query(); + } - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - private async Task ExportAction() + private async Task ExportAction() + { + var customDialog = new CustomDialog { - var customDialog = new CustomDialog - { - Title = Strings.Export - }; + Title = Strings.Export + }; - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + var exportViewModel = new ExportViewModel(async instance => + { + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - try - { - ExportManager.Export(instance.FilePath, WhoisResult); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Strings.OK; + try + { + ExportManager.Export(instance.FilePath, WhoisResult); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Strings.OK; - await _dialogCoordinator.ShowMessageAsync(this, Strings.Error, Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + await _dialogCoordinator.ShowMessageAsync(this, Strings.Error, Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - SettingsManager.Current.Whois_ExportFileType = instance.FileType; - SettingsManager.Current.Whois_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.TXT}, false, SettingsManager.Current.Whois_ExportFileType, SettingsManager.Current.Whois_ExportFilePath); + SettingsManager.Current.Whois_ExportFileType = instance.FileType; + SettingsManager.Current.Whois_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.TXT}, false, SettingsManager.Current.Whois_ExportFileType, SettingsManager.Current.Whois_ExportFilePath); - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + customDialog.Content = new ExportDialog + { + DataContext = exportViewModel + }; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } - #endregion + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + #endregion - #region Methods - private async Task Query() - { - IsStatusMessageDisplayed = false; - IsWhoisRunning = true; + #region Methods + private async Task Query() + { + IsStatusMessageDisplayed = false; + IsWhoisRunning = true; - WhoisResult = null; + WhoisResult = null; - // Change the tab title (not nice, but it works) - var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); + // Change the tab title (not nice, but it works) + var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); - if (window != null) + if (window != null) + { + foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) { - foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren(window)) - { - tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Domain; - } + tabablzControl.Items.OfType().First(x => x.Id == TabId).Header = Domain; } + } - try - { - var whoisServer = Whois.GetWhoisServer(Domain); - - if (string.IsNullOrEmpty(whoisServer)) - { - StatusMessage = string.Format(Strings.WhoisServerNotFoundForTheDomain, Domain); - IsStatusMessageDisplayed = true; - } - else - { - WhoisResult = await Whois.QueryAsync(Domain, whoisServer); - - AddDomainToHistory(Domain); - } - } - catch (Exception ex) + try + { + var whoisServer = Whois.GetWhoisServer(Domain); + + if (string.IsNullOrEmpty(whoisServer)) { - StatusMessage = ex.Message; + StatusMessage = string.Format(Strings.WhoisServerNotFoundForTheDomain, Domain); IsStatusMessageDisplayed = true; } + else + { + WhoisResult = await Whois.QueryAsync(Domain, whoisServer); - IsWhoisRunning = false; + AddDomainToHistory(Domain); + } } - - public void OnClose() + catch (Exception ex) { - + StatusMessage = ex.Message; + IsStatusMessageDisplayed = true; } - private void AddDomainToHistory(string websiteUri) - { - // Create the new list - var list = ListHelper.Modify(SettingsManager.Current.Whois_DomainHistory.ToList(), websiteUri, SettingsManager.Current.General_HistoryListEntries); + IsWhoisRunning = false; + } - // Clear the old items - SettingsManager.Current.Whois_DomainHistory.Clear(); - OnPropertyChanged(nameof(Domain)); // Raise property changed again, after the collection has been cleared + public void OnClose() + { - // Fill with the new items - list.ForEach(x => SettingsManager.Current.Whois_DomainHistory.Add(x)); - } - #endregion + } - #region Events - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) - { - - } - #endregion + private void AddDomainToHistory(string websiteUri) + { + // Create the new list + var list = ListHelper.Modify(SettingsManager.Current.Whois_DomainHistory.ToList(), websiteUri, SettingsManager.Current.General_HistoryListEntries); + + // Clear the old items + SettingsManager.Current.Whois_DomainHistory.Clear(); + OnPropertyChanged(nameof(Domain)); // Raise property changed again, after the collection has been cleared + + // Fill with the new items + list.ForEach(x => SettingsManager.Current.Whois_DomainHistory.Add(x)); + } + #endregion + + #region Events + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + } + #endregion } \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/WiFiViewModel.cs b/Source/NETworkManager/ViewModels/WiFiViewModel.cs index 847a053786..c1b4c682de 100644 --- a/Source/NETworkManager/ViewModels/WiFiViewModel.cs +++ b/Source/NETworkManager/ViewModels/WiFiViewModel.cs @@ -20,626 +20,625 @@ using System.Windows.Threading; using Windows.Devices.WiFi; -namespace NETworkManager.ViewModels +namespace NETworkManager.ViewModels; + +public class WiFiViewModel : ViewModelBase { - public class WiFiViewModel : ViewModelBase - { - #region Variables - private readonly IDialogCoordinator _dialogCoordinator; + #region Variables + private readonly IDialogCoordinator _dialogCoordinator; - private readonly bool _isLoading; - private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); - private bool _isTimerPaused; + private readonly bool _isLoading; + private readonly DispatcherTimer _autoRefreshTimer = new DispatcherTimer(); + private bool _isTimerPaused; - private bool _sdkContractsFailedToLoad; - public bool SDKContractsFailedToLoad + private bool _sdkContractsFailedToLoad; + public bool SDKContractsFailedToLoad + { + get => _sdkContractsFailedToLoad; + set { - get => _sdkContractsFailedToLoad; - set - { - if (value == _sdkContractsFailedToLoad) - return; + if (value == _sdkContractsFailedToLoad) + return; - _sdkContractsFailedToLoad = value; - OnPropertyChanged(); - } + _sdkContractsFailedToLoad = value; + OnPropertyChanged(); } + } - private bool _isAdaptersLoading; - public bool IsAdaptersLoading + private bool _isAdaptersLoading; + public bool IsAdaptersLoading + { + get => _isAdaptersLoading; + set { - get => _isAdaptersLoading; - set - { - if (value == _isAdaptersLoading) - return; + if (value == _isAdaptersLoading) + return; - _isAdaptersLoading = value; - OnPropertyChanged(); - } + _isAdaptersLoading = value; + OnPropertyChanged(); } + } - private List _adapters = new List(); - public List Adapters + private List _adapters = new List(); + public List Adapters + { + get => _adapters; + set { - get => _adapters; - set - { - if (value == _adapters) - return; + if (value == _adapters) + return; - _adapters = value; - OnPropertyChanged(); - } + _adapters = value; + OnPropertyChanged(); } + } - private WiFiAdapterInfo _selectedAdapters; - public WiFiAdapterInfo SelectedAdapter + private WiFiAdapterInfo _selectedAdapters; + public WiFiAdapterInfo SelectedAdapter + { + get => _selectedAdapters; + set { - get => _selectedAdapters; - set - { - if (value == _selectedAdapters) - return; - - if (value != null) - { - if (!_isLoading) - SettingsManager.Current.WiFi_InterfaceId = value.NetworkInterfaceInfo.Id; + if (value == _selectedAdapters) + return; - Scan(value.WiFiAdapter); - } + if (value != null) + { + if (!_isLoading) + SettingsManager.Current.WiFi_InterfaceId = value.NetworkInterfaceInfo.Id; - _selectedAdapters = value; - OnPropertyChanged(); + Scan(value.WiFiAdapter); } + + _selectedAdapters = value; + OnPropertyChanged(); } + } - private bool _isNetworksLoading; - public bool IsNetworksLoading + private bool _isNetworksLoading; + public bool IsNetworksLoading + { + get => _isNetworksLoading; + set { - get => _isNetworksLoading; - set - { - if (value == _isNetworksLoading) - return; + if (value == _isNetworksLoading) + return; - _isNetworksLoading = value; - OnPropertyChanged(); - } + _isNetworksLoading = value; + OnPropertyChanged(); } + } - private bool _autoRefresh; - public bool AutoRefresh + private bool _autoRefresh; + public bool AutoRefresh + { + get => _autoRefresh; + set { - get => _autoRefresh; - set - { - if (value == _autoRefresh) - return; + if (value == _autoRefresh) + return; - if (!_isLoading) - SettingsManager.Current.WiFi_AutoRefresh = value; + if (!_isLoading) + SettingsManager.Current.WiFi_AutoRefresh = value; - _autoRefresh = value; + _autoRefresh = value; - // Start timer to refresh automatically - if (!_isLoading) - { - if (value) - StartAutoRefreshTimer(); - else - StopAutoRefreshTimer(); - } - - OnPropertyChanged(); + // Start timer to refresh automatically + if (!_isLoading) + { + if (value) + StartAutoRefreshTimer(); + else + StopAutoRefreshTimer(); } + + OnPropertyChanged(); } + } - public ICollectionView AutoRefreshTimes { get; } + public ICollectionView AutoRefreshTimes { get; } - private AutoRefreshTimeInfo _selectedAutoRefreshTime; - public AutoRefreshTimeInfo SelectedAutoRefreshTime + private AutoRefreshTimeInfo _selectedAutoRefreshTime; + public AutoRefreshTimeInfo SelectedAutoRefreshTime + { + get => _selectedAutoRefreshTime; + set { - get => _selectedAutoRefreshTime; - set - { - if (value == _selectedAutoRefreshTime) - return; + if (value == _selectedAutoRefreshTime) + return; - if (!_isLoading) - SettingsManager.Current.WiFi_AutoRefreshTime = value; + if (!_isLoading) + SettingsManager.Current.WiFi_AutoRefreshTime = value; - _selectedAutoRefreshTime = value; + _selectedAutoRefreshTime = value; - if (AutoRefresh) - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); + if (AutoRefresh) + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(value)); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private string _search; - public string Search + private string _search; + public string Search + { + get => _search; + set { - get => _search; - set - { - if (value == _search) - return; + if (value == _search) + return; - _search = value; + _search = value; - NetworksView.Refresh(); + NetworksView.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _show2dot4GHzNetworks; - public bool Show2dot4GHzNetworks + private bool _show2dot4GHzNetworks; + public bool Show2dot4GHzNetworks + { + get => _show2dot4GHzNetworks; + set { - get => _show2dot4GHzNetworks; - set - { - if (value == _show2dot4GHzNetworks) - return; + if (value == _show2dot4GHzNetworks) + return; - if (!_isLoading) - SettingsManager.Current.WiFi_Show2dot4GHzNetworks = value; + if (!_isLoading) + SettingsManager.Current.WiFi_Show2dot4GHzNetworks = value; - _show2dot4GHzNetworks = value; + _show2dot4GHzNetworks = value; - NetworksView.Refresh(); + NetworksView.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private bool _show5GHzNetworks; - public bool Show5GHzNetworks + private bool _show5GHzNetworks; + public bool Show5GHzNetworks + { + get => _show5GHzNetworks; + set { - get => _show5GHzNetworks; - set - { - if (value == _show5GHzNetworks) - return; + if (value == _show5GHzNetworks) + return; - if (!_isLoading) - SettingsManager.Current.WiFi_Show5GHzNetworks = value; + if (!_isLoading) + SettingsManager.Current.WiFi_Show5GHzNetworks = value; - _show5GHzNetworks = value; + _show5GHzNetworks = value; - NetworksView.Refresh(); + NetworksView.Refresh(); - OnPropertyChanged(); - } + OnPropertyChanged(); } + } - private ObservableCollection _networks = new ObservableCollection(); - public ObservableCollection Networks + private ObservableCollection _networks = new ObservableCollection(); + public ObservableCollection Networks + { + get => _networks; + set { - get => _networks; - set - { - if (value != null && value == _networks) - return; + if (value != null && value == _networks) + return; - _networks = value; - OnPropertyChanged(); - } + _networks = value; + OnPropertyChanged(); } + } - public ICollectionView NetworksView { get; } + public ICollectionView NetworksView { get; } - private WiFiNetworkInfo _selectedNetwork; - public WiFiNetworkInfo SelectedNetwork + private WiFiNetworkInfo _selectedNetwork; + public WiFiNetworkInfo SelectedNetwork + { + get => _selectedNetwork; + set { - get => _selectedNetwork; - set - { - if (value == _selectedNetwork) - return; + if (value == _selectedNetwork) + return; - _selectedNetwork = value; - OnPropertyChanged(); - } + _selectedNetwork = value; + OnPropertyChanged(); } + } - private IList _selectedNetworks = new ArrayList(); - public IList SelectedNetworks + private IList _selectedNetworks = new ArrayList(); + public IList SelectedNetworks + { + get => _selectedNetworks; + set { - get => _selectedNetworks; - set - { - if (Equals(value, _selectedNetworks)) - return; + if (Equals(value, _selectedNetworks)) + return; - _selectedNetworks = value; - OnPropertyChanged(); - } + _selectedNetworks = value; + OnPropertyChanged(); } + } - public SeriesCollection Radio1Series { get; set; } = new SeriesCollection(); - public string[] Radio1Labels { get; set; } = new string[] { " ", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", " ", " " }; - public SeriesCollection Radio2Series { get; set; } = new SeriesCollection(); - public string[] Radio2Labels { get; set; } = new string[] { " ", " ", "36", "40", "44", "48", "52", "56", "60", "64", "", "", "", "", "100", "104", "108", "112", "116", "120", "124", "128", "132", "136", "140", "144", "149", "153", "157", "161", "165", " ", " " }; - public Func FormatterdBm { get; set; } = value => $"- {100 - value} dBm"; // Reverse y-axis 0 to -100 + public SeriesCollection Radio1Series { get; set; } = new SeriesCollection(); + public string[] Radio1Labels { get; set; } = new string[] { " ", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", " ", " " }; + public SeriesCollection Radio2Series { get; set; } = new SeriesCollection(); + public string[] Radio2Labels { get; set; } = new string[] { " ", " ", "36", "40", "44", "48", "52", "56", "60", "64", "", "", "", "", "100", "104", "108", "112", "116", "120", "124", "128", "132", "136", "140", "144", "149", "153", "157", "161", "165", " ", " " }; + public Func FormatterdBm { get; set; } = value => $"- {100 - value} dBm"; // Reverse y-axis 0 to -100 - private bool _isStatusMessageDisplayed; - public bool IsStatusMessageDisplayed + private bool _isStatusMessageDisplayed; + public bool IsStatusMessageDisplayed + { + get => _isStatusMessageDisplayed; + set { - get => _isStatusMessageDisplayed; - set - { - if (value == _isStatusMessageDisplayed) - return; + if (value == _isStatusMessageDisplayed) + return; - _isStatusMessageDisplayed = value; - OnPropertyChanged(); - } + _isStatusMessageDisplayed = value; + OnPropertyChanged(); } + } - private bool _isBackgroundSearchRunning; - public bool IsBackgroundSearchRunning + private bool _isBackgroundSearchRunning; + public bool IsBackgroundSearchRunning + { + get => _isBackgroundSearchRunning; + set { - get => _isBackgroundSearchRunning; - set - { - if (value == _isBackgroundSearchRunning) - return; + if (value == _isBackgroundSearchRunning) + return; - _isBackgroundSearchRunning = value; - OnPropertyChanged(); - } + _isBackgroundSearchRunning = value; + OnPropertyChanged(); } + } - private string _statusMessage; - public string StatusMessage + private string _statusMessage; + public string StatusMessage + { + get => _statusMessage; + set { - get => _statusMessage; - set - { - if (value == _statusMessage) - return; + if (value == _statusMessage) + return; - _statusMessage = value; - OnPropertyChanged(); - } + _statusMessage = value; + OnPropertyChanged(); } - #endregion + } + #endregion - #region Constructor, load settings - public WiFiViewModel(IDialogCoordinator instance) - { - _isLoading = true; + #region Constructor, load settings + public WiFiViewModel(IDialogCoordinator instance) + { + _isLoading = true; - _dialogCoordinator = instance; + _dialogCoordinator = instance; - // Result view + search - NetworksView = CollectionViewSource.GetDefaultView(Networks); - NetworksView.SortDescriptions.Add(new SortDescription(nameof(WiFiNetworkInfo.SSID), ListSortDirection.Ascending)); - NetworksView.Filter = o => + // Result view + search + NetworksView = CollectionViewSource.GetDefaultView(Networks); + NetworksView.SortDescriptions.Add(new SortDescription(nameof(WiFiNetworkInfo.SSID), ListSortDirection.Ascending)); + NetworksView.Filter = o => + { + if (o is WiFiNetworkInfo info) { - if (o is WiFiNetworkInfo info) - { - if (WiFi.Is2dot4GHzNetwork(info.ChannelCenterFrequencyInKilohertz) && !Show2dot4GHzNetworks) - return false; - - if (WiFi.Is5GHzNetwork(info.ChannelCenterFrequencyInKilohertz) && !Show5GHzNetworks) - return false; - - if (string.IsNullOrEmpty(Search)) - return true; - - - // Search by: SSID, Security, Channel, BSSID (MAC address), Vendor, Phy kind - return info.SSID.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || - WiFi.GetHumanReadableNetworkAuthenticationType(info.AuthenticationType).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || - $"{WiFi.GetChannelFromChannelFrequency(info.ChannelCenterFrequencyInKilohertz)}".IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || - info.BSSID.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || - OUILookup.Lookup(info.BSSID).FirstOrDefault()?.Vendor.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || - WiFi.GetHumandReadablePhyKind(info.PhyKind).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1; - } - else - { + if (WiFi.Is2dot4GHzNetwork(info.ChannelCenterFrequencyInKilohertz) && !Show2dot4GHzNetworks) return false; - } - }; - AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); - SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.WiFi_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.WiFi_AutoRefreshTime.TimeUnit)); + if (WiFi.Is5GHzNetwork(info.ChannelCenterFrequencyInKilohertz) && !Show5GHzNetworks) + return false; - _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; + if (string.IsNullOrEmpty(Search)) + return true; - LoadSettings(); - LoadAdapters(); + // Search by: SSID, Security, Channel, BSSID (MAC address), Vendor, Phy kind + return info.SSID.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + WiFi.GetHumanReadableNetworkAuthenticationType(info.AuthenticationType).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + $"{WiFi.GetChannelFromChannelFrequency(info.ChannelCenterFrequencyInKilohertz)}".IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + info.BSSID.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + OUILookup.Lookup(info.BSSID).FirstOrDefault()?.Vendor.IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1 || + WiFi.GetHumandReadablePhyKind(info.PhyKind).IndexOf(Search, StringComparison.OrdinalIgnoreCase) > -1; + } + else + { + return false; + } + }; - _isLoading = false; - } + AutoRefreshTimes = CollectionViewSource.GetDefaultView(AutoRefreshTime.GetDefaults); + SelectedAutoRefreshTime = AutoRefreshTimes.SourceCollection.Cast().FirstOrDefault(x => (x.Value == SettingsManager.Current.WiFi_AutoRefreshTime.Value && x.TimeUnit == SettingsManager.Current.WiFi_AutoRefreshTime.TimeUnit)); - private void LoadSettings() - { - Show2dot4GHzNetworks = SettingsManager.Current.WiFi_Show2dot4GHzNetworks; - Show5GHzNetworks = SettingsManager.Current.WiFi_Show5GHzNetworks; - } - #endregion + _autoRefreshTimer.Tick += AutoRefreshTimer_Tick; - #region ICommands & Actions - public ICommand ReloadAdaptersCommand => new RelayCommand(p => ReloadAdapterAction(), ReloadAdapters_CanExecute); + LoadSettings(); - private bool ReloadAdapters_CanExecute(object obj) => !IsAdaptersLoading; + LoadAdapters(); - private void ReloadAdapterAction() - { - ReloadAdapter(); - } + _isLoading = false; + } - public ICommand ScanNetworksCommand => new RelayCommand(p => ScanNetworksAction(), ScanNetworks_CanExecute); + private void LoadSettings() + { + Show2dot4GHzNetworks = SettingsManager.Current.WiFi_Show2dot4GHzNetworks; + Show5GHzNetworks = SettingsManager.Current.WiFi_Show5GHzNetworks; + } + #endregion - private bool ScanNetworks_CanExecute(object obj) => !IsAdaptersLoading && !IsNetworksLoading; + #region ICommands & Actions + public ICommand ReloadAdaptersCommand => new RelayCommand(p => ReloadAdapterAction(), ReloadAdapters_CanExecute); - private async Task ScanNetworksAction() - { - await Scan(SelectedAdapter.WiFiAdapter, true); - } + private bool ReloadAdapters_CanExecute(object obj) => !IsAdaptersLoading; - public ICommand ExportCommand => new RelayCommand(p => ExportAction()); + private void ReloadAdapterAction() + { + ReloadAdapter(); + } - private void ExportAction() - { - Export(); - } - #endregion + public ICommand ScanNetworksCommand => new RelayCommand(p => ScanNetworksAction(), ScanNetworks_CanExecute); - #region Methods - private async Task LoadAdapters() - { - IsAdaptersLoading = true; + private bool ScanNetworks_CanExecute(object obj) => !IsAdaptersLoading && !IsNetworksLoading; - try - { - Adapters = await WiFi.GetAdapterAsync(); + private async Task ScanNetworksAction() + { + await Scan(SelectedAdapter.WiFiAdapter, true); + } - // Get the last selected interface, if it is still available on this machine... - if (Adapters.Count > 0) - { - var info = Adapters.FirstOrDefault(s => s.NetworkInterfaceInfo.Id.ToString() == SettingsManager.Current.WiFi_InterfaceId); + public ICommand ExportCommand => new RelayCommand(p => ExportAction()); - SelectedAdapter = info ?? Adapters[0]; - } - } - catch (FileNotFoundException) // This exception is thrown, when the Microsoft.Windows.SDK.Contracts is not available... - { - SDKContractsFailedToLoad = true; - } + private void ExportAction() + { + Export(); + } + #endregion - IsAdaptersLoading = false; - } + #region Methods + private async Task LoadAdapters() + { + IsAdaptersLoading = true; - private async Task ReloadAdapter() + try { - IsAdaptersLoading = true; - - await Task.Delay(2000); // Make the user happy, let him see a reload animation (and he cannot spam the reload command) + Adapters = await WiFi.GetAdapterAsync(); - string id = string.Empty; - - if (SelectedAdapter != null) - id = SelectedAdapter.NetworkInterfaceInfo.Id; - - try + // Get the last selected interface, if it is still available on this machine... + if (Adapters.Count > 0) { - Adapters = await WiFi.GetAdapterAsync(); + var info = Adapters.FirstOrDefault(s => s.NetworkInterfaceInfo.Id.ToString() == SettingsManager.Current.WiFi_InterfaceId); - if (Adapters.Count > 0) - SelectedAdapter = string.IsNullOrEmpty(id) ? Adapters.FirstOrDefault() : Adapters.FirstOrDefault(x => x.NetworkInterfaceInfo.Id == id); + SelectedAdapter = info ?? Adapters[0]; } - catch (FileNotFoundException) // This exception is thrown, when the Microsoft.Windows.SDK.Contracts is not available... - { - SDKContractsFailedToLoad = true; - } - - IsAdaptersLoading = false; } - - private async Task Scan(WiFiAdapter adapter, bool fromBackground = false) + catch (FileNotFoundException) // This exception is thrown, when the Microsoft.Windows.SDK.Contracts is not available... { - if (fromBackground) - { - StatusMessage = Localization.Resources.Strings.SearchingForNetworksDots; - IsBackgroundSearchRunning = true; - } - else - { - IsStatusMessageDisplayed = false; - IsNetworksLoading = true; - } - - IEnumerable networks = await WiFi.GetNetworksAsync(adapter); + SDKContractsFailedToLoad = true; + } - Networks.Clear(); + IsAdaptersLoading = false; + } - Radio1Series.Clear(); - Radio2Series.Clear(); + private async Task ReloadAdapter() + { + IsAdaptersLoading = true; - foreach (var network in networks) - { - // Identify hidden networks - if (string.IsNullOrEmpty(network.SSID)) - network.SSID = Localization.Resources.Strings.HiddenNetwork; + await Task.Delay(2000); // Make the user happy, let him see a reload animation (and he cannot spam the reload command) - Networks.Add(network); + string id = string.Empty; - if (WiFi.ConvertChannelFrequencyToGigahertz(network.ChannelCenterFrequencyInKilohertz) < 5) // 2.4 GHz - AddNetworkToRadio1Chart(network); - else - AddNetworkToRadio2Chart(network); - } + if (SelectedAdapter != null) + id = SelectedAdapter.NetworkInterfaceInfo.Id; - IsStatusMessageDisplayed = true; - StatusMessage = string.Format(Localization.Resources.Strings.LastScanAtX, DateTime.Now.ToLongTimeString()); + try + { + Adapters = await WiFi.GetAdapterAsync(); - if (fromBackground) - IsBackgroundSearchRunning = false; - else - IsNetworksLoading = false; + if (Adapters.Count > 0) + SelectedAdapter = string.IsNullOrEmpty(id) ? Adapters.FirstOrDefault() : Adapters.FirstOrDefault(x => x.NetworkInterfaceInfo.Id == id); } - - private ChartValues GetDefaultChartValues(WiFi.Radio radio) + catch (FileNotFoundException) // This exception is thrown, when the Microsoft.Windows.SDK.Contracts is not available... { - ChartValues values = new ChartValues(); + SDKContractsFailedToLoad = true; + } - for (int i = 0; i < (radio == WiFi.Radio.One ? Radio1Labels.Length : Radio2Labels.Length); i++) - values.Add(-1); + IsAdaptersLoading = false; + } - return values; + private async Task Scan(WiFiAdapter adapter, bool fromBackground = false) + { + if (fromBackground) + { + StatusMessage = Localization.Resources.Strings.SearchingForNetworksDots; + IsBackgroundSearchRunning = true; } - - private ChartValues SetChartValues(WiFiNetworkInfo network, WiFi.Radio radio, int index) + else { - ChartValues values = GetDefaultChartValues(radio); + IsStatusMessageDisplayed = false; + IsNetworksLoading = true; + } - double reverseMilliwatts = 100 - (network.NetworkRssiInDecibelMilliwatts * -1); + IEnumerable networks = await WiFi.GetNetworksAsync(adapter); - values[index - 2] = -1; - values[index - 1] = reverseMilliwatts; - values[index] = reverseMilliwatts; - values[index + 1] = reverseMilliwatts; - values[index + 2] = -1; + Networks.Clear(); - return values; - } + Radio1Series.Clear(); + Radio2Series.Clear(); - private void AddNetworkToRadio1Chart(WiFiNetworkInfo network) + foreach (var network in networks) { - int index = Array.IndexOf(Radio1Labels, $"{WiFi.GetChannelFromChannelFrequency(network.ChannelCenterFrequencyInKilohertz)}"); + // Identify hidden networks + if (string.IsNullOrEmpty(network.SSID)) + network.SSID = Localization.Resources.Strings.HiddenNetwork; - Radio1Series.Add(new LineSeries - { - Title = network.SSID, - Values = SetChartValues(network, WiFi.Radio.One, index), - PointGeometry = null, - LineSmoothness = 0 - }); + Networks.Add(network); + + if (WiFi.ConvertChannelFrequencyToGigahertz(network.ChannelCenterFrequencyInKilohertz) < 5) // 2.4 GHz + AddNetworkToRadio1Chart(network); + else + AddNetworkToRadio2Chart(network); } - private void AddNetworkToRadio2Chart(WiFiNetworkInfo network) - { - int index = Array.IndexOf(Radio2Labels, $"{WiFi.GetChannelFromChannelFrequency(network.ChannelCenterFrequencyInKilohertz)}"); + IsStatusMessageDisplayed = true; + StatusMessage = string.Format(Localization.Resources.Strings.LastScanAtX, DateTime.Now.ToLongTimeString()); - Radio2Series.Add(new LineSeries - { - Title = network.SSID, - Values = SetChartValues(network, WiFi.Radio.Two, index), - PointGeometry = null, - LineSmoothness = 0 - }); - } + if (fromBackground) + IsBackgroundSearchRunning = false; + else + IsNetworksLoading = false; + } - private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) - { - _autoRefreshTimer.Interval = timeSpan; - } + private ChartValues GetDefaultChartValues(WiFi.Radio radio) + { + ChartValues values = new ChartValues(); - private void StartAutoRefreshTimer() - { - ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); + for (int i = 0; i < (radio == WiFi.Radio.One ? Radio1Labels.Length : Radio2Labels.Length); i++) + values.Add(-1); - _autoRefreshTimer.Start(); - } + return values; + } - private void StopAutoRefreshTimer() - { - _autoRefreshTimer.Stop(); - } + private ChartValues SetChartValues(WiFiNetworkInfo network, WiFi.Radio radio, int index) + { + ChartValues values = GetDefaultChartValues(radio); - private void PauseAutoRefreshTimer() - { - if (!_autoRefreshTimer.IsEnabled) - return; + double reverseMilliwatts = 100 - (network.NetworkRssiInDecibelMilliwatts * -1); - _autoRefreshTimer.Stop(); - _isTimerPaused = true; - } + values[index - 2] = -1; + values[index - 1] = reverseMilliwatts; + values[index] = reverseMilliwatts; + values[index + 1] = reverseMilliwatts; + values[index + 2] = -1; - private void ResumeAutoRefreshTimer() - { - if (!_isTimerPaused) - return; + return values; + } - _autoRefreshTimer.Start(); - _isTimerPaused = false; - } + private void AddNetworkToRadio1Chart(WiFiNetworkInfo network) + { + int index = Array.IndexOf(Radio1Labels, $"{WiFi.GetChannelFromChannelFrequency(network.ChannelCenterFrequencyInKilohertz)}"); - private async Task Connect() + Radio1Series.Add(new LineSeries { + Title = network.SSID, + Values = SetChartValues(network, WiFi.Radio.One, index), + PointGeometry = null, + LineSmoothness = 0 + }); + } - } + private void AddNetworkToRadio2Chart(WiFiNetworkInfo network) + { + int index = Array.IndexOf(Radio2Labels, $"{WiFi.GetChannelFromChannelFrequency(network.ChannelCenterFrequencyInKilohertz)}"); - private async Task Export() + Radio2Series.Add(new LineSeries { - var customDialog = new CustomDialog - { - Title = Localization.Resources.Strings.Export - }; + Title = network.SSID, + Values = SetChartValues(network, WiFi.Radio.Two, index), + PointGeometry = null, + LineSmoothness = 0 + }); + } - var exportViewModel = new ExportViewModel(async instance => - { - await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); + private void ChangeAutoRefreshTimerInterval(TimeSpan timeSpan) + { + _autoRefreshTimer.Interval = timeSpan; + } - try - { - ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? Networks : new ObservableCollection(SelectedNetworks.Cast().ToArray())); - } - catch (Exception ex) - { - var settings = AppearanceManager.MetroDialog; - settings.AffirmativeButtonText = Localization.Resources.Strings.OK; + private void StartAutoRefreshTimer() + { + ChangeAutoRefreshTimerInterval(AutoRefreshTime.CalculateTimeSpan(SelectedAutoRefreshTime)); - await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); - } + _autoRefreshTimer.Start(); + } - SettingsManager.Current.WiFi_ExportFileType = instance.FileType; - SettingsManager.Current.WiFi_ExportFilePath = instance.FilePath; - }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.WiFi_ExportFileType, SettingsManager.Current.WiFi_ExportFilePath); + private void StopAutoRefreshTimer() + { + _autoRefreshTimer.Stop(); + } - customDialog.Content = new ExportDialog - { - DataContext = exportViewModel - }; + private void PauseAutoRefreshTimer() + { + if (!_autoRefreshTimer.IsEnabled) + return; - await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); - } + _autoRefreshTimer.Stop(); + _isTimerPaused = true; + } + + private void ResumeAutoRefreshTimer() + { + if (!_isTimerPaused) + return; + + _autoRefreshTimer.Start(); + _isTimerPaused = false; + } + + private async Task Connect() + { - public void OnViewVisible() + } + + private async Task Export() + { + var customDialog = new CustomDialog { - ResumeAutoRefreshTimer(); - } + Title = Localization.Resources.Strings.Export + }; - public void OnViewHide() + var exportViewModel = new ExportViewModel(async instance => { - PauseAutoRefreshTimer(); - } + await _dialogCoordinator.HideMetroDialogAsync(this, customDialog); - #endregion + try + { + ExportManager.Export(instance.FilePath, instance.FileType, instance.ExportAll ? Networks : new ObservableCollection(SelectedNetworks.Cast().ToArray())); + } + catch (Exception ex) + { + var settings = AppearanceManager.MetroDialog; + settings.AffirmativeButtonText = Localization.Resources.Strings.OK; - #region Events - private async void AutoRefreshTimer_Tick(object sender, EventArgs e) - { - // Stop timer... - _autoRefreshTimer.Stop(); + await _dialogCoordinator.ShowMessageAsync(this, Localization.Resources.Strings.Error, Localization.Resources.Strings.AnErrorOccurredWhileExportingTheData + Environment.NewLine + Environment.NewLine + ex.Message, MessageDialogStyle.Affirmative, settings); + } - // Scan networks - await Scan(SelectedAdapter.WiFiAdapter, true); + SettingsManager.Current.WiFi_ExportFileType = instance.FileType; + SettingsManager.Current.WiFi_ExportFilePath = instance.FilePath; + }, instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); }, new ExportManager.ExportFileType[] { ExportManager.ExportFileType.CSV, ExportManager.ExportFileType.XML, ExportManager.ExportFileType.JSON }, true, SettingsManager.Current.WiFi_ExportFileType, SettingsManager.Current.WiFi_ExportFilePath); - // Restart timer... - _autoRefreshTimer.Start(); - } - private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + customDialog.Content = new ExportDialog { - } - #endregion + DataContext = exportViewModel + }; + + await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); + } + + public void OnViewVisible() + { + ResumeAutoRefreshTimer(); + } + + public void OnViewHide() + { + PauseAutoRefreshTimer(); + } + + #endregion + + #region Events + private async void AutoRefreshTimer_Tick(object sender, EventArgs e) + { + // Stop timer... + _autoRefreshTimer.Stop(); + + // Scan networks + await Scan(SelectedAdapter.WiFiAdapter, true); + + // Restart timer... + _autoRefreshTimer.Start(); + } + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { } + #endregion } \ No newline at end of file From 31beb0bb9ef90aaadc3f0d556ec33d37dbf46084 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Mon, 6 Mar 2023 21:01:19 +0100 Subject: [PATCH 11/11] Chore: Use .NET 7 syntax --- .../Views/ARPTableAddEntryDialog.xaml.cs | 21 ++- .../NETworkManager/Views/ARPTableView.xaml.cs | 43 +++-- .../Views/AWSProfileDialog.xaml.cs | 21 ++- .../AWSSessionManagerConnectDialog.xaml.cs | 21 ++- .../Views/AWSSessionManagerHostView.xaml.cs | 101 ++++++----- .../AWSSessionManagerSettingsView.xaml.cs | 73 ++++---- Source/NETworkManager/Views/AboutView.xaml.cs | 39 ++-- .../Views/BitCalculatorSettingsView.xaml.cs | 17 +- .../Views/BitCalculatorView.xaml.cs | 43 +++-- .../Views/ConfirmDeleteDialog.xaml.cs | 11 +- .../Views/ConnectionsView.xaml.cs | 43 +++-- .../CredentialsChangePasswordDialog.xaml.cs | 21 ++- .../Views/CredentialsPasswordDialog.xaml.cs | 21 ++- ...edentialsPasswordProfileFileDialog.xaml.cs | 21 ++- .../CredentialsSetPasswordDialog.xaml.cs | 21 ++- .../Views/CustomCommandDialog.xaml.cs | 21 ++- .../Views/DNSLookupHostView.xaml.cs | 75 ++++---- .../Views/DNSLookupSettingsView.xaml.cs | 35 ++-- .../Views/DNSLookupView.xaml.cs | 67 ++++--- .../Views/DashboardSettingsView.xaml.cs | 17 +- .../Views/DashboardView.xaml.cs | 39 ++-- .../Views/DiscoveryProtocolView.xaml.cs | 43 +++-- .../Views/DropdownDialog.xaml.cs | 17 +- .../NETworkManager/Views/ExportDialog.xaml.cs | 11 +- .../Views/FirstRunDialog.xaml.cs | 11 +- .../NETworkManager/Views/GroupDialog.xaml.cs | 61 ++++--- .../IPAddressAndSubnetmaskDialog.xaml.cs | 21 ++- .../Views/IPAddressDialog.xaml.cs | 21 ++- .../Views/IPScannerHostView.xaml.cs | 85 +++++---- .../Views/IPScannerSettingsView.xaml.cs | 33 ++-- .../Views/IPScannerView.xaml.cs | 97 +++++----- .../Views/ListenersView.xaml.cs | 43 +++-- .../Views/LookupHostView.xaml.cs | 33 ++-- .../Views/LookupOUILookupView.xaml.cs | 27 ++- .../Views/LookupPortLookupView.xaml.cs | 27 ++- .../Views/NetworkConnectionView.xaml.cs | 43 +++-- .../Views/NetworkInterfaceView.xaml.cs | 43 +++-- .../Views/PingMonitorHostView.xaml.cs | 65 ++++--- .../Views/PingMonitorSettingsView.xaml.cs | 17 +- .../Views/PingMonitorView.xaml.cs | 55 +++--- .../Views/PortProfileDialog.xaml.cs | 21 ++- .../Views/PortProfilesDialog.xaml.cs | 33 ++-- .../Views/PortScannerHostView.xaml.cs | 85 +++++---- .../Views/PortScannerSettingsView.xaml.cs | 35 ++-- .../Views/PortScannerView.xaml.cs | 65 ++++--- .../Views/PowerShellConnectDialog.xaml.cs | 21 ++- .../Views/PowerShellHostView.xaml.cs | 91 +++++----- .../Views/PowerShellSettingsView.xaml.cs | 43 +++-- .../Views/ProfileDialog.xaml.cs | 65 ++++--- .../Views/ProfileFileDialog.xaml.cs | 21 ++- .../NETworkManager/Views/ProfilesView.xaml.cs | 59 +++---- .../Views/PuTTYConnectDialog.xaml.cs | 21 ++- .../Views/PuTTYHostView.xaml.cs | 93 +++++----- .../Views/PuTTYSettingsView.xaml.cs | 167 +++++++++--------- .../Views/RemoteDesktopConnectDialog.xaml.cs | 21 ++- .../Views/RemoteDesktopHostView.xaml.cs | 97 +++++----- .../Views/RemoteDesktopSettingsView.xaml.cs | 17 +- .../NETworkManager/Views/SNMPHostView.xaml.cs | 43 +++-- .../Views/SNMPSettingsView.xaml.cs | 17 +- Source/NETworkManager/Views/SNMPView.xaml.cs | 37 ++-- .../Views/SNTPLookupHostView.xaml.cs | 35 ++-- .../Views/SNTPLookupSettingsView.xaml.cs | 35 ++-- .../Views/SNTPLookupView.xaml.cs | 39 ++-- .../ServerConnectionInfoProfileDialog.xaml.cs | 41 +++-- .../Views/SettingsAppearanceView.xaml.cs | 17 +- .../Views/SettingsAutostartView.xaml.cs | 17 +- .../Views/SettingsGeneralView.xaml.cs | 45 +++-- .../Views/SettingsHotKeysView.xaml.cs | 17 +- .../Views/SettingsLanguageView.xaml.cs | 17 +- .../Views/SettingsNetworkView.xaml.cs | 17 +- .../Views/SettingsProfilesView.xaml.cs | 61 ++++--- .../Views/SettingsSettingsView.xaml.cs | 39 ++-- .../Views/SettingsStatusView.xaml.cs | 17 +- .../Views/SettingsUpdateView.xaml.cs | 17 +- .../NETworkManager/Views/SettingsView.xaml.cs | 67 ++++--- .../Views/SettingsWindowView.xaml.cs | 17 +- .../SubnetCalculatorCalculatorView.xaml.cs | 17 +- .../Views/SubnetCalculatorHostView.xaml.cs | 33 ++-- .../SubnetCalculatorSubnettingView.xaml.cs | 37 ++-- .../SubnetCalculatorWideSubnetView.xaml.cs | 27 ++- .../Views/TigerVNCConnectDialog.xaml.cs | 21 ++- .../Views/TigerVNCHostView.xaml.cs | 103 ++++++----- .../Views/TigerVNCSettingsView.xaml.cs | 43 +++-- .../Views/TracerouteHostView.xaml.cs | 85 +++++---- .../Views/TracerouteSettingsView.xaml.cs | 17 +- .../Views/TracerouteView.xaml.cs | 55 +++--- .../Views/WakeOnLANSettingsView.xaml.cs | 17 +- .../Views/WakeOnLANView.xaml.cs | 43 +++-- .../Views/WebConsoleConnectDialog.xaml.cs | 21 ++- .../Views/WebConsoleHostView.xaml.cs | 57 +++--- .../Views/WhoisHostView.xaml.cs | 65 ++++--- .../Views/WhoisSettingsView.xaml.cs | 17 +- Source/NETworkManager/Views/WhoisView.xaml.cs | 35 ++-- Source/NETworkManager/Views/WiFiView.xaml.cs | 45 +++-- 94 files changed, 1859 insertions(+), 1953 deletions(-) diff --git a/Source/NETworkManager/Views/ARPTableAddEntryDialog.xaml.cs b/Source/NETworkManager/Views/ARPTableAddEntryDialog.xaml.cs index 34de9e7aa1..2f5d859a4e 100644 --- a/Source/NETworkManager/Views/ARPTableAddEntryDialog.xaml.cs +++ b/Source/NETworkManager/Views/ARPTableAddEntryDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ARPTableAddEntryDialog { - public partial class ARPTableAddEntryDialog + public ARPTableAddEntryDialog() { - public ARPTableAddEntryDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxIPAddress.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxIPAddress.Focus(); } } diff --git a/Source/NETworkManager/Views/ARPTableView.xaml.cs b/Source/NETworkManager/Views/ARPTableView.xaml.cs index 1e73084489..ced6b23d95 100644 --- a/Source/NETworkManager/Views/ARPTableView.xaml.cs +++ b/Source/NETworkManager/Views/ARPTableView.xaml.cs @@ -2,32 +2,31 @@ using NETworkManager.ViewModels; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ARPTableView { - public partial class ARPTableView - { - private readonly ARPTableViewModel _viewModel = new ARPTableViewModel(DialogCoordinator.Instance); + private readonly ARPTableViewModel _viewModel = new ARPTableViewModel(DialogCoordinator.Instance); - public ARPTableView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public ARPTableView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/AWSProfileDialog.xaml.cs b/Source/NETworkManager/Views/AWSProfileDialog.xaml.cs index 999dd9ab50..7ec18219b1 100644 --- a/Source/NETworkManager/Views/AWSProfileDialog.xaml.cs +++ b/Source/NETworkManager/Views/AWSProfileDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class AWSProfileDialog { - public partial class AWSProfileDialog + public AWSProfileDialog() { - public AWSProfileDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxProfile.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxProfile.Focus(); } } diff --git a/Source/NETworkManager/Views/AWSSessionManagerConnectDialog.xaml.cs b/Source/NETworkManager/Views/AWSSessionManagerConnectDialog.xaml.cs index 160ff3fd3c..45f62c0c56 100644 --- a/Source/NETworkManager/Views/AWSSessionManagerConnectDialog.xaml.cs +++ b/Source/NETworkManager/Views/AWSSessionManagerConnectDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class AWSSessionManagerConnectDialog { - public partial class AWSSessionManagerConnectDialog + public AWSSessionManagerConnectDialog() { - public AWSSessionManagerConnectDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - ComboBoxInstanceID.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + ComboBoxInstanceID.Focus(); } } diff --git a/Source/NETworkManager/Views/AWSSessionManagerHostView.xaml.cs b/Source/NETworkManager/Views/AWSSessionManagerHostView.xaml.cs index a58409a37a..c05e57674a 100644 --- a/Source/NETworkManager/Views/AWSSessionManagerHostView.xaml.cs +++ b/Source/NETworkManager/Views/AWSSessionManagerHostView.xaml.cs @@ -4,57 +4,56 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class AWSSessionManagerHostView { - public partial class AWSSessionManagerHostView - { - private readonly AWSSessionManagerHostViewModel _viewModel = new(DialogCoordinator.Instance); - - private bool _loaded; - - public AWSSessionManagerHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.AWSSessionManager.ToString(); - } - - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _loaded = true; - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ConnectProfileCommand.Execute(null); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible(bool fromSettings) - { - _viewModel.OnViewVisible(fromSettings); - } - - public void OnProfileLoaded() - { - _viewModel.OnProfileLoaded(); - } - - public void FocusEmbeddedWindow() - { - _viewModel.FocusEmbeddedWindow(); - } + private readonly AWSSessionManagerHostViewModel _viewModel = new(DialogCoordinator.Instance); + + private bool _loaded; + + public AWSSessionManagerHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.AWSSessionManager.ToString(); + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _loaded = true; + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ConnectProfileCommand.Execute(null); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible(bool fromSettings) + { + _viewModel.OnViewVisible(fromSettings); + } + + public void OnProfileLoaded() + { + _viewModel.OnProfileLoaded(); + } + + public void FocusEmbeddedWindow() + { + _viewModel.FocusEmbeddedWindow(); } } diff --git a/Source/NETworkManager/Views/AWSSessionManagerSettingsView.xaml.cs b/Source/NETworkManager/Views/AWSSessionManagerSettingsView.xaml.cs index e104dc26b2..daf16d77c8 100644 --- a/Source/NETworkManager/Views/AWSSessionManagerSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/AWSSessionManagerSettingsView.xaml.cs @@ -4,44 +4,43 @@ using System.Windows.Controls; using System.Windows.Input; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class AWSSessionManagerSettingsView { - public partial class AWSSessionManagerSettingsView + private readonly AWSSessionManagerSettingsViewModel _viewModel = new(DialogCoordinator.Instance); + + public AWSSessionManagerSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } + + private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) + { + if (!e.Data.GetDataPresent(DataFormats.FileDrop)) + return; + + var files = (string[])e.Data.GetData(DataFormats.FileDrop); + + if (files != null) + _viewModel.SetFilePathFromDragDrop(files[0]); + } + + private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) + { + e.Effects = DragDropEffects.Copy; + e.Handled = true; + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) { - private readonly AWSSessionManagerSettingsViewModel _viewModel = new(DialogCoordinator.Instance); - - public AWSSessionManagerSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } - - private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) - { - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) - return; - - var files = (string[])e.Data.GetData(DataFormats.FileDrop); - - if (files != null) - _viewModel.SetFilePathFromDragDrop(files[0]); - } - - private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) - { - e.Effects = DragDropEffects.Copy; - e.Handled = true; - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) - { - _viewModel.EditAWSProfile(); - } + _viewModel.EditAWSProfile(); } } diff --git a/Source/NETworkManager/Views/AboutView.xaml.cs b/Source/NETworkManager/Views/AboutView.xaml.cs index b60c7b4895..b1de095a30 100644 --- a/Source/NETworkManager/Views/AboutView.xaml.cs +++ b/Source/NETworkManager/Views/AboutView.xaml.cs @@ -1,31 +1,30 @@ using NETworkManager.ViewModels; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class AboutView { - public partial class AboutView - { - private readonly AboutViewModel _viewModel = new AboutViewModel(); + private readonly AboutViewModel _viewModel = new AboutViewModel(); - public AboutView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public AboutView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) menu.DataContext = _viewModel; + } - // Fix mouse wheel when using DataGrid (https://stackoverflow.com/a/16235785/4986782) - private void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e) - { - var scv = (ScrollViewer)sender; + // Fix mouse wheel when using DataGrid (https://stackoverflow.com/a/16235785/4986782) + private void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e) + { + var scv = (ScrollViewer)sender; - scv.ScrollToVerticalOffset(scv.VerticalOffset - e.Delta); + scv.ScrollToVerticalOffset(scv.VerticalOffset - e.Delta); - e.Handled = true; - } + e.Handled = true; } } diff --git a/Source/NETworkManager/Views/BitCalculatorSettingsView.xaml.cs b/Source/NETworkManager/Views/BitCalculatorSettingsView.xaml.cs index d68f666892..2336cb3ada 100644 --- a/Source/NETworkManager/Views/BitCalculatorSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/BitCalculatorSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class BitCalculatorSettingsView { - public partial class BitCalculatorSettingsView - { - private readonly BitCalculatorSettingsViewModel _viewModel = new(); + private readonly BitCalculatorSettingsViewModel _viewModel = new(); - public BitCalculatorSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public BitCalculatorSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/BitCalculatorView.xaml.cs b/Source/NETworkManager/Views/BitCalculatorView.xaml.cs index c12ea9666b..f4411fa28f 100644 --- a/Source/NETworkManager/Views/BitCalculatorView.xaml.cs +++ b/Source/NETworkManager/Views/BitCalculatorView.xaml.cs @@ -3,32 +3,31 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class BitCalculatorView { - public partial class BitCalculatorView - { - private readonly BitCalculatorViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly BitCalculatorViewModel _viewModel = new(DialogCoordinator.Instance); - public BitCalculatorView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public BitCalculatorView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/ConfirmDeleteDialog.xaml.cs b/Source/NETworkManager/Views/ConfirmDeleteDialog.xaml.cs index ddc2454751..0b0bbb78dc 100644 --- a/Source/NETworkManager/Views/ConfirmDeleteDialog.xaml.cs +++ b/Source/NETworkManager/Views/ConfirmDeleteDialog.xaml.cs @@ -1,10 +1,9 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ConfirmDeleteDialog { - public partial class ConfirmDeleteDialog + public ConfirmDeleteDialog() { - public ConfirmDeleteDialog() - { - InitializeComponent(); - } + InitializeComponent(); } } diff --git a/Source/NETworkManager/Views/ConnectionsView.xaml.cs b/Source/NETworkManager/Views/ConnectionsView.xaml.cs index a443b1ab3f..eb47a5aae4 100644 --- a/Source/NETworkManager/Views/ConnectionsView.xaml.cs +++ b/Source/NETworkManager/Views/ConnectionsView.xaml.cs @@ -2,32 +2,31 @@ using System.Windows.Controls; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ConnectionsView { - public partial class ConnectionsView - { - private readonly ConnectionsViewModel _viewModel = new ConnectionsViewModel(DialogCoordinator.Instance); + private readonly ConnectionsViewModel _viewModel = new ConnectionsViewModel(DialogCoordinator.Instance); - public ConnectionsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public ConnectionsView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/CredentialsChangePasswordDialog.xaml.cs b/Source/NETworkManager/Views/CredentialsChangePasswordDialog.xaml.cs index cb10126853..dd7b12140a 100644 --- a/Source/NETworkManager/Views/CredentialsChangePasswordDialog.xaml.cs +++ b/Source/NETworkManager/Views/CredentialsChangePasswordDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class CredentialsChangePasswordDialog { - public partial class CredentialsChangePasswordDialog + public CredentialsChangePasswordDialog() { - public CredentialsChangePasswordDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - PasswordBoxPassword.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + PasswordBoxPassword.Focus(); } } diff --git a/Source/NETworkManager/Views/CredentialsPasswordDialog.xaml.cs b/Source/NETworkManager/Views/CredentialsPasswordDialog.xaml.cs index b1a371b2e4..b15d348123 100644 --- a/Source/NETworkManager/Views/CredentialsPasswordDialog.xaml.cs +++ b/Source/NETworkManager/Views/CredentialsPasswordDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class CredentialsPasswordDialog { - public partial class CredentialsPasswordDialog + public CredentialsPasswordDialog() { - public CredentialsPasswordDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - PasswordBoxPassword.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + PasswordBoxPassword.Focus(); } } diff --git a/Source/NETworkManager/Views/CredentialsPasswordProfileFileDialog.xaml.cs b/Source/NETworkManager/Views/CredentialsPasswordProfileFileDialog.xaml.cs index ff9d72b9dd..329531f5dc 100644 --- a/Source/NETworkManager/Views/CredentialsPasswordProfileFileDialog.xaml.cs +++ b/Source/NETworkManager/Views/CredentialsPasswordProfileFileDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class CredentialsPasswordProfileFileDialog { - public partial class CredentialsPasswordProfileFileDialog + public CredentialsPasswordProfileFileDialog() { - public CredentialsPasswordProfileFileDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - PasswordBoxPassword.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + PasswordBoxPassword.Focus(); } } diff --git a/Source/NETworkManager/Views/CredentialsSetPasswordDialog.xaml.cs b/Source/NETworkManager/Views/CredentialsSetPasswordDialog.xaml.cs index 197601dfef..1685511116 100644 --- a/Source/NETworkManager/Views/CredentialsSetPasswordDialog.xaml.cs +++ b/Source/NETworkManager/Views/CredentialsSetPasswordDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class CredentialsSetPasswordDialog { - public partial class CredentialsSetPasswordDialog + public CredentialsSetPasswordDialog() { - public CredentialsSetPasswordDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - PasswordBoxPassword.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + PasswordBoxPassword.Focus(); } } diff --git a/Source/NETworkManager/Views/CustomCommandDialog.xaml.cs b/Source/NETworkManager/Views/CustomCommandDialog.xaml.cs index eb1609fa3d..0e95f5653f 100644 --- a/Source/NETworkManager/Views/CustomCommandDialog.xaml.cs +++ b/Source/NETworkManager/Views/CustomCommandDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class CustomCommandDialog { - public partial class CustomCommandDialog + public CustomCommandDialog() { - public CustomCommandDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxName.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxName.Focus(); } } diff --git a/Source/NETworkManager/Views/DNSLookupHostView.xaml.cs b/Source/NETworkManager/Views/DNSLookupHostView.xaml.cs index 72b42b35f1..e773e2637c 100644 --- a/Source/NETworkManager/Views/DNSLookupHostView.xaml.cs +++ b/Source/NETworkManager/Views/DNSLookupHostView.xaml.cs @@ -4,45 +4,44 @@ using NETworkManager.Models; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class DNSLookupHostView { - public partial class DNSLookupHostView + private readonly DNSLookupHostViewModel _viewModel = new DNSLookupHostViewModel(DialogCoordinator.Instance); + + public DNSLookupHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.DNSLookup.ToString(); + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.LookupProfileCommand.Execute(null); + } + + public void AddTab(string host) + { + _viewModel.AddTab(host); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible() { - private readonly DNSLookupHostViewModel _viewModel = new DNSLookupHostViewModel(DialogCoordinator.Instance); - - public DNSLookupHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.DNSLookup.ToString(); - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.LookupProfileCommand.Execute(null); - } - - public void AddTab(string host) - { - _viewModel.AddTab(host); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/DNSLookupSettingsView.xaml.cs b/Source/NETworkManager/Views/DNSLookupSettingsView.xaml.cs index 6917e711de..7d4c1eb57a 100644 --- a/Source/NETworkManager/Views/DNSLookupSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/DNSLookupSettingsView.xaml.cs @@ -4,27 +4,26 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class DNSLookupSettingsView { - public partial class DNSLookupSettingsView - { - private readonly DNSLookupSettingsViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly DNSLookupSettingsViewModel _viewModel = new(DialogCoordinator.Instance); - public DNSLookupSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public DNSLookupSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) - { - _viewModel.EditDNSServer(); - } + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + _viewModel.EditDNSServer(); } } diff --git a/Source/NETworkManager/Views/DNSLookupView.xaml.cs b/Source/NETworkManager/Views/DNSLookupView.xaml.cs index 29e1d92e51..8b0ceb5120 100644 --- a/Source/NETworkManager/Views/DNSLookupView.xaml.cs +++ b/Source/NETworkManager/Views/DNSLookupView.xaml.cs @@ -4,41 +4,40 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class DNSLookupView { - public partial class DNSLookupView + private readonly DNSLookupViewModel _viewModel; + + public DNSLookupView(int tabId, string host = null) + { + InitializeComponent(); + + _viewModel = new DNSLookupViewModel(DialogCoordinator.Instance, tabId, host); + + DataContext = _viewModel; + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _viewModel.OnLoaded(); + } + + public void CloseTab() + { + _viewModel.OnClose(); + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ColumnHeader_Click(object sender, RoutedEventArgs e) { - private readonly DNSLookupViewModel _viewModel; - - public DNSLookupView(int tabId, string host = null) - { - InitializeComponent(); - - _viewModel = new DNSLookupViewModel(DialogCoordinator.Instance, tabId, host); - - DataContext = _viewModel; - } - - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _viewModel.OnLoaded(); - } - - public void CloseTab() - { - _viewModel.OnClose(); - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ColumnHeader_Click(object sender, RoutedEventArgs e) - { - if (sender is DataGridColumnHeader columnHeader) - _viewModel.SortResultByPropertyName(columnHeader.Column.SortMemberPath); - } + if (sender is DataGridColumnHeader columnHeader) + _viewModel.SortResultByPropertyName(columnHeader.Column.SortMemberPath); } } diff --git a/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs b/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs index 2bb043fed7..5af614c57b 100644 --- a/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/DashboardSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class DashboardSettingsView { - public partial class DashboardSettingsView - { - private readonly DashboardSettingsViewModel _viewModel = new DashboardSettingsViewModel(); + private readonly DashboardSettingsViewModel _viewModel = new DashboardSettingsViewModel(); - public DashboardSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public DashboardSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/DashboardView.xaml.cs b/Source/NETworkManager/Views/DashboardView.xaml.cs index 2b79751b3f..48079f5ddb 100644 --- a/Source/NETworkManager/Views/DashboardView.xaml.cs +++ b/Source/NETworkManager/Views/DashboardView.xaml.cs @@ -1,30 +1,29 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class DashboardView { - public partial class DashboardView - { - private readonly DashboardViewModel _viewModel = new(); + private readonly DashboardViewModel _viewModel = new(); - private NetworkConnectionView _networkConnectiondView; + private NetworkConnectionView _networkConnectiondView; - public DashboardView() - { - InitializeComponent(); - DataContext = _viewModel; + public DashboardView() + { + InitializeComponent(); + DataContext = _viewModel; - _networkConnectiondView = new NetworkConnectionView(); - ContentControlNetworkConnection.Content = _networkConnectiondView; - } + _networkConnectiondView = new NetworkConnectionView(); + ContentControlNetworkConnection.Content = _networkConnectiondView; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/DiscoveryProtocolView.xaml.cs b/Source/NETworkManager/Views/DiscoveryProtocolView.xaml.cs index 4b388d7cbe..3c1e3463eb 100644 --- a/Source/NETworkManager/Views/DiscoveryProtocolView.xaml.cs +++ b/Source/NETworkManager/Views/DiscoveryProtocolView.xaml.cs @@ -3,32 +3,31 @@ using System.Windows; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class DiscoveryProtocolView { - public partial class DiscoveryProtocolView - { - private readonly DiscoveryProtocolViewModel _viewModel = new DiscoveryProtocolViewModel(DialogCoordinator.Instance); + private readonly DiscoveryProtocolViewModel _viewModel = new DiscoveryProtocolViewModel(DialogCoordinator.Instance); - public DiscoveryProtocolView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public DiscoveryProtocolView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/DropdownDialog.xaml.cs b/Source/NETworkManager/Views/DropdownDialog.xaml.cs index e5584b5248..f915c42b0a 100644 --- a/Source/NETworkManager/Views/DropdownDialog.xaml.cs +++ b/Source/NETworkManager/Views/DropdownDialog.xaml.cs @@ -1,15 +1,14 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class DropdownDialog { - public partial class DropdownDialog + public DropdownDialog() { - public DropdownDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { - } } } diff --git a/Source/NETworkManager/Views/ExportDialog.xaml.cs b/Source/NETworkManager/Views/ExportDialog.xaml.cs index 237251a4cf..bef0548b9b 100644 --- a/Source/NETworkManager/Views/ExportDialog.xaml.cs +++ b/Source/NETworkManager/Views/ExportDialog.xaml.cs @@ -1,10 +1,9 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ExportDialog { - public partial class ExportDialog + public ExportDialog() { - public ExportDialog() - { - InitializeComponent(); - } + InitializeComponent(); } } diff --git a/Source/NETworkManager/Views/FirstRunDialog.xaml.cs b/Source/NETworkManager/Views/FirstRunDialog.xaml.cs index 5a29b73e6a..64059039cb 100644 --- a/Source/NETworkManager/Views/FirstRunDialog.xaml.cs +++ b/Source/NETworkManager/Views/FirstRunDialog.xaml.cs @@ -1,10 +1,9 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class FirstRunDialog { - public partial class FirstRunDialog + public FirstRunDialog() { - public FirstRunDialog() - { - InitializeComponent(); - } + InitializeComponent(); } } diff --git a/Source/NETworkManager/Views/GroupDialog.xaml.cs b/Source/NETworkManager/Views/GroupDialog.xaml.cs index e574e082e6..1edc7a38ba 100644 --- a/Source/NETworkManager/Views/GroupDialog.xaml.cs +++ b/Source/NETworkManager/Views/GroupDialog.xaml.cs @@ -1,41 +1,40 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class GroupDialog { - public partial class GroupDialog + public GroupDialog() { - public GroupDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxName.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxName.Focus(); + } - // Set name as hostname (if empty or identical) - private string _oldName = string.Empty; + // Set name as hostname (if empty or identical) + private string _oldName = string.Empty; - + - private void TextBoxName_OnGotFocus(object sender, System.Windows.RoutedEventArgs e) - { - //_oldName = TextBoxName.Text; - } + private void TextBoxName_OnGotFocus(object sender, System.Windows.RoutedEventArgs e) + { + //_oldName = TextBoxName.Text; + } - private void TextBoxName_OnTextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) - { - /* - if (_oldName == TextBoxHost.Text) - TextBoxHost.Text = TextBoxName.Text; + private void TextBoxName_OnTextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) + { + /* + if (_oldName == TextBoxHost.Text) + TextBoxHost.Text = TextBoxName.Text; - _oldName = TextBoxName.Text; - */ - } - - private void ScrollViewer_ManipulationBoundaryFeedback(object sender, System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e) - { - e.Handled = true; - } + _oldName = TextBoxName.Text; + */ + } + + private void ScrollViewer_ManipulationBoundaryFeedback(object sender, System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e) + { + e.Handled = true; } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/IPAddressAndSubnetmaskDialog.xaml.cs b/Source/NETworkManager/Views/IPAddressAndSubnetmaskDialog.xaml.cs index 1df72c4425..3ff3025891 100644 --- a/Source/NETworkManager/Views/IPAddressAndSubnetmaskDialog.xaml.cs +++ b/Source/NETworkManager/Views/IPAddressAndSubnetmaskDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class IPAddressAndSubnetmaskDialog { - public partial class IPAddressAndSubnetmaskDialog + public IPAddressAndSubnetmaskDialog() { - public IPAddressAndSubnetmaskDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxIPAddress.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxIPAddress.Focus(); } } diff --git a/Source/NETworkManager/Views/IPAddressDialog.xaml.cs b/Source/NETworkManager/Views/IPAddressDialog.xaml.cs index 29b5a7b184..cb879d33b8 100644 --- a/Source/NETworkManager/Views/IPAddressDialog.xaml.cs +++ b/Source/NETworkManager/Views/IPAddressDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class IPAddressDialog { - public partial class IPAddressDialog + public IPAddressDialog() { - public IPAddressDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxIPAddress.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxIPAddress.Focus(); } } diff --git a/Source/NETworkManager/Views/IPScannerHostView.xaml.cs b/Source/NETworkManager/Views/IPScannerHostView.xaml.cs index 7cd18ccf33..93adb12c81 100644 --- a/Source/NETworkManager/Views/IPScannerHostView.xaml.cs +++ b/Source/NETworkManager/Views/IPScannerHostView.xaml.cs @@ -6,50 +6,49 @@ using NETworkManager.Profiles; using NETworkManager.Models; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class IPScannerHostView { - public partial class IPScannerHostView + private readonly IPScannerHostViewModel _viewModel = new IPScannerHostViewModel(DialogCoordinator.Instance); + + public IPScannerHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.IPScanner.ToString(); + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ScanProfileCommand.Execute(null); + } + + public void AddTab(string host) + { + _viewModel.AddTab(host); + } + + public void AddTab(ProfileInfo profile) + { + _viewModel.AddTab(profile); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible() { - private readonly IPScannerHostViewModel _viewModel = new IPScannerHostViewModel(DialogCoordinator.Instance); - - public IPScannerHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.IPScanner.ToString(); - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ScanProfileCommand.Execute(null); - } - - public void AddTab(string host) - { - _viewModel.AddTab(host); - } - - public void AddTab(ProfileInfo profile) - { - _viewModel.AddTab(profile); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/IPScannerSettingsView.xaml.cs b/Source/NETworkManager/Views/IPScannerSettingsView.xaml.cs index d2d367132c..14073717b5 100644 --- a/Source/NETworkManager/Views/IPScannerSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/IPScannerSettingsView.xaml.cs @@ -4,25 +4,24 @@ using System.Windows.Controls; using System.Windows.Input; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class IPScannerSettingsView { - public partial class IPScannerSettingsView - { - private readonly IPScannerSettingsViewModel _viewModel = new IPScannerSettingsViewModel(DialogCoordinator.Instance); + private readonly IPScannerSettingsViewModel _viewModel = new IPScannerSettingsViewModel(DialogCoordinator.Instance); - public IPScannerSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } - private void RowContextMenu_OnOpened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) menu.DataContext = _viewModel; - } + public IPScannerSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } + private void RowContextMenu_OnOpened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) menu.DataContext = _viewModel; + } - private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) - { - _viewModel.EditCustomCommand(); - } + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + _viewModel.EditCustomCommand(); } } diff --git a/Source/NETworkManager/Views/IPScannerView.xaml.cs b/Source/NETworkManager/Views/IPScannerView.xaml.cs index d988623b4a..6f53006cb8 100644 --- a/Source/NETworkManager/Views/IPScannerView.xaml.cs +++ b/Source/NETworkManager/Views/IPScannerView.xaml.cs @@ -4,76 +4,75 @@ using System.Windows.Controls; using NETworkManager.Utilities; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class IPScannerView { - public partial class IPScannerView - { - private readonly IPScannerViewModel _viewModel; + private readonly IPScannerViewModel _viewModel; - public IPScannerView(int tabId, string hostOrIPRange = null) - { - InitializeComponent(); + public IPScannerView(int tabId, string hostOrIPRange = null) + { + InitializeComponent(); - _viewModel = new IPScannerViewModel(DialogCoordinator.Instance, tabId, hostOrIPRange); + _viewModel = new IPScannerViewModel(DialogCoordinator.Instance, tabId, hostOrIPRange); - DataContext = _viewModel; + DataContext = _viewModel; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _viewModel.OnLoaded(); - } + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _viewModel.OnLoaded(); + } - private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) - { - _viewModel.OnClose(); - } + private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) + { + _viewModel.OnClose(); + } - public void CloseTab() - { - _viewModel.OnClose(); - } + public void CloseTab() + { + _viewModel.OnClose(); + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) { - if (sender is ContextMenu menu) - { - // Set DataContext to ViewModel - menu.DataContext = _viewModel; + // Set DataContext to ViewModel + menu.DataContext = _viewModel; - // Append custom commands - int index = menu.Items.Count - 1; + // Append custom commands + int index = menu.Items.Count - 1; - bool entryFound = false; + bool entryFound = false; - for (int i = 0; i < menu.Items.Count; i++) + for (int i = 0; i < menu.Items.Count; i++) + { + if (menu.Items[i] is MenuItem item) { - if (menu.Items[i] is MenuItem item) - { - if ((string)item.Tag != "CustomCommands") - continue; + if ((string)item.Tag != "CustomCommands") + continue; - index = i; + index = i; - entryFound = true; + entryFound = true; - break; - } + break; } + } - if (!entryFound) - return; + if (!entryFound) + return; - // Clear existing items in custom commands - ((MenuItem)menu.Items[index]).Items.Clear(); + // Clear existing items in custom commands + ((MenuItem)menu.Items[index]).Items.Clear(); - // Add items to custom commands - foreach (CustomCommandInfo info in _viewModel.CustomCommands) - { - ((MenuItem)menu.Items[index]).Items.Add(new MenuItem { Header = info.Name, Command = _viewModel.CustomCommandCommand, CommandParameter = info.ID }); - } + // Add items to custom commands + foreach (CustomCommandInfo info in _viewModel.CustomCommands) + { + ((MenuItem)menu.Items[index]).Items.Add(new MenuItem { Header = info.Name, Command = _viewModel.CustomCommandCommand, CommandParameter = info.ID }); } } } diff --git a/Source/NETworkManager/Views/ListenersView.xaml.cs b/Source/NETworkManager/Views/ListenersView.xaml.cs index 779a833209..7d5b077071 100644 --- a/Source/NETworkManager/Views/ListenersView.xaml.cs +++ b/Source/NETworkManager/Views/ListenersView.xaml.cs @@ -2,32 +2,31 @@ using System.Windows.Controls; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ListenersView { - public partial class ListenersView - { - private readonly ListenersViewModel _viewModel = new ListenersViewModel(DialogCoordinator.Instance); + private readonly ListenersViewModel _viewModel = new ListenersViewModel(DialogCoordinator.Instance); - public ListenersView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public ListenersView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/LookupHostView.xaml.cs b/Source/NETworkManager/Views/LookupHostView.xaml.cs index b8078466fd..712c1c90bd 100644 --- a/Source/NETworkManager/Views/LookupHostView.xaml.cs +++ b/Source/NETworkManager/Views/LookupHostView.xaml.cs @@ -1,25 +1,24 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class LookupHostView { - public partial class LookupHostView - { - private readonly LookupHostViewModel _viewModel = new(); + private readonly LookupHostViewModel _viewModel = new(); - public LookupHostView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public LookupHostView() + { + InitializeComponent(); + DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/LookupOUILookupView.xaml.cs b/Source/NETworkManager/Views/LookupOUILookupView.xaml.cs index 0db2070441..78eaa12731 100644 --- a/Source/NETworkManager/Views/LookupOUILookupView.xaml.cs +++ b/Source/NETworkManager/Views/LookupOUILookupView.xaml.cs @@ -2,22 +2,21 @@ using System.Windows.Controls; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class LookupOUILookupView { - public partial class LookupOUILookupView - { - private readonly LookupOUILookupViewModel _viewModel = new LookupOUILookupViewModel(DialogCoordinator.Instance); + private readonly LookupOUILookupViewModel _viewModel = new LookupOUILookupViewModel(DialogCoordinator.Instance); - public LookupOUILookupView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public LookupOUILookupView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/LookupPortLookupView.xaml.cs b/Source/NETworkManager/Views/LookupPortLookupView.xaml.cs index 0964b2d179..8ec9ad2983 100644 --- a/Source/NETworkManager/Views/LookupPortLookupView.xaml.cs +++ b/Source/NETworkManager/Views/LookupPortLookupView.xaml.cs @@ -2,22 +2,21 @@ using System.Windows.Controls; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class LookupPortLookupView { - public partial class LookupPortLookupView - { - private readonly LookupPortLookupViewModel _viewModel = new LookupPortLookupViewModel(DialogCoordinator.Instance); + private readonly LookupPortLookupViewModel _viewModel = new LookupPortLookupViewModel(DialogCoordinator.Instance); - public LookupPortLookupView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public LookupPortLookupView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/NetworkConnectionView.xaml.cs b/Source/NETworkManager/Views/NetworkConnectionView.xaml.cs index e6631a6dc5..5c215ef72e 100644 --- a/Source/NETworkManager/Views/NetworkConnectionView.xaml.cs +++ b/Source/NETworkManager/Views/NetworkConnectionView.xaml.cs @@ -2,32 +2,31 @@ using System.Windows.Controls; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class NetworkConnectionView { - public partial class NetworkConnectionView - { - private readonly NetworkConnectionViewModel _viewModel = new(); + private readonly NetworkConnectionViewModel _viewModel = new(); - public NetworkConnectionView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public NetworkConnectionView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void Reload() - { - _viewModel.CheckConnection(); - } + public void Reload() + { + _viewModel.CheckConnection(); + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _viewModel.CheckConnection(); - } + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _viewModel.CheckConnection(); } } diff --git a/Source/NETworkManager/Views/NetworkInterfaceView.xaml.cs b/Source/NETworkManager/Views/NetworkInterfaceView.xaml.cs index 80a4e92723..de216edf97 100644 --- a/Source/NETworkManager/Views/NetworkInterfaceView.xaml.cs +++ b/Source/NETworkManager/Views/NetworkInterfaceView.xaml.cs @@ -3,32 +3,31 @@ using System.Windows; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class NetworkInterfaceView { - public partial class NetworkInterfaceView - { - private readonly NetworkInterfaceViewModel _viewModel = new NetworkInterfaceViewModel(DialogCoordinator.Instance); + private readonly NetworkInterfaceViewModel _viewModel = new NetworkInterfaceViewModel(DialogCoordinator.Instance); - public NetworkInterfaceView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public NetworkInterfaceView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs b/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs index 030ee58836..4d393a6ae6 100644 --- a/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs +++ b/Source/NETworkManager/Views/PingMonitorHostView.xaml.cs @@ -3,43 +3,42 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views -{ - public partial class PingMonitorHostView - { - private readonly PingMonitorHostViewModel _viewModel = new(DialogCoordinator.Instance); +namespace NETworkManager.Views; - public PingMonitorHostView() - { - InitializeComponent(); - DataContext = _viewModel; - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } +public partial class PingMonitorHostView +{ + private readonly PingMonitorHostViewModel _viewModel = new(DialogCoordinator.Instance); - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.AddHostProfileCommand.Execute(null); - } + public PingMonitorHostView() + { + InitializeComponent(); + DataContext = _viewModel; + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void AddHost(string host) - { - _viewModel.AddHost(host); - } + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.AddHostProfileCommand.Execute(null); + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void AddHost(string host) + { + _viewModel.AddHost(host); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); } + + public void OnViewVisible() + { + _viewModel.OnViewVisible(); + } } diff --git a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs index 2ef63d9537..49296c92ab 100644 --- a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PingMonitorSettingsView { - public partial class PingMonitorSettingsView - { - private readonly PingMonitorSettingsViewModel _viewModel = new PingMonitorSettingsViewModel(); + private readonly PingMonitorSettingsViewModel _viewModel = new PingMonitorSettingsViewModel(); - public PingMonitorSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public PingMonitorSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/PingMonitorView.xaml.cs b/Source/NETworkManager/Views/PingMonitorView.xaml.cs index 553a1dc054..7ce51b52f8 100644 --- a/Source/NETworkManager/Views/PingMonitorView.xaml.cs +++ b/Source/NETworkManager/Views/PingMonitorView.xaml.cs @@ -3,43 +3,42 @@ using NETworkManager.Models.Network; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PingMonitorView { - public partial class PingMonitorView - { - private readonly PingMonitorViewModel _viewModel; + private readonly PingMonitorViewModel _viewModel; - public Guid HostId => _viewModel.HostId; + public Guid HostId => _viewModel.HostId; - public PingMonitorView(Guid hostId, Action closeCallback, PingMonitorOptions options) - { - InitializeComponent(); + public PingMonitorView(Guid hostId, Action closeCallback, PingMonitorOptions options) + { + InitializeComponent(); - _viewModel = new PingMonitorViewModel(DialogCoordinator.Instance, hostId, closeCallback, options); + _viewModel = new PingMonitorViewModel(DialogCoordinator.Instance, hostId, closeCallback, options); - DataContext = _viewModel; + DataContext = _viewModel; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - _viewModel.OnLoaded(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + _viewModel.OnLoaded(); + } - public void Export() - { - _viewModel.Export(); - } + public void Export() + { + _viewModel.Export(); + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) - { - _viewModel.OnClose(); - } + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + _viewModel.OnClose(); + } - public void CloseView() - { - _viewModel.OnClose(); - } + public void CloseView() + { + _viewModel.OnClose(); } } diff --git a/Source/NETworkManager/Views/PortProfileDialog.xaml.cs b/Source/NETworkManager/Views/PortProfileDialog.xaml.cs index d7db579d0a..4843896d35 100644 --- a/Source/NETworkManager/Views/PortProfileDialog.xaml.cs +++ b/Source/NETworkManager/Views/PortProfileDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PortProfileDialog { - public partial class PortProfileDialog + public PortProfileDialog() { - public PortProfileDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxName.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxName.Focus(); } } diff --git a/Source/NETworkManager/Views/PortProfilesDialog.xaml.cs b/Source/NETworkManager/Views/PortProfilesDialog.xaml.cs index dbfb36b554..b7c45bf654 100644 --- a/Source/NETworkManager/Views/PortProfilesDialog.xaml.cs +++ b/Source/NETworkManager/Views/PortProfilesDialog.xaml.cs @@ -1,26 +1,25 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PortProfilesDialog { - public partial class PortProfilesDialog + public PortProfilesDialog() { - public PortProfilesDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxSearch.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxSearch.Focus(); + } - private void DataGridRow_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - var x = (PortProfilesViewModel)DataContext; + private void DataGridRow_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + var x = (PortProfilesViewModel)DataContext; - if (x.OKCommand.CanExecute(null)) - x.OKCommand.Execute(null); - } + if (x.OKCommand.CanExecute(null)) + x.OKCommand.Execute(null); } } diff --git a/Source/NETworkManager/Views/PortScannerHostView.xaml.cs b/Source/NETworkManager/Views/PortScannerHostView.xaml.cs index 2d7666b2eb..c4ebd8880f 100644 --- a/Source/NETworkManager/Views/PortScannerHostView.xaml.cs +++ b/Source/NETworkManager/Views/PortScannerHostView.xaml.cs @@ -6,50 +6,49 @@ using NETworkManager.Profiles; using NETworkManager.Models; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PortScannerHostView { - public partial class PortScannerHostView + private readonly PortScannerHostViewModel _viewModel = new PortScannerHostViewModel(DialogCoordinator.Instance); + + public PortScannerHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.PortScanner.ToString(); + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ScanProfileCommand.Execute(null); + } + + public void AddTab(string host) + { + _viewModel.AddTab(host); + } + + public void AddTab(ProfileInfo profile) + { + _viewModel.AddTab(profile); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible() { - private readonly PortScannerHostViewModel _viewModel = new PortScannerHostViewModel(DialogCoordinator.Instance); - - public PortScannerHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.PortScanner.ToString(); - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ScanProfileCommand.Execute(null); - } - - public void AddTab(string host) - { - _viewModel.AddTab(host); - } - - public void AddTab(ProfileInfo profile) - { - _viewModel.AddTab(profile); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/PortScannerSettingsView.xaml.cs b/Source/NETworkManager/Views/PortScannerSettingsView.xaml.cs index 31c2f10574..d65e842d2c 100644 --- a/Source/NETworkManager/Views/PortScannerSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/PortScannerSettingsView.xaml.cs @@ -4,26 +4,25 @@ using System.Windows.Controls; using System.Windows.Input; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PortScannerSettingsView { - public partial class PortScannerSettingsView - { - private readonly PortScannerSettingsViewModel _viewModel = new PortScannerSettingsViewModel(DialogCoordinator.Instance); + private readonly PortScannerSettingsViewModel _viewModel = new PortScannerSettingsViewModel(DialogCoordinator.Instance); - public PortScannerSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } - private void RowContextMenu_OnOpened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + public PortScannerSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } + private void RowContextMenu_OnOpened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) - { - _viewModel.EditPortProfile(); - } + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + _viewModel.EditPortProfile(); } } diff --git a/Source/NETworkManager/Views/PortScannerView.xaml.cs b/Source/NETworkManager/Views/PortScannerView.xaml.cs index 7bcf3f46e9..049cfa87f0 100644 --- a/Source/NETworkManager/Views/PortScannerView.xaml.cs +++ b/Source/NETworkManager/Views/PortScannerView.xaml.cs @@ -4,48 +4,47 @@ using System.Windows.Controls.Primitives; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PortScannerView { - public partial class PortScannerView - { - private readonly PortScannerViewModel _viewModel; + private readonly PortScannerViewModel _viewModel; - public PortScannerView(int tabId, string host = null, string ports = null) - { - InitializeComponent(); + public PortScannerView(int tabId, string host = null, string ports = null) + { + InitializeComponent(); - _viewModel = new PortScannerViewModel(DialogCoordinator.Instance, tabId, host, ports); + _viewModel = new PortScannerViewModel(DialogCoordinator.Instance, tabId, host, ports); - DataContext = _viewModel; + DataContext = _viewModel; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _viewModel.OnLoaded(); - } + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _viewModel.OnLoaded(); + } - private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) - { - _viewModel.OnClose(); - } + private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) + { + _viewModel.OnClose(); + } - public void CloseTab() - { - _viewModel.OnClose(); - } + public void CloseTab() + { + _viewModel.OnClose(); + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void ColumnHeader_Click(object sender, RoutedEventArgs e) - { - if (sender is DataGridColumnHeader columnHeader) - _viewModel.SortResultByPropertyName(columnHeader.Column.SortMemberPath); - } + private void ColumnHeader_Click(object sender, RoutedEventArgs e) + { + if (sender is DataGridColumnHeader columnHeader) + _viewModel.SortResultByPropertyName(columnHeader.Column.SortMemberPath); } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/PowerShellConnectDialog.xaml.cs b/Source/NETworkManager/Views/PowerShellConnectDialog.xaml.cs index a74a73a04d..cac04d44fa 100644 --- a/Source/NETworkManager/Views/PowerShellConnectDialog.xaml.cs +++ b/Source/NETworkManager/Views/PowerShellConnectDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PowerShellConnectDialog { - public partial class PowerShellConnectDialog + public PowerShellConnectDialog() { - public PowerShellConnectDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - ComboBoxHost.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + ComboBoxHost.Focus(); } } diff --git a/Source/NETworkManager/Views/PowerShellHostView.xaml.cs b/Source/NETworkManager/Views/PowerShellHostView.xaml.cs index 9324cfd142..59dc28c269 100644 --- a/Source/NETworkManager/Views/PowerShellHostView.xaml.cs +++ b/Source/NETworkManager/Views/PowerShellHostView.xaml.cs @@ -5,63 +5,62 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PowerShellHostView { - public partial class PowerShellHostView - { - private readonly PowerShellHostViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly PowerShellHostViewModel _viewModel = new(DialogCoordinator.Instance); - private bool _loaded; + private bool _loaded; - public PowerShellHostView() - { - InitializeComponent(); - DataContext = _viewModel; + public PowerShellHostView() + { + InitializeComponent(); + DataContext = _viewModel; - InterTabController.Partition = ApplicationName.PowerShell.ToString(); - } + InterTabController.Partition = ApplicationName.PowerShell.ToString(); + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _loaded = true; - } + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _loaded = true; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ConnectProfileCommand.Execute(null); - } + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ConnectProfileCommand.Execute(null); + } - public async Task AddTab(string host) - { - // Wait for the interface to load, before displaying the dialog to connect a new profile... - // MahApps will throw an exception... - while (!_loaded) - await Task.Delay(250); + public async Task AddTab(string host) + { + // Wait for the interface to load, before displaying the dialog to connect a new profile... + // MahApps will throw an exception... + while (!_loaded) + await Task.Delay(250); - if (_viewModel.IsConfigured) - _viewModel.AddTab(host); - } + if (_viewModel.IsConfigured) + _viewModel.AddTab(host); + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); + } - public void FocusEmbeddedWindow() - { - _viewModel.FocusEmbeddedWindow(); - } + public void FocusEmbeddedWindow() + { + _viewModel.FocusEmbeddedWindow(); } } diff --git a/Source/NETworkManager/Views/PowerShellSettingsView.xaml.cs b/Source/NETworkManager/Views/PowerShellSettingsView.xaml.cs index 2bd63bd594..8c8fea89a2 100644 --- a/Source/NETworkManager/Views/PowerShellSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/PowerShellSettingsView.xaml.cs @@ -2,33 +2,32 @@ using NETworkManager.ViewModels; using System.Windows; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PowerShellSettingsView { - public partial class PowerShellSettingsView - { - private readonly PowerShellSettingsViewModel _viewModel = new PowerShellSettingsViewModel(DialogCoordinator.Instance); + private readonly PowerShellSettingsViewModel _viewModel = new PowerShellSettingsViewModel(DialogCoordinator.Instance); - public PowerShellSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public PowerShellSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) - { - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) - return; + private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) + { + if (!e.Data.GetDataPresent(DataFormats.FileDrop)) + return; - var files = (string[])e.Data.GetData(DataFormats.FileDrop); + var files = (string[])e.Data.GetData(DataFormats.FileDrop); - if (files != null) - _viewModel.SetFilePathFromDragDrop(files[0]); - } + if (files != null) + _viewModel.SetFilePathFromDragDrop(files[0]); + } - private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) - { - e.Effects = DragDropEffects.Copy; - e.Handled = true; - } + private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) + { + e.Effects = DragDropEffects.Copy; + e.Handled = true; } } diff --git a/Source/NETworkManager/Views/ProfileDialog.xaml.cs b/Source/NETworkManager/Views/ProfileDialog.xaml.cs index f70565a6c6..769779f375 100644 --- a/Source/NETworkManager/Views/ProfileDialog.xaml.cs +++ b/Source/NETworkManager/Views/ProfileDialog.xaml.cs @@ -1,40 +1,39 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ProfileDialog { - public partial class ProfileDialog + public ProfileDialog() + { + InitializeComponent(); + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxName.Focus(); + } + + // Set name as hostname (if empty or identical) + private string _oldName = string.Empty; + + private void TextBoxName_OnGotFocus(object sender, RoutedEventArgs e) + { + _oldName = TextBoxName.Text; + } + + private void TextBoxName_OnTextChanged(object sender, TextChangedEventArgs e) + { + if (_oldName == TextBoxHost.Text) + TextBoxHost.Text = TextBoxName.Text; + + _oldName = TextBoxName.Text; + } + + private void ScrollViewer_ManipulationBoundaryFeedback(object sender, System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e) { - public ProfileDialog() - { - InitializeComponent(); - } - - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxName.Focus(); - } - - // Set name as hostname (if empty or identical) - private string _oldName = string.Empty; - - private void TextBoxName_OnGotFocus(object sender, RoutedEventArgs e) - { - _oldName = TextBoxName.Text; - } - - private void TextBoxName_OnTextChanged(object sender, TextChangedEventArgs e) - { - if (_oldName == TextBoxHost.Text) - TextBoxHost.Text = TextBoxName.Text; - - _oldName = TextBoxName.Text; - } - - private void ScrollViewer_ManipulationBoundaryFeedback(object sender, System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e) - { - e.Handled = true; - } + e.Handled = true; } } diff --git a/Source/NETworkManager/Views/ProfileFileDialog.xaml.cs b/Source/NETworkManager/Views/ProfileFileDialog.xaml.cs index fffc6a36ba..0601caef1f 100644 --- a/Source/NETworkManager/Views/ProfileFileDialog.xaml.cs +++ b/Source/NETworkManager/Views/ProfileFileDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ProfileFileDialog { - public partial class ProfileFileDialog + public ProfileFileDialog() { - public ProfileFileDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxName.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxName.Focus(); } } diff --git a/Source/NETworkManager/Views/ProfilesView.xaml.cs b/Source/NETworkManager/Views/ProfilesView.xaml.cs index 1e63366502..75be1e57be 100644 --- a/Source/NETworkManager/Views/ProfilesView.xaml.cs +++ b/Source/NETworkManager/Views/ProfilesView.xaml.cs @@ -4,44 +4,43 @@ using System.Windows.Controls; using System.Windows.Input; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ProfilesView { - public partial class ProfilesView - { - private readonly ProfilesViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly ProfilesViewModel _viewModel = new(DialogCoordinator.Instance); - public ProfilesView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public ProfilesView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void DataGridGroupsRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + private void DataGridGroupsRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (e.ChangedButton == MouseButton.Left) { - if (e.ChangedButton == MouseButton.Left) - { - if (_viewModel.EditGroupCommand.CanExecute(null)) - _viewModel.EditGroupCommand.Execute(null); - } + if (_viewModel.EditGroupCommand.CanExecute(null)) + _viewModel.EditGroupCommand.Execute(null); } - private void DataGridProfilesRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + } + private void DataGridProfilesRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (e.ChangedButton == MouseButton.Left) { - if (e.ChangedButton == MouseButton.Left) - { - if (_viewModel.EditProfileCommand.CanExecute(null)) - _viewModel.EditProfileCommand.Execute(null); - } + if (_viewModel.EditProfileCommand.CanExecute(null)) + _viewModel.EditProfileCommand.Execute(null); } + } - public void Refresh() - { - _viewModel.RefreshProfiles(); - } + public void Refresh() + { + _viewModel.RefreshProfiles(); } } diff --git a/Source/NETworkManager/Views/PuTTYConnectDialog.xaml.cs b/Source/NETworkManager/Views/PuTTYConnectDialog.xaml.cs index 198ed86226..a9e679eb07 100644 --- a/Source/NETworkManager/Views/PuTTYConnectDialog.xaml.cs +++ b/Source/NETworkManager/Views/PuTTYConnectDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PuTTYConnectDialog { - public partial class PuTTYConnectDialog + public PuTTYConnectDialog() { - public PuTTYConnectDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - ComboBoxHost.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + ComboBoxHost.Focus(); } } diff --git a/Source/NETworkManager/Views/PuTTYHostView.xaml.cs b/Source/NETworkManager/Views/PuTTYHostView.xaml.cs index 6552cbbe5e..6f3a0de2d5 100644 --- a/Source/NETworkManager/Views/PuTTYHostView.xaml.cs +++ b/Source/NETworkManager/Views/PuTTYHostView.xaml.cs @@ -5,63 +5,62 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PuTTYHostView { - public partial class PuTTYHostView - { - private readonly PuTTYHostViewModel _viewModel = new PuTTYHostViewModel(DialogCoordinator.Instance); + private readonly PuTTYHostViewModel _viewModel = new PuTTYHostViewModel(DialogCoordinator.Instance); - private bool _loaded; - - public PuTTYHostView() - { - InitializeComponent(); - DataContext = _viewModel; + private bool _loaded; + + public PuTTYHostView() + { + InitializeComponent(); + DataContext = _viewModel; - InterTabController.Partition = ApplicationName.PuTTY.ToString(); - } + InterTabController.Partition = ApplicationName.PuTTY.ToString(); + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _loaded = true; - } + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _loaded = true; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ConnectProfileCommand.Execute(null); - } + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ConnectProfileCommand.Execute(null); + } - public async Task AddTab(string host) - { - // Wait for the interface to load, before displaying the dialog to connect a new profile... - // MahApps will throw an exception... - while (!_loaded) - await Task.Delay(250); + public async Task AddTab(string host) + { + // Wait for the interface to load, before displaying the dialog to connect a new profile... + // MahApps will throw an exception... + while (!_loaded) + await Task.Delay(250); - if (_viewModel.IsConfigured) - _viewModel.AddTab(host); - } + if (_viewModel.IsConfigured) + _viewModel.AddTab(host); + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); + } - public void FocusEmbeddedWindow() - { - _viewModel.FocusEmbeddedWindow(); - } + public void FocusEmbeddedWindow() + { + _viewModel.FocusEmbeddedWindow(); } } diff --git a/Source/NETworkManager/Views/PuTTYSettingsView.xaml.cs b/Source/NETworkManager/Views/PuTTYSettingsView.xaml.cs index 23b4561ba2..a4cef0377e 100644 --- a/Source/NETworkManager/Views/PuTTYSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/PuTTYSettingsView.xaml.cs @@ -2,103 +2,102 @@ using NETworkManager.ViewModels; using System.Windows; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class PuTTYSettingsView { - public partial class PuTTYSettingsView - { - /// - /// Variable to hold an instance of the view model. - /// - private readonly PuTTYSettingsViewModel _viewModel = new PuTTYSettingsViewModel(DialogCoordinator.Instance); + /// + /// Variable to hold an instance of the view model. + /// + private readonly PuTTYSettingsViewModel _viewModel = new PuTTYSettingsViewModel(DialogCoordinator.Instance); - /// - /// Create a new instance of . - /// - public PuTTYSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + /// + /// Create a new instance of . + /// + public PuTTYSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } - /// - /// Set the file from drag and drop. - /// - /// - /// - private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) - { - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) - return; + /// + /// Set the file from drag and drop. + /// + /// + /// + private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) + { + if (!e.Data.GetDataPresent(DataFormats.FileDrop)) + return; - var files = (string[])e.Data.GetData(DataFormats.FileDrop); + var files = (string[])e.Data.GetData(DataFormats.FileDrop); - if (files != null) - _viewModel.SetApplicationFilePathFromDragDrop(files[0]); - } + if (files != null) + _viewModel.SetApplicationFilePathFromDragDrop(files[0]); + } - /// - /// Method to override the drag over effect. - /// - /// - /// - private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) - { - e.Effects = DragDropEffects.Copy; - e.Handled = true; - } + /// + /// Method to override the drag over effect. + /// + /// + /// + private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) + { + e.Effects = DragDropEffects.Copy; + e.Handled = true; + } - /// - /// Set the file from drag and drop. - /// - /// - /// - private void TextBoxPrivateKeyFilePath_Drop(object sender, DragEventArgs e) - { - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) - return; + /// + /// Set the file from drag and drop. + /// + /// + /// + private void TextBoxPrivateKeyFilePath_Drop(object sender, DragEventArgs e) + { + if (!e.Data.GetDataPresent(DataFormats.FileDrop)) + return; - var files = (string[])e.Data.GetData(DataFormats.FileDrop); + var files = (string[])e.Data.GetData(DataFormats.FileDrop); - if (files != null) - _viewModel.SetPrivateKeyFilePathFromDragDrop(files[0]); - } + if (files != null) + _viewModel.SetPrivateKeyFilePathFromDragDrop(files[0]); + } - /// - /// Method to override the drag over effect. - /// - /// - /// - private void TextBoxPrivateKeyFilePath_PreviewDragOver(object sender, DragEventArgs e) - { - e.Effects = DragDropEffects.Copy; - e.Handled = true; - } + /// + /// Method to override the drag over effect. + /// + /// + /// + private void TextBoxPrivateKeyFilePath_PreviewDragOver(object sender, DragEventArgs e) + { + e.Effects = DragDropEffects.Copy; + e.Handled = true; + } - /// - /// Set the folder from drag and drop. - /// - /// - /// - private void TextBoxLogPathFolderPath_Drop(object sender, DragEventArgs e) - { - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) - return; + /// + /// Set the folder from drag and drop. + /// + /// + /// + private void TextBoxLogPathFolderPath_Drop(object sender, DragEventArgs e) + { + if (!e.Data.GetDataPresent(DataFormats.FileDrop)) + return; - var folder = (string[])e.Data.GetData(DataFormats.FileDrop); + var folder = (string[])e.Data.GetData(DataFormats.FileDrop); - if (folder != null) - _viewModel.SetLogPathFolderPathFromDragDrop(folder[0]); - } + if (folder != null) + _viewModel.SetLogPathFolderPathFromDragDrop(folder[0]); + } - /// - /// Method to override the drag over effect. - /// - /// - /// - private void TextBoxLogPathFolderPath_PreviewDragOver(object sender, DragEventArgs e) - { - e.Effects = DragDropEffects.Copy; - e.Handled = true; - } + /// + /// Method to override the drag over effect. + /// + /// + /// + private void TextBoxLogPathFolderPath_PreviewDragOver(object sender, DragEventArgs e) + { + e.Effects = DragDropEffects.Copy; + e.Handled = true; } } diff --git a/Source/NETworkManager/Views/RemoteDesktopConnectDialog.xaml.cs b/Source/NETworkManager/Views/RemoteDesktopConnectDialog.xaml.cs index 8a2544294a..dceec3aa1d 100644 --- a/Source/NETworkManager/Views/RemoteDesktopConnectDialog.xaml.cs +++ b/Source/NETworkManager/Views/RemoteDesktopConnectDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class RemoteDesktopConnectDialog { - public partial class RemoteDesktopConnectDialog + public RemoteDesktopConnectDialog() { - public RemoteDesktopConnectDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - ComboBoxHost.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + ComboBoxHost.Focus(); } } diff --git a/Source/NETworkManager/Views/RemoteDesktopHostView.xaml.cs b/Source/NETworkManager/Views/RemoteDesktopHostView.xaml.cs index 10a6ab8bb4..659f5b41f4 100644 --- a/Source/NETworkManager/Views/RemoteDesktopHostView.xaml.cs +++ b/Source/NETworkManager/Views/RemoteDesktopHostView.xaml.cs @@ -5,56 +5,55 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class RemoteDesktopHostView { - public partial class RemoteDesktopHostView + private readonly RemoteDesktopHostViewModel _viewModel = new RemoteDesktopHostViewModel(DialogCoordinator.Instance); + + private bool _loaded; + + public RemoteDesktopHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.RemoteDesktop.ToString(); + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _loaded = true; + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ConnectProfileCommand.Execute(null); + } + + public async Task AddTab(string host) + { + // Wait for the interface to load, before displaying the dialog to connect a new Profile... + // MahApps will throw an exception... + while (!_loaded) + await Task.Delay(250); + + _viewModel.AddTab(host); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible() { - private readonly RemoteDesktopHostViewModel _viewModel = new RemoteDesktopHostViewModel(DialogCoordinator.Instance); - - private bool _loaded; - - public RemoteDesktopHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.RemoteDesktop.ToString(); - } - - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _loaded = true; - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ConnectProfileCommand.Execute(null); - } - - public async Task AddTab(string host) - { - // Wait for the interface to load, before displaying the dialog to connect a new Profile... - // MahApps will throw an exception... - while (!_loaded) - await Task.Delay(250); - - _viewModel.AddTab(host); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/RemoteDesktopSettingsView.xaml.cs b/Source/NETworkManager/Views/RemoteDesktopSettingsView.xaml.cs index dad7506474..102e3aebac 100644 --- a/Source/NETworkManager/Views/RemoteDesktopSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/RemoteDesktopSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class RemoteDesktopSettingsView { - public partial class RemoteDesktopSettingsView - { - private readonly RemoteDesktopSettingsViewModel _viewModel = new RemoteDesktopSettingsViewModel(); + private readonly RemoteDesktopSettingsViewModel _viewModel = new RemoteDesktopSettingsViewModel(); - public RemoteDesktopSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public RemoteDesktopSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SNMPHostView.xaml.cs b/Source/NETworkManager/Views/SNMPHostView.xaml.cs index f79020cfd2..b8704d9a3c 100644 --- a/Source/NETworkManager/Views/SNMPHostView.xaml.cs +++ b/Source/NETworkManager/Views/SNMPHostView.xaml.cs @@ -1,33 +1,32 @@ using NETworkManager.Models; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SNMPHostView { - public partial class SNMPHostView - { - private readonly SNMPHostViewModel _viewModel = new(); + private readonly SNMPHostViewModel _viewModel = new(); - public SNMPHostView() - { - InitializeComponent(); - DataContext = _viewModel; + public SNMPHostView() + { + InitializeComponent(); + DataContext = _viewModel; - InterTabController.Partition = ApplicationName.SNMP.ToString(); - } + InterTabController.Partition = ApplicationName.SNMP.ToString(); + } - public void AddTab(string host) - { - _viewModel.AddTab(host); - } + public void AddTab(string host) + { + _viewModel.AddTab(host); + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/SNMPSettingsView.xaml.cs b/Source/NETworkManager/Views/SNMPSettingsView.xaml.cs index a4417bc7d4..ed2ab27b1d 100644 --- a/Source/NETworkManager/Views/SNMPSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/SNMPSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SNMPSettingsView { - public partial class SNMPSettingsView - { - private readonly SNMPSettingsViewModel _viewModel = new SNMPSettingsViewModel(); + private readonly SNMPSettingsViewModel _viewModel = new SNMPSettingsViewModel(); - public SNMPSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SNMPSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SNMPView.xaml.cs b/Source/NETworkManager/Views/SNMPView.xaml.cs index bb7365c5a5..3b2e9a3b30 100644 --- a/Source/NETworkManager/Views/SNMPView.xaml.cs +++ b/Source/NETworkManager/Views/SNMPView.xaml.cs @@ -2,30 +2,29 @@ using System.Windows.Controls; using MahApps.Metro.Controls.Dialogs; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SNMPView { - public partial class SNMPView - { - private readonly SNMPViewModel _viewModel; + private readonly SNMPViewModel _viewModel; - public SNMPView(int tabId, string host = null) - { - InitializeComponent(); + public SNMPView(int tabId, string host = null) + { + InitializeComponent(); - _viewModel = new SNMPViewModel(DialogCoordinator.Instance, tabId, host); + _viewModel = new SNMPViewModel(DialogCoordinator.Instance, tabId, host); - DataContext = _viewModel; - } + DataContext = _viewModel; + } - public void CloseTab() - { - _viewModel.OnClose(); - } + public void CloseTab() + { + _viewModel.OnClose(); + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SNTPLookupHostView.xaml.cs b/Source/NETworkManager/Views/SNTPLookupHostView.xaml.cs index 35ae769b3c..ea5cc816b6 100644 --- a/Source/NETworkManager/Views/SNTPLookupHostView.xaml.cs +++ b/Source/NETworkManager/Views/SNTPLookupHostView.xaml.cs @@ -4,28 +4,27 @@ using NETworkManager.Models; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SNTPLookupHostView { - public partial class SNTPLookupHostView - { - private readonly SNTPLookupHostViewModel _viewModel = new (DialogCoordinator.Instance); + private readonly SNTPLookupHostViewModel _viewModel = new (DialogCoordinator.Instance); - public SNTPLookupHostView() - { - InitializeComponent(); - DataContext = _viewModel; + public SNTPLookupHostView() + { + InitializeComponent(); + DataContext = _viewModel; - InterTabController.Partition = ApplicationName.SNTPLookup.ToString(); - } + InterTabController.Partition = ApplicationName.SNTPLookup.ToString(); + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml.cs b/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml.cs index 5c0a2b35ff..778af459c1 100644 --- a/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/SNTPLookupSettingsView.xaml.cs @@ -4,27 +4,26 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SNTPLookupSettingsView { - public partial class SNTPLookupSettingsView - { - private readonly SNTPLookupSettingsViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly SNTPLookupSettingsViewModel _viewModel = new(DialogCoordinator.Instance); - public SNTPLookupSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SNTPLookupSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) - { - _viewModel.EditServer(); - } + private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + _viewModel.EditServer(); } } diff --git a/Source/NETworkManager/Views/SNTPLookupView.xaml.cs b/Source/NETworkManager/Views/SNTPLookupView.xaml.cs index b3cb67bf2b..a088d0f726 100644 --- a/Source/NETworkManager/Views/SNTPLookupView.xaml.cs +++ b/Source/NETworkManager/Views/SNTPLookupView.xaml.cs @@ -3,30 +3,29 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SNTPLookupView { - public partial class SNTPLookupView - { - private readonly SNTPLookupViewModel _viewModel; + private readonly SNTPLookupViewModel _viewModel; - public SNTPLookupView(int tabId) - { - InitializeComponent(); + public SNTPLookupView(int tabId) + { + InitializeComponent(); - _viewModel = new SNTPLookupViewModel(DialogCoordinator.Instance, tabId); + _viewModel = new SNTPLookupViewModel(DialogCoordinator.Instance, tabId); - DataContext = _viewModel; - } - - public void CloseTab() - { - _viewModel.OnClose(); - } + DataContext = _viewModel; + } + + public void CloseTab() + { + _viewModel.OnClose(); + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/ServerConnectionInfoProfileDialog.xaml.cs b/Source/NETworkManager/Views/ServerConnectionInfoProfileDialog.xaml.cs index ddabe53bd3..04094fadc4 100644 --- a/Source/NETworkManager/Views/ServerConnectionInfoProfileDialog.xaml.cs +++ b/Source/NETworkManager/Views/ServerConnectionInfoProfileDialog.xaml.cs @@ -1,31 +1,30 @@ using NETworkManager.Models.Network; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class ServerConnectionInfoProfileDialog { - public partial class ServerConnectionInfoProfileDialog + private (string Server, int Port, TransportProtocol TransportProtocol) _newItemOptions; + public ServerConnectionInfoProfileDialog((string Server, int Port, TransportProtocol TransportProtocol) NewItemOptions) { - private (string Server, int Port, TransportProtocol TransportProtocol) _newItemOptions; - public ServerConnectionInfoProfileDialog((string Server, int Port, TransportProtocol TransportProtocol) NewItemOptions) - { - InitializeComponent(); + InitializeComponent(); - _newItemOptions = NewItemOptions; - } + _newItemOptions = NewItemOptions; + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - TextBoxName.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + TextBoxName.Focus(); + } - private void DataGridServers_AddingNewItem(object sender, System.Windows.Controls.AddingNewItemEventArgs e) + private void DataGridServers_AddingNewItem(object sender, System.Windows.Controls.AddingNewItemEventArgs e) + { + e.NewItem = new ServerConnectionInfo { - e.NewItem = new ServerConnectionInfo - { - Server = _newItemOptions.Server, - Port = _newItemOptions.Port, - TransportProtocol = _newItemOptions.TransportProtocol - }; - } + Server = _newItemOptions.Server, + Port = _newItemOptions.Port, + TransportProtocol = _newItemOptions.TransportProtocol + }; } } diff --git a/Source/NETworkManager/Views/SettingsAppearanceView.xaml.cs b/Source/NETworkManager/Views/SettingsAppearanceView.xaml.cs index f9db4f270d..133a193920 100644 --- a/Source/NETworkManager/Views/SettingsAppearanceView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsAppearanceView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsAppearanceView { - public partial class SettingsAppearanceView - { - private readonly SettingsAppearanceViewModel _viewModel = new SettingsAppearanceViewModel(); + private readonly SettingsAppearanceViewModel _viewModel = new SettingsAppearanceViewModel(); - public SettingsAppearanceView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsAppearanceView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SettingsAutostartView.xaml.cs b/Source/NETworkManager/Views/SettingsAutostartView.xaml.cs index 88e981b51e..a6fb090fb2 100644 --- a/Source/NETworkManager/Views/SettingsAutostartView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsAutostartView.xaml.cs @@ -1,16 +1,15 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsAutostartView { - public partial class SettingsAutostartView - { - private readonly SettingsAutostartViewModel _viewModel = new SettingsAutostartViewModel(DialogCoordinator.Instance); + private readonly SettingsAutostartViewModel _viewModel = new SettingsAutostartViewModel(DialogCoordinator.Instance); - public SettingsAutostartView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsAutostartView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SettingsGeneralView.xaml.cs b/Source/NETworkManager/Views/SettingsGeneralView.xaml.cs index 42b4c38196..1b0ee1277a 100644 --- a/Source/NETworkManager/Views/SettingsGeneralView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsGeneralView.xaml.cs @@ -1,34 +1,33 @@ using System.Windows.Input; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsGeneralView { - public partial class SettingsGeneralView - { - private readonly SettingsGeneralViewModel _viewModel = new SettingsGeneralViewModel(); + private readonly SettingsGeneralViewModel _viewModel = new SettingsGeneralViewModel(); - public SettingsGeneralView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsGeneralView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ListBoxVisibleToHide_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) - { - if(!_viewModel.IsVisibleToHideApplicationEnabled) - return; + private void ListBoxVisibleToHide_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if(!_viewModel.IsVisibleToHideApplicationEnabled) + return; - if (e.ChangedButton == MouseButton.Left) - _viewModel.VisibleToHideApplicationCommand.Execute(null); - } + if (e.ChangedButton == MouseButton.Left) + _viewModel.VisibleToHideApplicationCommand.Execute(null); + } - private void ListBoxHideToVisible_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) - { - if (!_viewModel.IsHideToVisibleApplicationEnabled) - return; + private void ListBoxHideToVisible_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (!_viewModel.IsHideToVisibleApplicationEnabled) + return; - if (e.ChangedButton == MouseButton.Left) - _viewModel.HideToVisibleApplicationCommand.Execute(null); - } + if (e.ChangedButton == MouseButton.Left) + _viewModel.HideToVisibleApplicationCommand.Execute(null); } } diff --git a/Source/NETworkManager/Views/SettingsHotKeysView.xaml.cs b/Source/NETworkManager/Views/SettingsHotKeysView.xaml.cs index ec80a74991..f4c5320c57 100644 --- a/Source/NETworkManager/Views/SettingsHotKeysView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsHotKeysView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsHotKeysView { - public partial class SettingsHotKeysView - { - private readonly SettingsHotKeysViewModel _viewModel = new SettingsHotKeysViewModel(); + private readonly SettingsHotKeysViewModel _viewModel = new SettingsHotKeysViewModel(); - public SettingsHotKeysView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsHotKeysView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SettingsLanguageView.xaml.cs b/Source/NETworkManager/Views/SettingsLanguageView.xaml.cs index f0cbb4cfa3..a8476db9c4 100644 --- a/Source/NETworkManager/Views/SettingsLanguageView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsLanguageView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsLanguageView { - public partial class SettingsLanguageView - { - private readonly SettingsLanguageViewModel _viewModel = new(); + private readonly SettingsLanguageViewModel _viewModel = new(); - public SettingsLanguageView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsLanguageView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SettingsNetworkView.xaml.cs b/Source/NETworkManager/Views/SettingsNetworkView.xaml.cs index d298f22802..4ce7c1f01a 100644 --- a/Source/NETworkManager/Views/SettingsNetworkView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsNetworkView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsNetworkView { - public partial class SettingsNetworkView - { - private readonly SettingsNetworkViewModel _viewModel = new(); + private readonly SettingsNetworkViewModel _viewModel = new(); - public SettingsNetworkView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsNetworkView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SettingsProfilesView.xaml.cs b/Source/NETworkManager/Views/SettingsProfilesView.xaml.cs index 93c32facea..d7e62a199f 100644 --- a/Source/NETworkManager/Views/SettingsProfilesView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsProfilesView.xaml.cs @@ -3,38 +3,37 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsProfilesView { - public partial class SettingsProfilesView + private readonly SettingsProfilesViewModel _viewModel = new SettingsProfilesViewModel(DialogCoordinator.Instance); + + public SettingsProfilesView() + { + InitializeComponent(); + DataContext = _viewModel; + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + if (_viewModel.CloseAction != null) + return; + + var window = Window.GetWindow(this); + + if (window != null) + _viewModel.CloseAction = window.Close; + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void DataGridRow_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { - private readonly SettingsProfilesViewModel _viewModel = new SettingsProfilesViewModel(DialogCoordinator.Instance); - - public SettingsProfilesView() - { - InitializeComponent(); - DataContext = _viewModel; - } - - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - if (_viewModel.CloseAction != null) - return; - - var window = Window.GetWindow(this); - - if (window != null) - _viewModel.CloseAction = window.Close; - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void DataGridRow_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - _viewModel.EditProfileFileCommand.Execute(null); - } + _viewModel.EditProfileFileCommand.Execute(null); } } diff --git a/Source/NETworkManager/Views/SettingsSettingsView.xaml.cs b/Source/NETworkManager/Views/SettingsSettingsView.xaml.cs index eff65869aa..aebc0663ed 100644 --- a/Source/NETworkManager/Views/SettingsSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsSettingsView.xaml.cs @@ -2,32 +2,31 @@ using NETworkManager.ViewModels; using System.Windows; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsSettingsView { - public partial class SettingsSettingsView - { - private readonly SettingsSettingsViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly SettingsSettingsViewModel _viewModel = new(DialogCoordinator.Instance); - public SettingsSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - if (_viewModel.CloseAction != null) - return; + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + if (_viewModel.CloseAction != null) + return; - var window = Window.GetWindow(this); + var window = Window.GetWindow(this); - if (window != null) - _viewModel.CloseAction = window.Close; - } + if (window != null) + _viewModel.CloseAction = window.Close; + } - public void OnVisible() - { + public void OnVisible() + { - } } } diff --git a/Source/NETworkManager/Views/SettingsStatusView.xaml.cs b/Source/NETworkManager/Views/SettingsStatusView.xaml.cs index 8ca24bc5c7..00059f970d 100644 --- a/Source/NETworkManager/Views/SettingsStatusView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsStatusView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsStatusView { - public partial class SettingsStatusView - { - private readonly SettingsStatusViewModel _viewModel = new SettingsStatusViewModel(); + private readonly SettingsStatusViewModel _viewModel = new SettingsStatusViewModel(); - public SettingsStatusView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsStatusView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SettingsUpdateView.xaml.cs b/Source/NETworkManager/Views/SettingsUpdateView.xaml.cs index 2eeea76186..e431a59b36 100644 --- a/Source/NETworkManager/Views/SettingsUpdateView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsUpdateView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsUpdateView { - public partial class SettingsUpdateView - { - private readonly SettingsUpdateViewModel _viewModel = new SettingsUpdateViewModel(); + private readonly SettingsUpdateViewModel _viewModel = new SettingsUpdateViewModel(); - public SettingsUpdateView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsUpdateView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SettingsView.xaml.cs b/Source/NETworkManager/Views/SettingsView.xaml.cs index a64bd9add9..c8720da57f 100644 --- a/Source/NETworkManager/Views/SettingsView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsView.xaml.cs @@ -3,41 +3,40 @@ using NETworkManager.Settings; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsView { - public partial class SettingsView + private readonly SettingsViewModel _viewModel; + + public SettingsView(ApplicationName applicationName) + { + InitializeComponent(); + _viewModel = new SettingsViewModel(applicationName); + + DataContext = _viewModel; + } + + private void ScrollViewer_ManipulationBoundaryFeedback(object sender, System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e) { - private readonly SettingsViewModel _viewModel; - - public SettingsView(ApplicationName applicationName) - { - InitializeComponent(); - _viewModel = new SettingsViewModel(applicationName); - - DataContext = _viewModel; - } - - private void ScrollViewer_ManipulationBoundaryFeedback(object sender, System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e) - { - e.Handled = true; - } - - public void ChangeSettingsView(ApplicationName name) - { - _viewModel.ChangeSettingsView(name); - - // Scroll into view - ListBoxSettings.ScrollIntoView(_viewModel.SelectedSettingsView); - } - - public void Refresh() - { - ProfilesView.Refresh(); - } - - public DocumentationIdentifier GetDocumentationIdentifier() - { - return _viewModel.GetDocumentationIdentifier(); - } + e.Handled = true; } + + public void ChangeSettingsView(ApplicationName name) + { + _viewModel.ChangeSettingsView(name); + + // Scroll into view + ListBoxSettings.ScrollIntoView(_viewModel.SelectedSettingsView); + } + + public void Refresh() + { + ProfilesView.Refresh(); + } + + public DocumentationIdentifier GetDocumentationIdentifier() + { + return _viewModel.GetDocumentationIdentifier(); + } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/SettingsWindowView.xaml.cs b/Source/NETworkManager/Views/SettingsWindowView.xaml.cs index 6effadeb1c..9f2a625841 100644 --- a/Source/NETworkManager/Views/SettingsWindowView.xaml.cs +++ b/Source/NETworkManager/Views/SettingsWindowView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SettingsWindowView { - public partial class SettingsWindowView - { - private readonly SettingsWindowViewModel _viewModel = new SettingsWindowViewModel(); + private readonly SettingsWindowViewModel _viewModel = new SettingsWindowViewModel(); - public SettingsWindowView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SettingsWindowView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SubnetCalculatorCalculatorView.xaml.cs b/Source/NETworkManager/Views/SubnetCalculatorCalculatorView.xaml.cs index d44f95873b..07a48dacc0 100644 --- a/Source/NETworkManager/Views/SubnetCalculatorCalculatorView.xaml.cs +++ b/Source/NETworkManager/Views/SubnetCalculatorCalculatorView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SubnetCalculatorCalculatorView { - public partial class SubnetCalculatorCalculatorView - { - private readonly SubnetCalculatorCalculatorViewModel _viewModel = new SubnetCalculatorCalculatorViewModel(); + private readonly SubnetCalculatorCalculatorViewModel _viewModel = new SubnetCalculatorCalculatorViewModel(); - public SubnetCalculatorCalculatorView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SubnetCalculatorCalculatorView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SubnetCalculatorHostView.xaml.cs b/Source/NETworkManager/Views/SubnetCalculatorHostView.xaml.cs index 4e68897208..e9a29af843 100644 --- a/Source/NETworkManager/Views/SubnetCalculatorHostView.xaml.cs +++ b/Source/NETworkManager/Views/SubnetCalculatorHostView.xaml.cs @@ -1,25 +1,24 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SubnetCalculatorHostView { - public partial class SubnetCalculatorHostView - { - private readonly SubnetCalculatorHostViewModel _viewModel = new(); + private readonly SubnetCalculatorHostViewModel _viewModel = new(); - public SubnetCalculatorHostView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public SubnetCalculatorHostView() + { + InitializeComponent(); + DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/SubnetCalculatorSubnettingView.xaml.cs b/Source/NETworkManager/Views/SubnetCalculatorSubnettingView.xaml.cs index 2eb77aae81..7b732cb311 100644 --- a/Source/NETworkManager/Views/SubnetCalculatorSubnettingView.xaml.cs +++ b/Source/NETworkManager/Views/SubnetCalculatorSubnettingView.xaml.cs @@ -2,29 +2,28 @@ using NETworkManager.ViewModels; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SubnetCalculatorSubnettingView { - public partial class SubnetCalculatorSubnettingView - { - private readonly SubnetCalculatorSubnettingViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly SubnetCalculatorSubnettingViewModel _viewModel = new(DialogCoordinator.Instance); - public SubnetCalculatorSubnettingView() - { - InitializeComponent(); - DataContext = _viewModel; + public SubnetCalculatorSubnettingView() + { + InitializeComponent(); + DataContext = _viewModel; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) - { - _viewModel.OnShutdown(); - } + private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) + { + _viewModel.OnShutdown(); + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/SubnetCalculatorWideSubnetView.xaml.cs b/Source/NETworkManager/Views/SubnetCalculatorWideSubnetView.xaml.cs index 07d840a23c..f3badc4a7e 100644 --- a/Source/NETworkManager/Views/SubnetCalculatorWideSubnetView.xaml.cs +++ b/Source/NETworkManager/Views/SubnetCalculatorWideSubnetView.xaml.cs @@ -1,23 +1,22 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class SubnetCalculatorWideSubnetView { - public partial class SubnetCalculatorWideSubnetView - { - private readonly SubnetCalculatorWideSubnetViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly SubnetCalculatorWideSubnetViewModel _viewModel = new(DialogCoordinator.Instance); - public SubnetCalculatorWideSubnetView() - { - InitializeComponent(); - DataContext = _viewModel; + public SubnetCalculatorWideSubnetView() + { + InitializeComponent(); + DataContext = _viewModel; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) - { - _viewModel.OnShutdown(); - } + private void Dispatcher_ShutdownStarted(object sender, System.EventArgs e) + { + _viewModel.OnShutdown(); } } diff --git a/Source/NETworkManager/Views/TigerVNCConnectDialog.xaml.cs b/Source/NETworkManager/Views/TigerVNCConnectDialog.xaml.cs index 08ebba7232..5d95553345 100644 --- a/Source/NETworkManager/Views/TigerVNCConnectDialog.xaml.cs +++ b/Source/NETworkManager/Views/TigerVNCConnectDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class TigerVNCConnectDialog { - public partial class TigerVNCConnectDialog + public TigerVNCConnectDialog() { - public TigerVNCConnectDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - ComboBoxHost.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + ComboBoxHost.Focus(); } } diff --git a/Source/NETworkManager/Views/TigerVNCHostView.xaml.cs b/Source/NETworkManager/Views/TigerVNCHostView.xaml.cs index 9f623904b3..eb2a6a8347 100644 --- a/Source/NETworkManager/Views/TigerVNCHostView.xaml.cs +++ b/Source/NETworkManager/Views/TigerVNCHostView.xaml.cs @@ -5,59 +5,58 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class TigerVNCHostView { - public partial class TigerVNCHostView + private readonly TigerVNCHostViewModel _viewModel = new TigerVNCHostViewModel(DialogCoordinator.Instance); + + private bool _loaded; + + + public TigerVNCHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.TigerVNC.ToString(); + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + _loaded = true; + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ConnectProfileCommand.Execute(null); + } + + public async Task AddTab(string host) + { + // Wait for the interface to load, before displaying the dialog to connect a new profile... + // MahApps will throw an exception... + while (!_loaded) + await Task.Delay(250); + + if (_viewModel.IsConfigured) + _viewModel.AddTab(host); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible() { - private readonly TigerVNCHostViewModel _viewModel = new TigerVNCHostViewModel(DialogCoordinator.Instance); - - private bool _loaded; - - - public TigerVNCHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.TigerVNC.ToString(); - } - - private void UserControl_Loaded(object sender, RoutedEventArgs e) - { - _loaded = true; - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ConnectProfileCommand.Execute(null); - } - - public async Task AddTab(string host) - { - // Wait for the interface to load, before displaying the dialog to connect a new profile... - // MahApps will throw an exception... - while (!_loaded) - await Task.Delay(250); - - if (_viewModel.IsConfigured) - _viewModel.AddTab(host); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/TigerVNCSettingsView.xaml.cs b/Source/NETworkManager/Views/TigerVNCSettingsView.xaml.cs index e83fba112b..4af570595d 100644 --- a/Source/NETworkManager/Views/TigerVNCSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/TigerVNCSettingsView.xaml.cs @@ -2,33 +2,32 @@ using NETworkManager.ViewModels; using System.Windows; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class TigerVNCSettingsView { - public partial class TigerVNCSettingsView - { - private readonly TigerVNCSettingsViewModel _viewModel = new TigerVNCSettingsViewModel(DialogCoordinator.Instance); + private readonly TigerVNCSettingsViewModel _viewModel = new TigerVNCSettingsViewModel(DialogCoordinator.Instance); - public TigerVNCSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public TigerVNCSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) - { - if (!e.Data.GetDataPresent(DataFormats.FileDrop)) - return; + private void TextBoxApplicationFilePath_Drop(object sender, DragEventArgs e) + { + if (!e.Data.GetDataPresent(DataFormats.FileDrop)) + return; - var files = (string[])e.Data.GetData(DataFormats.FileDrop); + var files = (string[])e.Data.GetData(DataFormats.FileDrop); - if (files != null) - _viewModel.SetFilePathFromDragDrop(files[0]); - } + if (files != null) + _viewModel.SetFilePathFromDragDrop(files[0]); + } - private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) - { - e.Effects = DragDropEffects.Copy; - e.Handled = true; - } + private void TextBoxApplicationFilePath_PreviewDragOver(object sender, DragEventArgs e) + { + e.Effects = DragDropEffects.Copy; + e.Handled = true; } } diff --git a/Source/NETworkManager/Views/TracerouteHostView.xaml.cs b/Source/NETworkManager/Views/TracerouteHostView.xaml.cs index 48566c3460..69799cdcc5 100644 --- a/Source/NETworkManager/Views/TracerouteHostView.xaml.cs +++ b/Source/NETworkManager/Views/TracerouteHostView.xaml.cs @@ -6,50 +6,49 @@ using NETworkManager.Profiles; using NETworkManager.Models; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class TracerouteHostView { - public partial class TracerouteHostView + private readonly TracerouteHostViewModel _viewModel = new TracerouteHostViewModel(DialogCoordinator.Instance); + + public TracerouteHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.Traceroute.ToString(); + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.TraceProfileCommand.Execute(null); + } + + public void AddTab(string host) + { + _viewModel.AddTab(host); + } + + public void AddTab(ProfileInfo profile) + { + _viewModel.AddTab(profile); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible() { - private readonly TracerouteHostViewModel _viewModel = new TracerouteHostViewModel(DialogCoordinator.Instance); - - public TracerouteHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.Traceroute.ToString(); - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.TraceProfileCommand.Execute(null); - } - - public void AddTab(string host) - { - _viewModel.AddTab(host); - } - - public void AddTab(ProfileInfo profile) - { - _viewModel.AddTab(profile); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/TracerouteSettingsView.xaml.cs b/Source/NETworkManager/Views/TracerouteSettingsView.xaml.cs index 6fcce9d9f4..14cdd2bfb9 100644 --- a/Source/NETworkManager/Views/TracerouteSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/TracerouteSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class TracerouteSettingsView { - public partial class TracerouteSettingsView - { - private readonly TracerouteSettingsViewModel _viewModel = new TracerouteSettingsViewModel(); + private readonly TracerouteSettingsViewModel _viewModel = new TracerouteSettingsViewModel(); - public TracerouteSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public TracerouteSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/TracerouteView.xaml.cs b/Source/NETworkManager/Views/TracerouteView.xaml.cs index 5bea0113b9..b27c00fa04 100644 --- a/Source/NETworkManager/Views/TracerouteView.xaml.cs +++ b/Source/NETworkManager/Views/TracerouteView.xaml.cs @@ -3,42 +3,41 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class TracerouteView { - public partial class TracerouteView - { - private readonly TracerouteViewModel _viewModel; + private readonly TracerouteViewModel _viewModel; - public TracerouteView(int tabId, string host = null) - { - InitializeComponent(); + public TracerouteView(int tabId, string host = null) + { + InitializeComponent(); - _viewModel = new TracerouteViewModel(DialogCoordinator.Instance, tabId, host); + _viewModel = new TracerouteViewModel(DialogCoordinator.Instance, tabId, host); - DataContext = _viewModel; + DataContext = _viewModel; - Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; - } + Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted; + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - _viewModel.OnLoaded(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + _viewModel.OnLoaded(); + } - private void Dispatcher_ShutdownStarted(object sender, EventArgs e) - { - _viewModel.OnClose(); - } + private void Dispatcher_ShutdownStarted(object sender, EventArgs e) + { + _viewModel.OnClose(); + } - public void CloseTab() - { - _viewModel.OnClose(); - } + public void CloseTab() + { + _viewModel.OnClose(); + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; } } \ No newline at end of file diff --git a/Source/NETworkManager/Views/WakeOnLANSettingsView.xaml.cs b/Source/NETworkManager/Views/WakeOnLANSettingsView.xaml.cs index c55c720242..1b840017ab 100644 --- a/Source/NETworkManager/Views/WakeOnLANSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/WakeOnLANSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WakeOnLANSettingsView { - public partial class WakeOnLANSettingsView - { - private readonly WakeOnLANSettingsViewModel _viewModel = new(); + private readonly WakeOnLANSettingsViewModel _viewModel = new(); - public WakeOnLANSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public WakeOnLANSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/WakeOnLANView.xaml.cs b/Source/NETworkManager/Views/WakeOnLANView.xaml.cs index 7fc1c02331..2989528e95 100644 --- a/Source/NETworkManager/Views/WakeOnLANView.xaml.cs +++ b/Source/NETworkManager/Views/WakeOnLANView.xaml.cs @@ -3,32 +3,31 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WakeOnLANView { - public partial class WakeOnLANView - { - private readonly WakeOnLANViewModel _viewModel = new(DialogCoordinator.Instance); + private readonly WakeOnLANViewModel _viewModel = new(DialogCoordinator.Instance); - public WakeOnLANView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public WakeOnLANView() + { + InitializeComponent(); + DataContext = _viewModel; + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/WebConsoleConnectDialog.xaml.cs b/Source/NETworkManager/Views/WebConsoleConnectDialog.xaml.cs index 87c0dd2966..e5510e3716 100644 --- a/Source/NETworkManager/Views/WebConsoleConnectDialog.xaml.cs +++ b/Source/NETworkManager/Views/WebConsoleConnectDialog.xaml.cs @@ -1,16 +1,15 @@ -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WebConsoleConnectDialog { - public partial class WebConsoleConnectDialog + public WebConsoleConnectDialog() { - public WebConsoleConnectDialog() - { - InitializeComponent(); - } + InitializeComponent(); + } - private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - // Need to be in loaded event, focusmanger won't work... - ComboBoxUrl.Focus(); - } + private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e) + { + // Need to be in loaded event, focusmanger won't work... + ComboBoxUrl.Focus(); } } diff --git a/Source/NETworkManager/Views/WebConsoleHostView.xaml.cs b/Source/NETworkManager/Views/WebConsoleHostView.xaml.cs index 4826a1b103..ef52e35345 100644 --- a/Source/NETworkManager/Views/WebConsoleHostView.xaml.cs +++ b/Source/NETworkManager/Views/WebConsoleHostView.xaml.cs @@ -4,40 +4,39 @@ using System.Windows; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WebConsoleHostView { - public partial class WebConsoleHostView - { - private readonly WebConsoleHostViewModel _viewModel = new WebConsoleHostViewModel(DialogCoordinator.Instance); + private readonly WebConsoleHostViewModel _viewModel = new WebConsoleHostViewModel(DialogCoordinator.Instance); - public WebConsoleHostView() - { - InitializeComponent(); - DataContext = _viewModel; + public WebConsoleHostView() + { + InitializeComponent(); + DataContext = _viewModel; - InterTabController.Partition = ApplicationName.WebConsole.ToString(); - } + InterTabController.Partition = ApplicationName.WebConsole.ToString(); + } - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.ConnectProfileCommand.Execute(null); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.ConnectProfileCommand.Execute(null); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/WhoisHostView.xaml.cs b/Source/NETworkManager/Views/WhoisHostView.xaml.cs index 31197c2124..da1c8b0fb5 100644 --- a/Source/NETworkManager/Views/WhoisHostView.xaml.cs +++ b/Source/NETworkManager/Views/WhoisHostView.xaml.cs @@ -4,40 +4,39 @@ using NETworkManager.Models; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WhoisHostView { - public partial class WhoisHostView + private readonly WhoisHostViewModel _viewModel = new WhoisHostViewModel(DialogCoordinator.Instance); + + public WhoisHostView() + { + InitializeComponent(); + DataContext = _viewModel; + + InterTabController.Partition = ApplicationName.Whois.ToString(); + } + + private void ContextMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; + } + + private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) + { + if (e.ChangedButton == System.Windows.Input.MouseButton.Left) + _viewModel.QueryProfileCommand.Execute(null); + } + + public void OnViewHide() + { + _viewModel.OnViewHide(); + } + + public void OnViewVisible() { - private readonly WhoisHostViewModel _viewModel = new WhoisHostViewModel(DialogCoordinator.Instance); - - public WhoisHostView() - { - InitializeComponent(); - DataContext = _viewModel; - - InterTabController.Partition = ApplicationName.Whois.ToString(); - } - - private void ContextMenu_Opened(object sender, RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } - - private void ListBoxItem_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) - { - if (e.ChangedButton == System.Windows.Input.MouseButton.Left) - _viewModel.QueryProfileCommand.Execute(null); - } - - public void OnViewHide() - { - _viewModel.OnViewHide(); - } - - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + _viewModel.OnViewVisible(); } } diff --git a/Source/NETworkManager/Views/WhoisSettingsView.xaml.cs b/Source/NETworkManager/Views/WhoisSettingsView.xaml.cs index 58dbde6f9f..c5103750e5 100644 --- a/Source/NETworkManager/Views/WhoisSettingsView.xaml.cs +++ b/Source/NETworkManager/Views/WhoisSettingsView.xaml.cs @@ -1,15 +1,14 @@ using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WhoisSettingsView { - public partial class WhoisSettingsView - { - private readonly WhoisSettingsViewModel _viewModel = new WhoisSettingsViewModel(); + private readonly WhoisSettingsViewModel _viewModel = new WhoisSettingsViewModel(); - public WhoisSettingsView() - { - InitializeComponent(); - DataContext = _viewModel; - } + public WhoisSettingsView() + { + InitializeComponent(); + DataContext = _viewModel; } } diff --git a/Source/NETworkManager/Views/WhoisView.xaml.cs b/Source/NETworkManager/Views/WhoisView.xaml.cs index 33e09c18aa..b22a62ccb6 100644 --- a/Source/NETworkManager/Views/WhoisView.xaml.cs +++ b/Source/NETworkManager/Views/WhoisView.xaml.cs @@ -2,29 +2,28 @@ using MahApps.Metro.Controls.Dialogs; using NETworkManager.ViewModels; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WhoisView { - public partial class WhoisView - { - private readonly WhoisViewModel _viewModel; + private readonly WhoisViewModel _viewModel; - public WhoisView(int tabId, string domain = null) - { - InitializeComponent(); + public WhoisView(int tabId, string domain = null) + { + InitializeComponent(); - _viewModel = new WhoisViewModel(DialogCoordinator.Instance, tabId, domain); + _viewModel = new WhoisViewModel(DialogCoordinator.Instance, tabId, domain); - DataContext = _viewModel; - } + DataContext = _viewModel; + } - private void UserControl_OnLoaded(object sender, RoutedEventArgs e) - { - _viewModel.OnLoaded(); - } + private void UserControl_OnLoaded(object sender, RoutedEventArgs e) + { + _viewModel.OnLoaded(); + } - public void CloseTab() - { - _viewModel.OnClose(); - } + public void CloseTab() + { + _viewModel.OnClose(); } } diff --git a/Source/NETworkManager/Views/WiFiView.xaml.cs b/Source/NETworkManager/Views/WiFiView.xaml.cs index ad586783b7..2582e761c1 100644 --- a/Source/NETworkManager/Views/WiFiView.xaml.cs +++ b/Source/NETworkManager/Views/WiFiView.xaml.cs @@ -2,33 +2,32 @@ using NETworkManager.ViewModels; using System.Windows.Controls; -namespace NETworkManager.Views +namespace NETworkManager.Views; + +public partial class WiFiView { - public partial class WiFiView - { - private readonly WiFiViewModel _viewModel; + private readonly WiFiViewModel _viewModel; - public WiFiView() - { - _viewModel= new WiFiViewModel(DialogCoordinator.Instance); - InitializeComponent(); - DataContext = _viewModel; - } + public WiFiView() + { + _viewModel= new WiFiViewModel(DialogCoordinator.Instance); + InitializeComponent(); + DataContext = _viewModel; + } - public void OnViewHide() - { - _viewModel.OnViewHide(); - } + public void OnViewHide() + { + _viewModel.OnViewHide(); + } - public void OnViewVisible() - { - _viewModel.OnViewVisible(); - } + public void OnViewVisible() + { + _viewModel.OnViewVisible(); + } - private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) - { - if (sender is ContextMenu menu) - menu.DataContext = _viewModel; - } + private void ContextMenu_Opened(object sender, System.Windows.RoutedEventArgs e) + { + if (sender is ContextMenu menu) + menu.DataContext = _viewModel; } }