diff --git a/Source/GlobalAssemblyInfo.cs b/Source/GlobalAssemblyInfo.cs index 253d93713a..e59641343d 100644 --- a/Source/GlobalAssemblyInfo.cs +++ b/Source/GlobalAssemblyInfo.cs @@ -6,5 +6,5 @@ [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("2026.11.21.0")] -[assembly: AssemblyFileVersion("2026.11.21.0")] +[assembly: AssemblyVersion("2026.11.22.0")] +[assembly: AssemblyFileVersion("2026.11.22.0")] diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 3890e3a6d2..404f9bc8bf 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -1419,6 +1419,15 @@ public static string ApplyFilter { } } + /// + /// Looks up a localized string similar to Apply the profile to the selected network interface "{0}" instead?. + /// + public static string ApplyProfileToSelectedNetworkInterfaceXInstead { + get { + return ResourceManager.GetString("ApplyProfileToSelectedNetworkInterfaceXInstead", resourceCulture); + } + } + /// /// Looks up a localized string similar to Apply theme to PowerShell console. /// @@ -1689,6 +1698,15 @@ public static string BetaFeatureMessage { } } + /// + /// Looks up a localized string similar to Bind to network interface. + /// + public static string BindToNetworkInterface { + get { + return ResourceManager.GetString("BindToNetworkInterface", resourceCulture); + } + } + /// /// Looks up a localized string similar to Bit Calculator. /// @@ -2377,6 +2395,15 @@ public static string CommandXDoesNotSupportProfiles { } } + /// + /// Looks up a localized string similar to The command "{0}" only accepts a profile: enter "@" and the name of the profile!. + /// + public static string CommandXOnlyAcceptsAProfile { + get { + return ResourceManager.GetString("CommandXOnlyAcceptsAProfile", resourceCulture); + } + } + /// /// Looks up a localized string similar to Comment. /// @@ -5264,6 +5291,15 @@ public static string FailedToLoadHostsFileMessage { } } + /// + /// Looks up a localized string similar to Failed to load the network interfaces. Disable "Bind to network interface" and enable it again to try again.. + /// + public static string FailedToLoadNetworkInterfacesTryAgain { + get { + return ResourceManager.GetString("FailedToLoadNetworkInterfacesTryAgain", resourceCulture); + } + } + /// /// Looks up a localized string similar to Fax. /// @@ -5761,6 +5797,15 @@ public static string FixedScreenSize { } } + /// + /// Looks up a localized string similar to To fix this, edit the profile and select another network interface or disable "Bind to network interface".. + /// + public static string FixNetworkInterfaceOfProfileHint { + get { + return ResourceManager.GetString("FixNetworkInterfaceOfProfileHint", resourceCulture); + } + } + /// /// Looks up a localized string similar to Flush DNS cache. /// @@ -6081,7 +6126,7 @@ public static string HelpMessage_Animations { /// ///Only the PowerShell consoles configured in the PowerShell settings are modified. Both Windows PowerShell and PWSH (PowerShell 7 and higher) are supported. /// - ///Click in the upper right corner on the help / documentation button ( [rest of string was truncated]";. + ///Click in the upper right corner on the help / documentation button (left [rest of string was truncated]";. /// public static string HelpMessage_ApplyThemeToPowerShellConsole { get { @@ -6102,6 +6147,15 @@ public static string HelpMessage_BackgroundJob { } } + /// + /// Looks up a localized string similar to The profile is always applied to this network interface (not to the one selected in Network Interface), selecting the profile also selects the network interface. The network interface is identified by its ID, which is unique per computer: on another computer, select the network interface again or disable this option.. + /// + public static string HelpMessage_BindToNetworkInterface { + get { + return ResourceManager.GetString("HelpMessage_BindToNetworkInterface", resourceCulture); + } + } + /// /// Looks up a localized string similar to The DNS resolver is determined via ip-api.com. /// @@ -8958,6 +9012,24 @@ public static string NetworkInterface { } } + /// + /// Looks up a localized string similar to "{0}" is not a valid IPv4 address or subnet mask. Check the configuration (or the profile) and try again.. + /// + public static string NetworkInterfaceConfigInvalidValueX { + get { + return ResourceManager.GetString("NetworkInterfaceConfigInvalidValueX", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A static IP address needs an IPv4 address and a subnet mask. Check the configuration (or the profile) and try again.. + /// + public static string NetworkInterfaceConfigIPAddressAndSubnetmaskRequired { + get { + return ResourceManager.GetString("NetworkInterfaceConfigIPAddressAndSubnetmaskRequired", resourceCulture); + } + } + /// /// Looks up a localized string similar to Configuration applied. /// @@ -8976,6 +9048,42 @@ public static string NetworkInterfaceConfigureAdminMessage { } } + /// + /// Looks up a localized string similar to Network interface not found. + /// + public static string NetworkInterfaceNotFound { + get { + return ResourceManager.GetString("NetworkInterfaceNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The network interface of the profile "{0}" was not found on this computer:. + /// + public static string NetworkInterfaceOfProfileXNotFoundOnThisComputer { + get { + return ResourceManager.GetString("NetworkInterfaceOfProfileXNotFoundOnThisComputer", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The network interface "{0}" was not found (e.g. it was removed). Nothing was changed.. + /// + public static string NetworkInterfaceXNotFoundNothingChanged { + get { + return ResourceManager.GetString("NetworkInterfaceXNotFoundNothingChanged", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The network interface "{0}" of the profile was not found on this computer. The values are filled in for the selected network interface, check it before you apply them.. + /// + public static string NetworkInterfaceXOfProfileNotFoundCheckSelected { + get { + return ResourceManager.GetString("NetworkInterfaceXOfProfileNotFoundCheckSelected", resourceCulture); + } + } + /// /// Looks up a localized string similar to Network kind. /// @@ -9292,6 +9400,15 @@ public static string Note { } } + /// + /// Looks up a localized string similar to Not found on this computer. + /// + public static string NotFoundOnThisComputer { + get { + return ResourceManager.GetString("NotFoundOnThisComputer", resourceCulture); + } + } + /// /// Looks up a localized string similar to Nothing found!. /// @@ -10420,7 +10537,7 @@ public static string Profile { /// /// Looks up a localized string similar to Profile files are encrypted on disk using AES with a key size of 256 bits and a block size of 128 bits in CBC mode. The encryption key is derived from a master password using Rfc2898DeriveBytes (PBKDF2) with 1,000,000 iterations. At runtime, passwords are stored as SecureString once the profile file is loaded. For some functions, the password must be converted to a normal string and remains unencrypted in memory until the garbage collector cleans them up. /// - ///First make a backup copy of your profile files be [rest of string was truncated]";. + ///First make a backup copy of your profile files befo [rest of string was truncated]";. /// public static string ProfileEncryptionDisclaimer { get { @@ -10571,6 +10688,15 @@ public static string ProfileXNotFound { } } + /// + /// Looks up a localized string similar to The profile "{0}" was not loaded, because a configuration is being applied. Run the command again when it has finished.. + /// + public static string ProfileXNotLoadedConfigurationRunning { + get { + return ResourceManager.GetString("ProfileXNotLoadedConfigurationRunning", resourceCulture); + } + } + /// /// Looks up a localized string similar to Program. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index fb17fd0761..1f77193dd5 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5654,4 +5654,46 @@ Do you want to start the scan? The last used network interface is not available, "{0}" is used instead. + + "{0}" is not a valid IPv4 address or subnet mask. Check the configuration (or the profile) and try again. + + + Bind to network interface + + + The profile is always applied to this network interface (not to the one selected in Network Interface), selecting the profile also selects the network interface. The network interface is identified by its ID, which is unique per computer: on another computer, select the network interface again or disable this option. + + + Not found on this computer + + + Network interface not found + + + The network interface of the profile "{0}" was not found on this computer: + + + Apply the profile to the selected network interface "{0}" instead? + + + To fix this, edit the profile and select another network interface or disable "Bind to network interface". + + + The network interface "{0}" was not found (e.g. it was removed). Nothing was changed. + + + The network interface "{0}" of the profile was not found on this computer. The values are filled in for the selected network interface, check it before you apply them. + + + A static IP address needs an IPv4 address and a subnet mask. Check the configuration (or the profile) and try again. + + + Failed to load the network interfaces. Disable "Bind to network interface" and enable it again to try again. + + + The command "{0}" only accepts a profile: enter "@" and the name of the profile! + + + The profile "{0}" was not loaded, because a configuration is being applied. Run the command again when it has finished. + \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/BandwidthMeter.cs b/Source/NETworkManager.Models/Network/BandwidthMeter.cs index 33018b3634..f7499b9a5c 100644 --- a/Source/NETworkManager.Models/Network/BandwidthMeter.cs +++ b/Source/NETworkManager.Models/Network/BandwidthMeter.cs @@ -15,8 +15,8 @@ public BandwidthMeter(string id) _timer.Interval = TimeSpan.FromMilliseconds(UpdateInterval); _timer.Tick += Timer_Tick; - _networkInterface = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() - .FirstOrDefault(x => x.Id == id); + _id = id; + _networkInterface = FindNetworkInterface(id); } #endregion @@ -55,7 +55,8 @@ public double UpdateInterval public bool IsRunning => _timer.IsEnabled; private readonly DispatcherTimer _timer = new(); - private readonly System.Net.NetworkInformation.NetworkInterface _networkInterface; + private readonly string _id; + private System.Net.NetworkInformation.NetworkInterface _networkInterface; private readonly Stopwatch _stopwatch = new(); private long _previousBytesSent; private long _previousBytesReceived; @@ -91,7 +92,10 @@ public void Stop() private void Update() { - // The interface may have been removed/disabled after this meter was created. + // The interface may have been removed/disabled after this meter was created: look it up again (e.g. a + // VPN or USB adapter that was added again with the same ID). + _networkInterface ??= FindNetworkInterface(_id); + if (_networkInterface == null) return; @@ -104,7 +108,11 @@ private void Update() } catch (NetworkInformationException) { - // Transient failure (e.g. adapter going down) - skip this tick. + // Adapter going down or removed (the object is stale) - skip this tick and look it up again on the + // next one. The baseline is seeded again, so there is no speed spike. + _networkInterface = null; + _canUpdate = false; + return; } @@ -140,5 +148,11 @@ private void Update() byteReceivedSpeed, byteSentSpeed)); } + private static System.Net.NetworkInformation.NetworkInterface FindNetworkInterface(string id) + { + return System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() + .FirstOrDefault(x => x.Id == id); + } + #endregion } diff --git a/Source/NETworkManager.Models/Network/NetworkInterface.cs b/Source/NETworkManager.Models/Network/NetworkInterface.cs index 1c2072268c..2aced18d56 100644 --- a/Source/NETworkManager.Models/Network/NetworkInterface.cs +++ b/Source/NETworkManager.Models/Network/NetworkInterface.cs @@ -173,8 +173,6 @@ public static List GetNetworkInterfaces() } } - var dnsAutoconfigurationEnabled = IsDNSAutoconfigurationEnabled(networkInterface.Id) == true; - // Check if IPv4 protocol is available var ipv4ProtocolAvailable = true; IPv4InterfaceProperties ipv4Properties = null; @@ -188,6 +186,9 @@ public static List GetNetworkInterfaces() ipv4ProtocolAvailable = false; } + // Static DNS servers of IPv4, or of IPv6 if IPv4 is not available (e.g. IPv6 only) + var noStaticDNSServers = IsDNSAutoconfigurationEnabled(networkInterface.Id, ipv6: ipv4Properties == null); + // Check if IPv6 protocol is available var ipv6ProtocolAvailable = true; @@ -222,7 +223,7 @@ public static List GetNetworkInterfaces() IPv6AddressLinkLocal = [.. listIPv6AddressLinkLocal], IPv6Address = [.. listIPv6Address], IPv6Gateway = [.. listIPv6Gateway], - DNSAutoconfigurationEnabled = dnsAutoconfigurationEnabled, + DNSAutoconfigurationEnabled = IsDNSAutoconfigured(noStaticDNSServers, ipv4Properties?.IsDhcpEnabled), DNSSuffix = ipProperties.DnsSuffix, DNSServer = [.. ipProperties.DnsAddresses], Profile = profileByAlias.GetValueOrDefault(networkInterface.Name, NetworkProfile.NotConfigured) @@ -232,6 +233,34 @@ public static List GetNetworkInterfaces() return listNetworkInterfaceInfo; } + /// + /// Finds a network interface by its ID (GUID, unique per computer; the name is not). + /// + /// Network interfaces, see . + /// ID of the network interface. + /// The network interface, or if the ID is empty or not found. + public static NetworkInterfaceInfo FindById(IEnumerable networkInterfaces, string id) + { + return string.IsNullOrEmpty(id) ? null : networkInterfaces.FirstOrDefault(x => x.Id == id); + } + + /// + /// Gets the network interface to select after the list was (re)loaded: the remembered one (selected by the user, + /// also if it is back after it was missing, e.g. a VPN or USB adapter), then the one selected before the reload, + /// then the first one. + /// + /// Network interfaces, see . + /// ID of the preferred network interface (remembered in the settings, or selected by a + /// profile in this session). + /// ID of the network interface selected before the reload. + /// The network interface to select, or if the list is empty. + public static NetworkInterfaceInfo GetNetworkInterfaceToSelect( + IReadOnlyCollection networkInterfaces, string rememberedId, string previousId) + { + return FindById(networkInterfaces, rememberedId) ?? FindById(networkInterfaces, previousId) ?? + networkInterfaces.FirstOrDefault(); + } + /// /// Gets the IPv4 subnets of the operational network interfaces (e.g. to scan the subnet of a specific network /// interface), in the order of the network interfaces with the link-local subnet (169.254.0.0/16, no DHCP server @@ -456,23 +485,45 @@ public static Task ConfigureNetworkInterfaceAsync(NetworkInterfaceConfig config) /// gateway, and DNS server settings. Cannot be null. private static void ConfigureNetworkInterface(NetworkInterfaceConfig config) { - var name = PowerShellHelper.EscapeSingleQuotes(config.Name); - var commands = new List(); + ThrowIfInvalid(config); // netsh returns an error if DHCP is already enabled. Skip these commands, so every error can be reported. var (dhcpEnabled, dnsAutoconfigurationEnabled) = GetCurrentDhcpState(config.Name); - // IP + RunCommands(GetConfigureCommands(config, dhcpEnabled, dnsAutoconfigurationEnabled)); + } + + /// + /// Gets the netsh commands to apply the configuration to a network interface. Switching to DHCP is skipped + /// if DHCP is already enabled, because netsh returns an error in that case. + /// + /// Configuration to apply (values must be validated, see ). + /// Whether DHCP is currently enabled for the IP address ( if unknown). + /// Whether DHCP is currently enabled for the DNS servers ( if unknown). + /// Commands to run. + public static List GetConfigureCommands(NetworkInterfaceConfig config, bool? dhcpEnabled, + bool? dnsAutoconfigurationEnabled) + { + var name = PowerShellHelper.EscapeSingleQuotes(config.Name); + var commands = new List(); + + // IP (without gateway: "gateway=none", an empty value is a syntax error) if (config.EnableStaticIPAddress) - commands.Add($"& netsh interface ipv4 set address name='{name}' source=static address={config.IPAddress} mask={config.Subnetmask} gateway={config.Gateway}"); + { + var gateway = string.IsNullOrEmpty(config.Gateway) ? "none" : config.Gateway; + + commands.Add($"& netsh interface ipv4 set address name='{name}' source=static address={config.IPAddress} mask={config.Subnetmask} gateway={gateway}"); + } else if (dhcpEnabled != true) + { commands.Add($"& netsh interface ipv4 set address name='{name}' source=dhcp"); + } // DNS if (config.EnableStaticDNS) { commands.Add($"& netsh interface ipv4 set dnsservers name='{name}' source=static address={config.PrimaryDNSServer} register=primary validate=no"); - + if (!string.IsNullOrEmpty(config.SecondaryDNSServer)) commands.Add($"& netsh interface ipv4 add dnsservers name='{name}' address={config.SecondaryDNSServer} index=2 validate=no"); } @@ -481,7 +532,24 @@ private static void ConfigureNetworkInterface(NetworkInterfaceConfig config) commands.Add($"& netsh interface ipv4 set dnsservers name='{name}' source=dhcp"); } - RunCommands(commands); + return commands; + } + + /// + /// Whether the DNS servers of a network interface are obtained automatically (shown on the Information tab and + /// exported): no static DNS servers and DHCP enabled for the IPv4 address. With a static IP address, DNS servers can't + /// be obtained automatically (Windows dialog); without static DNS servers it has no DNS servers at all (the + /// "NameServer" value is empty in both cases). + /// + /// No static DNS servers are set (see ), + /// if unknown. + /// DHCP is enabled for the IPv4 address, if IPv4 is not available + /// (e.g. IPv6 only: then is about the IPv6 DNS servers, which are not affected + /// by a static IPv4 address). + /// if the DNS servers are obtained automatically. + public static bool IsDNSAutoconfigured(bool? noStaticDNSServers, bool? dhcpEnabled) + { + return noStaticDNSServers == true && dhcpEnabled != false; } /// @@ -489,15 +557,23 @@ private static void ConfigureNetworkInterface(NetworkInterfaceConfig config) /// detected via the registry: the "NameServer" value of the interface is empty, if no static DNS servers are set. /// /// ID (GUID) of the network interface. + /// Check the IPv6 DNS servers ("Tcpip6") instead of the IPv4 ones ("Tcpip"). /// Whether DNS autoconfiguration is enabled, or if it cannot be determined. - private static bool? IsDNSAutoconfigurationEnabled(string interfaceId) + private static bool? IsDNSAutoconfigurationEnabled(string interfaceId, bool ipv6 = false) { using var interfaceKey = Registry.LocalMachine.OpenSubKey( - $@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{interfaceId}"); + $@"SYSTEM\CurrentControlSet\Services\{(ipv6 ? "Tcpip6" : "Tcpip")}\Parameters\Interfaces\{interfaceId}"); - var nameServer = interfaceKey?.GetValue("NameServer"); + if (interfaceKey == null) + return null; - return nameServer == null ? null : string.IsNullOrEmpty(nameServer.ToString()); + var nameServer = interfaceKey.GetValue("NameServer"); + + // IPv6: the value may not exist if DNS servers were never set statically (IPv4 always has it) + if (nameServer == null) + return ipv6 ? true : null; + + return string.IsNullOrEmpty(nameServer.ToString()); } /// @@ -620,6 +696,8 @@ public static Task AddIPAddressToNetworkInterfaceAsync(NetworkInterfaceConfig co /// coexistence settings. Cannot be null. private static void AddIPAddressToNetworkInterface(NetworkInterfaceConfig config) { + ThrowIfInvalid(config); + var name = PowerShellHelper.EscapeSingleQuotes(config.Name); var commands = new List(); @@ -649,10 +727,30 @@ public static Task RemoveIPAddressFromNetworkInterfaceAsync(NetworkInterfaceConf /// null. private static void RemoveIPAddressFromNetworkInterface(NetworkInterfaceConfig config) { + ThrowIfInvalid(config); + var name = PowerShellHelper.EscapeSingleQuotes(config.Name); RunCommands([$"& netsh interface ipv4 delete address '{name}' {config.IPAddress}"]); } + /// + /// Throws if a value of the configuration is not a valid IPv4 address or subnet mask, so that nothing else (e.g. a + /// command from a manipulated profile file) can be inserted into the command line that runs elevated. + /// + /// Configuration to check. + /// If a value is invalid. + private static void ThrowIfInvalid(NetworkInterfaceConfig config) + { + var invalidValue = config.GetInvalidValue(); + + if (invalidValue == null) + return; + + throw new FormatException(invalidValue.Length == 0 + ? "A static IP address needs an IPv4 address and a subnet mask." + : $"\"{invalidValue}\" is not a valid IPv4 address or subnet mask."); + } + /// /// Runs one or more native commands (netsh, ipconfig) one after another via a PowerShell runspace. /// Stops at the first command that fails (non-zero exit code) and throws an exception with the output of the diff --git a/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs b/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs index 56d9fe29b5..8611cc6f74 100644 --- a/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs +++ b/Source/NETworkManager.Models/Network/NetworkInterfaceConfig.cs @@ -1,4 +1,6 @@ -namespace NETworkManager.Models.Network; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; public class NetworkInterfaceConfig { @@ -46,4 +48,106 @@ public class NetworkInterfaceConfig /// Secondary DNS server to use for the static DNS server configuration. /// public string SecondaryDNSServer { get; init; } -} \ No newline at end of file + + /// + /// Creates the configuration for a network interface from the values entered by the user (Configure tab or + /// profile). Values are trimmed, a subnet mask in CIDR notation (e.g. "/24" or "24") is converted to a subnet mask, static DNS servers + /// without any address fall back to DHCP and a secondary DNS server without a primary one becomes the primary. + /// + /// Name of the network interface. + /// Use a static IP address (otherwise DHCP). + /// Static IPv4 address. + /// Subnet mask (e.g. "255.255.255.0") or CIDR (e.g. "/24"). + /// Default gateway (optional). + /// Use static DNS servers (otherwise DHCP). + /// Primary DNS server. + /// Secondary DNS server. + /// Configuration to apply. + public static NetworkInterfaceConfig Create(string name, bool enableStaticIPAddress, string ipAddress, + string subnetmaskOrCidr, string gateway, bool enableStaticDNS, string primaryDNSServer, + string secondaryDNSServer) + { + // Values from the UI are validated with trimmed input (and profile values are trimmed when saved). + ipAddress = ipAddress?.Trim(); + gateway = gateway?.Trim(); + primaryDNSServer = primaryDNSServer?.Trim(); + secondaryDNSServer = secondaryDNSServer?.Trim(); + + var subnetmask = enableStaticIPAddress ? ConvertSubnetmaskOrCidr(subnetmaskOrCidr) : null; + + // DNS servers can only be obtained automatically with DHCP (older profiles may contain a static IP address + // with DHCP for the DNS servers, the UI selects static DNS servers in that case) + if (enableStaticIPAddress) + enableStaticDNS = true; + + // If primary and secondary DNS are empty --> autoconfiguration + if (enableStaticDNS && string.IsNullOrEmpty(primaryDNSServer) && string.IsNullOrEmpty(secondaryDNSServer)) + enableStaticDNS = false; + + // When primary DNS is empty, swap it with secondary (if not empty) + if (enableStaticDNS && string.IsNullOrEmpty(primaryDNSServer) && !string.IsNullOrEmpty(secondaryDNSServer)) + { + primaryDNSServer = secondaryDNSServer; + secondaryDNSServer = string.Empty; + } + + // Values of the option that is not used (e.g. a static IP address stored in a profile that uses DHCP) are not + // applied and not validated. + return new NetworkInterfaceConfig + { + Name = name, + EnableStaticIPAddress = enableStaticIPAddress, + IPAddress = enableStaticIPAddress ? ipAddress : null, + Subnetmask = enableStaticIPAddress ? subnetmask : null, + Gateway = enableStaticIPAddress ? gateway : null, + EnableStaticDNS = enableStaticDNS, + PrimaryDNSServer = enableStaticDNS ? primaryDNSServer : null, + SecondaryDNSServer = enableStaticDNS ? secondaryDNSServer : null + }; + } + + /// + /// Gets the first value that is not a valid IPv4 address (IP address, gateway, DNS servers) or subnet mask. + /// The values are inserted into a command line that runs elevated, so they must be checked again before they + /// are applied: profile files can be edited or shared without the validation of the UI. + /// + /// The invalid value ( if the IP address or subnet mask of a static IP + /// address is missing), or if all values are valid. + public string GetInvalidValue() + { + // Required for a static IP address (not checked by the UI for profiles from edited or shared files) + if (EnableStaticIPAddress && (string.IsNullOrEmpty(IPAddress) || string.IsNullOrEmpty(Subnetmask))) + return string.Empty; + + foreach (var value in new[] { IPAddress, Gateway, PrimaryDNSServer, SecondaryDNSServer }) + { + if (!string.IsNullOrEmpty(value) && !RegexHelper.IPv4AddressRegex().IsMatch(value)) + return value; + } + + if (!string.IsNullOrEmpty(Subnetmask) && !RegexHelper.SubnetmaskRegex().IsMatch(Subnetmask)) + return Subnetmask; + + return null; + } + + /// + /// Converts a subnet mask or CIDR as accepted by the IPv4SubnetmaskOrCIDRValidator (e.g. "255.255.255.0", + /// "/24" or "24") to a subnet mask, which is required by netsh. + /// + /// Subnet mask or CIDR. + /// Subnet mask, or the trimmed input if it is neither a subnet mask nor a CIDR. + public static string ConvertSubnetmaskOrCidr(string subnetmaskOrCidr) + { + var value = subnetmaskOrCidr?.Trim(); + + if (string.IsNullOrEmpty(value) || RegexHelper.SubnetmaskRegex().IsMatch(value)) + return value; + + // Not Subnetmask.ConvertSubnetmaskOrCidrToCidr: it throws for invalid input, which is reported by + // GetInvalidValue instead + return int.TryParse(value.TrimStart('/'), out var cidr) && cidr is >= 0 and <= 32 + ? Network.Subnetmask.ConvertCidrToSubnetmask(cidr) + : value; + } +} diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandDefinition.cs b/Source/NETworkManager.Models/RunCommand/RunCommandDefinition.cs index 04ab528256..bb7923614f 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandDefinition.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandDefinition.cs @@ -63,11 +63,11 @@ public sealed class RunCommandDefinition public IReadOnlyList SyntaxParts { get; init; } = []; /// - /// Syntax of the arguments (e.g. "<Hosts> [DNS server] [Type] | @<Profile>"), empty if there are - /// none. + /// Syntax of the arguments (e.g. "<Hosts> [DNS server] [Type] | @<Profile>", or + /// "[@<Profile>]" without a target), empty if there are none. /// public string Syntax => string.Join(" ", - SyntaxParts.Select(x => x.Kind == RunCommandSyntaxPartKind.Profile ? $"| {x.Text}" : x.Text)); + SyntaxParts.Select(x => x.Kind == RunCommandSyntaxPartKind.Profile && SupportsTarget ? $"| {x.Text}" : x.Text)); /// /// Checks if the text is the command or one of its aliases (case-insensitive). diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandParseError.cs b/Source/NETworkManager.Models/RunCommand/RunCommandParseError.cs index bac326a81b..fa498a43d0 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandParseError.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandParseError.cs @@ -11,5 +11,10 @@ public enum RunCommandParseError NoArguments, NoProfiles, MissingProfileName, - UnknownArgument + UnknownArgument, + + /// + /// A command without a target that accepts a profile (e.g. "networkinterface") got an argument without "@". + /// + OnlyProfile } diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandParseResult.cs b/Source/NETworkManager.Models/RunCommand/RunCommandParseResult.cs index d071d92cf6..bf56465854 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandParseResult.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandParseResult.cs @@ -89,7 +89,10 @@ public RunCommandSyntaxPartKind? CurrentSyntaxPart case RunCommandPosition.Type: return RunCommandSyntaxPartKind.Type; case RunCommandPosition.Target: - return RunCommandSyntaxPartKind.Target; + // Without a target, only a profile can follow the command (e.g. "networkinterface @home") + return Command.SupportsTarget || !Command.SupportsProfile + ? RunCommandSyntaxPartKind.Target + : RunCommandSyntaxPartKind.Profile; } // A complete type keyword is being typed (e.g. "aaaa"). diff --git a/Source/NETworkManager.Models/RunCommand/RunCommandParser.cs b/Source/NETworkManager.Models/RunCommand/RunCommandParser.cs index 9c0d9aa834..2e76e90010 100644 --- a/Source/NETworkManager.Models/RunCommand/RunCommandParser.cs +++ b/Source/NETworkManager.Models/RunCommand/RunCommandParser.cs @@ -143,7 +143,8 @@ public static RunCommandParseResult Parse(string input, IEnumerable"); } + + /// + /// Profile of a command without a target (e.g. "[@<Profile>]"): the profile is optional, the command + /// alone opens the application. + /// + /// Name of the part (e.g. "Profile"). + /// Part of the syntax. + public static RunCommandSyntaxPart OptionalProfile(string name) + { + return new RunCommandSyntaxPart(RunCommandSyntaxPartKind.Profile, name, $"[@<{name}>]"); + } } diff --git a/Source/NETworkManager.Profiles/ProfileInfo.cs b/Source/NETworkManager.Profiles/ProfileInfo.cs index 78966fad7c..eca7bbf3b3 100644 --- a/Source/NETworkManager.Profiles/ProfileInfo.cs +++ b/Source/NETworkManager.Profiles/ProfileInfo.cs @@ -46,6 +46,9 @@ public ProfileInfo(ProfileInfo profile) // Network Interface NetworkInterface_Enabled = profile.NetworkInterface_Enabled; + NetworkInterface_BindToInterface = profile.NetworkInterface_BindToInterface; + NetworkInterface_InterfaceId = profile.NetworkInterface_InterfaceId; + NetworkInterface_InterfaceName = profile.NetworkInterface_InterfaceName; NetworkInterface_EnableStaticIPAddress = profile.NetworkInterface_EnableStaticIPAddress; NetworkInterface_IPAddress = profile.NetworkInterface_IPAddress; NetworkInterface_Subnetmask = profile.NetworkInterface_Subnetmask; @@ -316,6 +319,24 @@ public ProfileInfo(ProfileInfo profile) public bool IsDynamic { get; set; } public bool NetworkInterface_Enabled { get; set; } + + /// + /// Apply the profile to the network interface instead of the one + /// selected in the Network Interface tool. + /// + public bool NetworkInterface_BindToInterface { get; set; } + + /// + /// ID (GUID) of the network interface the profile is bound to. Unique per computer. + /// + public string NetworkInterface_InterfaceId { get; set; } + + /// + /// Name of the network interface the profile is bound to (when it was selected), shown if the network interface + /// is not found on this computer. + /// + public string NetworkInterface_InterfaceName { get; set; } + public bool NetworkInterface_EnableStaticIPAddress { get; set; } public string NetworkInterface_IPAddress { get; set; } public string NetworkInterface_Subnetmask { get; set; } diff --git a/Source/NETworkManager.Profiles/ProfileManager.cs b/Source/NETworkManager.Profiles/ProfileManager.cs index c4bb3ad038..9fccaed8b8 100644 --- a/Source/NETworkManager.Profiles/ProfileManager.cs +++ b/Source/NETworkManager.Profiles/ProfileManager.cs @@ -6,6 +6,7 @@ using System.Collections.ObjectModel; using System.IO; using System.Linq; +using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Text.Json; @@ -1307,6 +1308,26 @@ public static void AddProfiles(IEnumerable profiles) ProfilesUpdated(); } + /// + /// Profiles replaced by (old -> new). Weak, so the old profiles are not kept alive. + /// + private static readonly ConditionalWeakTable ReplacedProfiles = new(); + + /// + /// Gets the current version of a profile: a profile is replaced by a new object when it is edited (see + /// ). Lists that select the previously selected profile again after the profiles + /// were updated use it, so the edited profile stays selected (instead of the first one). + /// + /// Profile, e.g. the one selected before the profiles were updated. + /// The profile that replaced it (also if it was edited several times), or the profile itself. + public static ProfileInfo GetCurrentProfile(ProfileInfo profile) + { + while (profile != null && ReplacedProfiles.TryGetValue(profile, out var newProfile)) + profile = newProfile; + + return profile; + } + /// /// Method to replace a profile in a group. /// @@ -1341,6 +1362,9 @@ public static void ReplaceProfile(ProfileInfo oldProfile, ProfileInfo newProfile newGroup.Profiles.Add(newProfile); + // Before the lists are updated (they select the edited profile again, see GetCurrentProfile) + ReplacedProfiles.AddOrUpdate(oldProfile, newProfile); + ProfilesUpdated(); } diff --git a/Source/NETworkManager.Tests/Network/NetworkInterfaceConfigTests.cs b/Source/NETworkManager.Tests/Network/NetworkInterfaceConfigTests.cs new file mode 100644 index 0000000000..62e86b0490 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/NetworkInterfaceConfigTests.cs @@ -0,0 +1,139 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class NetworkInterfaceConfigTests +{ + private static NetworkInterfaceConfig CreateStatic(string subnetmask = "255.255.255.0", bool enableStaticDNS = true, + string primaryDNSServer = "1.1.1.1", string secondaryDNSServer = "1.0.0.1") + { + return NetworkInterfaceConfig.Create("Ethernet", true, "192.168.1.10", subnetmask, "192.168.1.1", + enableStaticDNS, primaryDNSServer, secondaryDNSServer); + } + + [Fact] + public void Create_StaticValuesAreKept() + { + var config = CreateStatic(); + + Assert.Equal("Ethernet", config.Name); + Assert.True(config.EnableStaticIPAddress); + Assert.Equal("192.168.1.10", config.IPAddress); + Assert.Equal("255.255.255.0", config.Subnetmask); + Assert.Equal("192.168.1.1", config.Gateway); + Assert.True(config.EnableStaticDNS); + Assert.Equal("1.1.1.1", config.PrimaryDNSServer); + Assert.Equal("1.0.0.1", config.SecondaryDNSServer); + } + + [Theory] + [InlineData("/24", "255.255.255.0")] + [InlineData("/16", "255.255.0.0")] + [InlineData("/32", "255.255.255.255")] + [InlineData("24", "255.255.255.0")] + [InlineData(" 8 ", "255.0.0.0")] + [InlineData("255.255.252.0", "255.255.252.0")] + public void Create_CidrIsConvertedToSubnetmask(string cidr, string expected) + { + Assert.Equal(expected, CreateStatic(cidr).Subnetmask); + } + + [Fact] + public void Create_StaticDNSWithoutServers_FallsBackToDHCP() + { + var config = CreateStatic(primaryDNSServer: "", secondaryDNSServer: null); + + Assert.False(config.EnableStaticDNS); + } + + [Fact] + public void Create_OnlySecondaryDNSServer_BecomesPrimary() + { + var config = CreateStatic(primaryDNSServer: "", secondaryDNSServer: "8.8.8.8"); + + Assert.True(config.EnableStaticDNS); + Assert.Equal("8.8.8.8", config.PrimaryDNSServer); + Assert.Equal(string.Empty, config.SecondaryDNSServer); + } + + [Fact] + public void Create_DHCP_IgnoresEmptyStaticValues() + { + var config = NetworkInterfaceConfig.Create("Ethernet", false, null, null, null, false, null, null); + + Assert.False(config.EnableStaticIPAddress); + Assert.False(config.EnableStaticDNS); + } + + [Fact] + public void Create_ValuesAreTrimmed() + { + var config = NetworkInterfaceConfig.Create("Ethernet", true, " 192.168.1.10 ", " /24", "192.168.1.1 ", true, + " 1.1.1.1", "1.0.0.1 "); + + Assert.Equal("192.168.1.10", config.IPAddress); + Assert.Equal("255.255.255.0", config.Subnetmask); + Assert.Equal("192.168.1.1", config.Gateway); + Assert.Equal("1.1.1.1", config.PrimaryDNSServer); + Assert.Equal("1.0.0.1", config.SecondaryDNSServer); + } + + [Fact] + public void Create_UnusedValuesAreRemoved() + { + var config = NetworkInterfaceConfig.Create("Ethernet", false, "not used; Remove-Item", "/24", "x", false, + "y", "z"); + + Assert.Null(config.IPAddress); + Assert.Null(config.Subnetmask); + Assert.Null(config.Gateway); + Assert.Null(config.PrimaryDNSServer); + Assert.Null(config.SecondaryDNSServer); + Assert.Null(config.GetInvalidValue()); + } + + [Fact] + public void GetInvalidValue_ValidConfig_ReturnsNull() + { + Assert.Null(CreateStatic().GetInvalidValue()); + Assert.Null(CreateStatic(secondaryDNSServer: "").GetInvalidValue()); + } + + [Theory] + [InlineData("192.168.1.10; Remove-Item C:\\ -Recurse", "/24", "192.168.1.1", "1.1.1.1")] + [InlineData("192.168.1.10", "255.255.255.0 & calc", "192.168.1.1", "1.1.1.1")] + [InlineData("192.168.1.10", "/24", "192.168.1.1 | calc", "1.1.1.1")] + [InlineData("192.168.1.10", "/24", "192.168.1.1", "$(calc)")] + [InlineData("192.168.1.256", "/24", "", "")] + public void GetInvalidValue_ReturnsInvalidValue(string ipAddress, string subnetmask, string gateway, + string primaryDNSServer) + { + var config = NetworkInterfaceConfig.Create("Ethernet", true, ipAddress, subnetmask, gateway, true, + primaryDNSServer, ""); + + Assert.NotNull(config.GetInvalidValue()); + } + + [Fact] + public void Create_StaticIPWithDHCPDNS_UsesStaticDNSServers() + { + var config = NetworkInterfaceConfig.Create("Ethernet", true, "192.168.1.10", "/24", "192.168.1.1", false, + "1.1.1.1", "8.8.8.8"); + + Assert.True(config.EnableStaticDNS); + Assert.Equal("1.1.1.1", config.PrimaryDNSServer); + Assert.Equal("8.8.8.8", config.SecondaryDNSServer); + } + + [Theory] + [InlineData("", "/24")] + [InlineData("192.168.1.10", "")] + [InlineData(null, null)] + public void GetInvalidValue_StaticIPWithoutAddressOrSubnetmask_ReturnsEmpty(string ipAddress, string subnetmask) + { + var config = NetworkInterfaceConfig.Create("Ethernet", true, ipAddress, subnetmask, "", false, null, null); + + Assert.Equal(string.Empty, config.GetInvalidValue()); + } +} diff --git a/Source/NETworkManager.Tests/Network/NetworkInterfaceConfigureCommandsTests.cs b/Source/NETworkManager.Tests/Network/NetworkInterfaceConfigureCommandsTests.cs new file mode 100644 index 0000000000..17dcd6c850 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/NetworkInterfaceConfigureCommandsTests.cs @@ -0,0 +1,52 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class NetworkInterfaceConfigureCommandsTests +{ + [Fact] + public void StaticIPAndDNS() + { + var config = NetworkInterfaceConfig.Create("Ethernet", true, "192.168.1.10", "/24", "192.168.1.1", true, + "1.1.1.1", "1.0.0.1"); + + Assert.Equal([ + "& netsh interface ipv4 set address name='Ethernet' source=static address=192.168.1.10 mask=255.255.255.0 gateway=192.168.1.1", + "& netsh interface ipv4 set dnsservers name='Ethernet' source=static address=1.1.1.1 register=primary validate=no", + "& netsh interface ipv4 add dnsservers name='Ethernet' address=1.0.0.1 index=2 validate=no" + ], NetworkInterface.GetConfigureCommands(config, true, true)); + } + + [Fact] + public void StaticIPWithoutGateway_UsesGatewayNone() + { + var config = NetworkInterfaceConfig.Create("Ethernet", true, "10.0.0.5", "255.0.0.0", "", true, "10.0.0.1", + ""); + + Assert.Equal( + "& netsh interface ipv4 set address name='Ethernet' source=static address=10.0.0.5 mask=255.0.0.0 gateway=none", + NetworkInterface.GetConfigureCommands(config, false, false)[0]); + } + + [Fact] + public void DHCP_SkippedIfAlreadyEnabled() + { + var config = NetworkInterfaceConfig.Create("Ethernet", false, null, null, null, false, null, null); + + Assert.Empty(NetworkInterface.GetConfigureCommands(config, true, true)); + Assert.Equal([ + "& netsh interface ipv4 set address name='Ethernet' source=dhcp", + "& netsh interface ipv4 set dnsservers name='Ethernet' source=dhcp" + ], NetworkInterface.GetConfigureCommands(config, null, false)); + } + + [Fact] + public void NameIsEscaped() + { + var config = NetworkInterfaceConfig.Create("John's LAN", false, null, null, null, false, null, null); + + Assert.Equal("& netsh interface ipv4 set address name='John''s LAN' source=dhcp", + NetworkInterface.GetConfigureCommands(config, false, true)[0]); + } +} diff --git a/Source/NETworkManager.Tests/Network/NetworkInterfaceDNSAutoconfigurationTests.cs b/Source/NETworkManager.Tests/Network/NetworkInterfaceDNSAutoconfigurationTests.cs new file mode 100644 index 0000000000..1754bcf0bc --- /dev/null +++ b/Source/NETworkManager.Tests/Network/NetworkInterfaceDNSAutoconfigurationTests.cs @@ -0,0 +1,26 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class NetworkInterfaceDNSAutoconfigurationTests +{ + [Theory] + // DHCP, no static DNS servers: obtained automatically + [InlineData(true, true, true)] + // DHCP with static DNS servers + [InlineData(false, true, false)] + // Static IP address without DNS servers ("NameServer" is empty, but nothing is obtained automatically) + [InlineData(true, false, false)] + // Static IP address and static DNS servers + [InlineData(false, false, false)] + // Registry value not readable + [InlineData(null, true, false)] + // IPv4 not available (e.g. IPv6 only): only the static DNS servers count + [InlineData(true, null, true)] + [InlineData(false, null, false)] + public void IsDNSAutoconfigured(bool? noStaticDNSServers, bool? dhcpEnabled, bool expected) + { + Assert.Equal(expected, NetworkInterface.IsDNSAutoconfigured(noStaticDNSServers, dhcpEnabled)); + } +} diff --git a/Source/NETworkManager.Tests/Network/NetworkInterfaceSelectionTests.cs b/Source/NETworkManager.Tests/Network/NetworkInterfaceSelectionTests.cs new file mode 100644 index 0000000000..85e781cacc --- /dev/null +++ b/Source/NETworkManager.Tests/Network/NetworkInterfaceSelectionTests.cs @@ -0,0 +1,57 @@ +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class NetworkInterfaceSelectionTests +{ + private static readonly NetworkInterfaceInfo Ethernet = new() { Id = "{A}", Name = "Ethernet" }; + private static readonly NetworkInterfaceInfo WiFi = new() { Id = "{B}", Name = "Wi-Fi" }; + private static readonly NetworkInterfaceInfo Vpn = new() { Id = "{C}", Name = "VPN" }; + + private static readonly NetworkInterfaceInfo[] All = [Ethernet, WiFi, Vpn]; + + [Theory] + [InlineData("{B}", "Wi-Fi")] + [InlineData("{X}", null)] + [InlineData("", null)] + [InlineData(null, null)] + public void FindById(string id, string expectedName) + { + Assert.Equal(expectedName, NetworkInterface.FindById(All, id)?.Name); + } + + [Fact] + public void GetNetworkInterfaceToSelect_RememberedFirst() + { + Assert.Same(Vpn, NetworkInterface.GetNetworkInterfaceToSelect(All, "{C}", "{B}")); + } + + [Fact] + public void GetNetworkInterfaceToSelect_RememberedMissing_PreviousSelection() + { + // e.g. the remembered VPN adapter is disconnected: the fallback selected before stays selected + Assert.Same(WiFi, NetworkInterface.GetNetworkInterfaceToSelect([Ethernet, WiFi], "{C}", "{B}")); + } + + [Fact] + public void GetNetworkInterfaceToSelect_RememberedIsBack() + { + // The remembered adapter replaces the fallback when it is back (the fallback is not remembered) + Assert.Same(Vpn, NetworkInterface.GetNetworkInterfaceToSelect(All, "{C}", "{A}")); + } + + [Theory] + [InlineData("{X}", "{Y}")] + [InlineData(null, null)] + public void GetNetworkInterfaceToSelect_NothingKnown_First(string rememberedId, string previousId) + { + Assert.Same(Ethernet, NetworkInterface.GetNetworkInterfaceToSelect(All, rememberedId, previousId)); + } + + [Fact] + public void GetNetworkInterfaceToSelect_Empty() + { + Assert.Null(NetworkInterface.GetNetworkInterfaceToSelect([], "{A}", "{A}")); + } +} diff --git a/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs b/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs index a636e37b29..d5abed0059 100644 --- a/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs +++ b/Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs @@ -48,6 +48,13 @@ public class RunCommandParserTests SupportsTarget = true, Types = ["oui", "port"], TypeBeforeTarget = true }, new() { Type = RunCommandType.Application, Application = ApplicationName.Firewall, Command = "firewall" }, + // No target, but a profile (optional) + new() + { + Type = RunCommandType.Application, Application = ApplicationName.NetworkInterface, + Command = "networkinterface", SupportsProfile = true, + SyntaxParts = [RunCommandSyntaxPart.OptionalProfile("Profile")] + }, new() { Type = RunCommandType.Setting, Command = "settings" } ]; @@ -474,6 +481,41 @@ public void Syntax() Assert.Equal(" [DNS server] [Type] | @", result.Command.Syntax); } + [Fact] + public void SyntaxProfileWithoutTarget() + { + Assert.Equal("[@]", Parse("networkinterface ").Command.Syntax); + } + + [Theory] + [InlineData("networkinterface @home", "home")] + [InlineData("networkinterface @Home Office", "Home Office")] + public void ProfileWithoutTarget(string input, string profileName) + { + var result = Parse(input); + + Assert.Equal(RunCommandParseError.None, result.Error); + Assert.Equal(profileName, result.ProfileName); + Assert.Null(result.Target); + } + + [Theory] + [InlineData("networkinterface home")] + [InlineData("networkinterface 10.0.0.1 ")] + public void ProfileWithoutTargetNeedsAt(string input) + { + var result = Parse(input); + + Assert.Equal(RunCommandParseError.OnlyProfile, result.Error); + Assert.Equal("networkinterface", result.ErrorValue); + } + + [Fact] + public void ProfileWithoutTargetNotSupported() + { + Assert.Equal(RunCommandParseError.NoProfiles, Parse("firewall @home").Error); + } + [Theory] [InlineData("dns", null)] [InlineData("dns ", RunCommandSyntaxPartKind.Target)] @@ -492,6 +534,8 @@ public void Syntax() [InlineData("lookup ", RunCommandSyntaxPartKind.Type)] [InlineData("lookup port 2", RunCommandSyntaxPartKind.Target)] [InlineData("portscan 10.0.0.1 ", RunCommandSyntaxPartKind.Argument)] + [InlineData("networkinterface ", RunCommandSyntaxPartKind.Profile)] + [InlineData("networkinterface @ho", RunCommandSyntaxPartKind.Profile)] public void CurrentSyntaxPart(string input, RunCommandSyntaxPartKind? part) { Assert.Equal(part, Parse(input).CurrentSyntaxPart); diff --git a/Source/NETworkManager/ProfileDialogManager.cs b/Source/NETworkManager/ProfileDialogManager.cs index 57711b9d20..eefaa6d701 100644 --- a/Source/NETworkManager/ProfileDialogManager.cs +++ b/Source/NETworkManager/ProfileDialogManager.cs @@ -41,6 +41,13 @@ private static ProfileInfo ParseProfileInfo(ProfileViewModel instance) // Network Interface NetworkInterface_Enabled = instance.NetworkInterface_Enabled, + NetworkInterface_BindToInterface = instance.NetworkInterface_BindToInterface, + NetworkInterface_InterfaceId = instance.NetworkInterface_BindToInterface + ? instance.NetworkInterface_BoundInterfaceId + : null, + NetworkInterface_InterfaceName = instance.NetworkInterface_BindToInterface + ? instance.NetworkInterface_BoundInterfaceName + : null, NetworkInterface_EnableStaticIPAddress = instance.NetworkInterface_EnableStaticIPAddress, NetworkInterface_IPAddress = instance.NetworkInterface_IPAddress?.Trim(), NetworkInterface_Gateway = instance.NetworkInterface_Gateway?.Trim(), diff --git a/Source/NETworkManager/RunCommandManager.cs b/Source/NETworkManager/RunCommandManager.cs index 6c67912b8b..6373ec35f5 100644 --- a/Source/NETworkManager/RunCommandManager.cs +++ b/Source/NETworkManager/RunCommandManager.cs @@ -301,6 +301,7 @@ private static string GetParseErrorMessage(RunCommandParseResult result) RunCommandParseError.NoProfiles => string.Format(Strings.CommandXDoesNotSupportProfiles, result.ErrorValue), RunCommandParseError.MissingProfileName => Strings.EnterTheNameOfAProfileAfterAt, RunCommandParseError.UnknownArgument => string.Format(Strings.UnknownArgumentX, result.ErrorValue), + RunCommandParseError.OnlyProfile => string.Format(Strings.CommandXOnlyAcceptsAProfile, result.ErrorValue), _ => throw new ArgumentOutOfRangeException(nameof(result), result.Error, null) }; } @@ -513,6 +514,8 @@ [.. DNSLookup.QueryTypes.Select(x => x.ToString().ToLowerInvariant()).Order()]), ApplicationName.RDAP => Create(name, [], [Target(Strings.Query), type], types: [.. RDAPTypes.Keys]), ApplicationName.Whois => Create(name, [], [Target(Strings.Domain)]), ApplicationName.IPGeolocation => Create(name, ["geo"], [Target(Strings.Host)]), + // No target, but profiles: selects the profile and fills in its values (never applied, see the view model) + ApplicationName.NetworkInterface => Create(name, [], null, supportsProfile: true), ApplicationName.LLDPCDPCapture => Create(name, ["lldp", "cdp"], null), ApplicationName.MDNSDiscovery => Create(name, ["mdns", "dnssd"], [Target(Strings.MDNSDiscovery_ServiceType), Argument(Strings.DurationS)], RunCommandArgument.Duration, @@ -549,16 +552,17 @@ [.. DNSLookup.QueryTypes.Select(x => x.ToString().ToLowerInvariant()).Order()]), /// Syntax of the arguments, or null if the command accepts no target. /// Second argument after the target. /// Type keywords. - /// The application has profiles (only with a target). + /// The application has profiles (default: if it accepts a target). /// The type keyword comes before the target. private static RunCommandDefinition Create(ApplicationName application, string[] aliases, RunCommandSyntaxPart[] syntaxParts, RunCommandArgument argument = RunCommandArgument.None, - string[] types = null, bool supportsProfile = true, bool typeBeforeTarget = false) + string[] types = null, bool? supportsProfile = null, bool typeBeforeTarget = false) { var supportsTarget = syntaxParts != null; - // Applications that accept a target support profiles, unless they have none (e.g. Subnet Calculator). - supportsProfile &= supportsTarget; + // Applications that accept a target support profiles, unless they have none (e.g. Subnet Calculator). Without + // a target only if set (Network Interface: the profile is optional). + var profile = supportsProfile ?? supportsTarget; return new RunCommandDefinition { @@ -567,12 +571,14 @@ private static RunCommandDefinition Create(ApplicationName application, string[] Command = application.ToString().ToLowerInvariant(), Aliases = aliases, SupportsTarget = supportsTarget, - SupportsProfile = supportsProfile, + SupportsProfile = profile, Argument = argument, Types = types ?? [], TypeBeforeTarget = typeBeforeTarget, - SyntaxParts = supportsProfile - ? [.. syntaxParts, RunCommandSyntaxPart.Profile(Strings.Profile)] + SyntaxParts = profile + ? supportsTarget + ? [.. syntaxParts, RunCommandSyntaxPart.Profile(Strings.Profile)] + : [RunCommandSyntaxPart.OptionalProfile(Strings.Profile)] : syntaxParts ?? [] }; } diff --git a/Source/NETworkManager/ScreenshotData.cs b/Source/NETworkManager/ScreenshotData.cs index 5558271cb0..9c3790e9cd 100644 --- a/Source/NETworkManager/ScreenshotData.cs +++ b/Source/NETworkManager/ScreenshotData.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using System.Net.NetworkInformation; using NETworkManager.Models.Cloudflare; using NETworkManager.Models.IPApi; using NETworkManager.Models.Network; @@ -105,6 +106,104 @@ public static IPGeolocationResult CreateIPGeolocationResult() #endregion + #region Network Interface + + /// + /// Creates the network adapters of the Network Interface tool (instead of the real adapters): a connected Ethernet + /// adapter (the computer in the home network, DHCP) and a disconnected Wi-Fi adapter. The MAC addresses are locally + /// administered (02-...), so they don't belong to a real vendor. + /// + public static List CreateNetworkInterfaces() + { + var now = DateTime.Now; + + return + [ + new NetworkInterfaceInfo + { + Id = "{6F1C2D3E-0000-4000-8000-000000000001}", + Name = "Ethernet", + Description = "Example Gigabit Network Connection", + Type = "Ethernet", + PhysicalAddress = PhysicalAddress.Parse("02-00-5E-10-00-0A"), + Status = OperationalStatus.Up, + IsOperational = true, + Speed = 1_000_000_000, + IPv4ProtocolAvailable = true, + IPv4Address = + [ + new Tuple(IPAddress.Parse(ComputerIPv4), IPAddress.Parse("255.255.255.0")) + ], + IPv4Gateway = [IPAddress.Parse(RouterIPv4)], + DhcpEnabled = true, + DhcpServer = [IPAddress.Parse(RouterIPv4)], + DhcpLeaseObtained = now.AddHours(-2), + DhcpLeaseExpires = now.AddHours(22), + IPv6ProtocolAvailable = true, + IPv6Address = [IPAddress.Parse(ComputerIPv6)], + IPv6AddressLinkLocal = [IPAddress.Parse("fe80::10")], + IPv6Gateway = [IPAddress.Parse(RouterIPv6)], + DNSAutoconfigurationEnabled = true, + DNSSuffix = "home.arpa", + DNSServer = [IPAddress.Parse(RouterIPv4)], + Profile = NetworkProfile.Private + }, + new NetworkInterfaceInfo + { + Id = "{6F1C2D3E-0000-4000-8000-000000000002}", + Name = "Wi-Fi", + Description = "Example Wi-Fi 6 Wireless Adapter", + Type = "Wireless80211", + PhysicalAddress = PhysicalAddress.Parse("02-00-5E-10-00-0B"), + Status = OperationalStatus.Down, + IsOperational = false, + Speed = -1, + IPv4ProtocolAvailable = true, + IPv4Address = [], + IPv4Gateway = [], + DhcpEnabled = true, + DhcpServer = [], + IPv6ProtocolAvailable = true, + IPv6Address = [], + IPv6AddressLinkLocal = [], + IPv6Gateway = [], + DNSAutoconfigurationEnabled = true, + DNSServer = [] + } + ]; + } + + /// + /// Creates the samples of the bandwidth chart (one per second, ending now): a download with a short peak and a + /// smaller upload, so the chart is filled without a measurement. + /// + /// Number of samples (seconds). + public static List CreateBandwidthSamples(int count) + { + var start = DateTime.Now.AddSeconds(-count); + var samples = new List(); + + long totalReceived = 48_213_557_120; // ~48 GB since boot + long totalSent = 6_902_114_304; + + for (var i = 0; i < count; i++) + { + // Bytes per second: ~3-6 MB/s download with a peak in the middle, ~0.3-0.6 MB/s upload + var peak = Math.Exp(-Math.Pow((i - count * 0.6) / (count * 0.08), 2)); + var received = (long)(4_000_000 + 1_500_000 * Math.Sin(i / 4.0) + 9_000_000 * peak); + var sent = (long)(450_000 + 150_000 * Math.Cos(i / 3.0) + 900_000 * peak); + + totalReceived += received; + totalSent += sent; + + samples.Add(new BandwidthMeterSpeedArgs(start.AddSeconds(i), totalReceived, totalSent, received, sent)); + } + + return samples; + } + + #endregion + #region LLDP / CDP Capture /// diff --git a/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs b/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs index 13119109b1..b278bad023 100644 --- a/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs +++ b/Source/NETworkManager/ViewModels/NetworkInterfaceViewModel.cs @@ -40,7 +40,18 @@ public class NetworkInterfaceViewModel : ProfileHostViewModelBase private BandwidthMeter _bandwidthMeter; - private readonly bool _isLoading; + /// + /// The network interface is selected by the (re)load of the network interfaces, not by the user: the selection is + /// not saved, so a fallback (e.g. while a VPN or USB adapter is missing) doesn't replace the remembered one. + /// + private bool _isSelectingNetworkInterfaceByCode; + + /// + /// The network interface to select after a reload (also if it is back after it was missing). Selected by the user + /// (saved in the settings), by a profile (only for this session: looking at a profile doesn't change the network + /// interface shown after a restart) or configured. + /// + private string _preferredNetworkInterfaceId = SettingsManager.Current.NetworkInterface_InterfaceId; /// /// Gets or sets a value indicating whether network interfaces are currently loading. @@ -62,7 +73,10 @@ public bool IsNetworkInterfaceLoading /// Gets a value indicating whether the application has the permission to change the network configuration /// (running as administrator or as member of the "Network Configuration Operators" group). /// - public bool HasPermissionToConfigure { get; } = NetworkInterface.HasPermissionToConfigure(); + /// Always in the screenshot mode (): nothing is changed there, see + /// . + public bool HasPermissionToConfigure { get; } = + NetworkInterface.HasPermissionToConfigure() || ScreenshotData.IsEnabled; /// /// Gets or sets a value indicating whether configuration is allowed. @@ -162,6 +176,11 @@ private set } } = []; + /// + /// ID of the interface the bandwidth meter and the configuration were set up for. + /// + private string _selectedNetworkInterfaceId; + /// /// Gets or sets the currently selected network interface. /// @@ -173,21 +192,31 @@ public NetworkInterfaceInfo SelectedNetworkInterface if (value == field) return; - if (value != null) + // A reload creates new objects for the same interfaces (and the ComboBox selects null while the list is + // replaced). Only start a new measurement and reset the configuration if another interface is selected, + // not when the selected one is reloaded (e.g. after a network change or Apply). + if (value != null && value.Id != _selectedNetworkInterfaceId) { - if (!_isLoading) - SettingsManager.Current.NetworkInterface_InterfaceId = value.Id; + _selectedNetworkInterfaceId = value.Id; + + if (!_isSelectingNetworkInterfaceByCode) + { + RememberNetworkInterface(value); + + // Selected by the user while the network interfaces were loaded: a profile selected before must + // not switch the network interface back after the load + _pendingProfile = null; + } // Bandwidth - StopBandwidthMeter(); StartBandwidthMeter(value.Id); // Configuration SetConfigurationDefaults(value); - - CanConfigure = value.IsOperational; } + CanConfigure = value?.IsOperational == true; + field = value; OnPropertyChanged(); } @@ -360,7 +389,12 @@ public bool ConfigEnableStaticIPAddress if (value == field) return; - ConfigEnableStaticDNS = true; + // DNS servers can only be obtained automatically with DHCP (same as the Windows dialog) + if (value) + { + ConfigEnableDynamicDNS = false; + ConfigEnableStaticDNS = true; + } field = value; OnPropertyChanged(); @@ -482,7 +516,8 @@ public string ConfigSecondaryDNSServer #endregion /// - /// Gets or sets the selected profile. Pre-fills the Config* fields from the profile. + /// Gets or sets the selected profile. Selecting a profile selects the network interface it is bound to and fills + /// in its values on the Configure tab. /// public override ProfileInfo SelectedProfile { @@ -492,18 +527,16 @@ public override ProfileInfo SelectedProfile if (value == base.SelectedProfile) return; - if (value != null) - { - ConfigEnableDynamicIPAddress = !value.NetworkInterface_EnableStaticIPAddress; - ConfigEnableStaticIPAddress = value.NetworkInterface_EnableStaticIPAddress; - ConfigIPAddress = value.NetworkInterface_IPAddress; - ConfigGateway = value.NetworkInterface_Gateway; - ConfigSubnetmask = value.NetworkInterface_Subnetmask; - ConfigEnableDynamicDNS = !value.NetworkInterface_EnableStaticDNS; - ConfigEnableStaticDNS = value.NetworkInterface_EnableStaticDNS; - ConfigPrimaryDNSServer = value.NetworkInterface_PrimaryDNSServer; - ConfigSecondaryDNSServer = value.NetworkInterface_SecondaryDNSServer; - } + // Another profile (or none) selected by the user: a profile that waits for the load is not loaded + if (!IsProfileSelectedByCode) + _pendingProfile = null; + + // Only if the user selects the profile. The profile list is rebuilt (and the previous or the first profile + // selected again) when the view becomes visible, on search / filter and when a profile changes: this + // must not overwrite the values entered on the Configure tab or switch the network interface. + // Not while a configuration is applied (like Reset): the result would be shown for another interface + if (value != null && !IsProfileSelectedByCode && !IsConfigurationRunning) + LoadProfileAfterLoad(value); base.SelectedProfile = value; } @@ -518,8 +551,6 @@ public override ProfileInfo SelectedProfile /// public NetworkInterfaceViewModel() { - _isLoading = true; - // Initialize the bandwidth chart before loading interfaces, so the chart collections // exist by the time the (possibly synchronous) interface load selects an interface and // starts the bandwidth meter. @@ -529,17 +560,17 @@ public NetworkInterfaceViewModel() InitializeProfileHost(); - // Detect if network address or status changed... - NetworkChange.NetworkAvailabilityChanged += (_, _) => ReloadNetworkInterfaces(); - NetworkChange.NetworkAddressChanged += (_, _) => ReloadNetworkInterfaces(); + // Detect if network address or status changed... The events are raised on a thread pool thread: reload on the + // UI thread, otherwise the bandwidth meter (DispatcherTimer) of the selected interface is created on a thread + // without a running dispatcher and never updates. + NetworkChange.NetworkAvailabilityChanged += (_, _) => ReloadNetworkInterfacesOnUIThread(); + NetworkChange.NetworkAddressChanged += (_, _) => ReloadNetworkInterfacesOnUIThread(); // React to settings changes (e.g. the configurable bandwidth chart time window) SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; // Colors of the bandwidth chart for the new theme (the paints don't follow the theme) AppearanceManager.ThemeResourcesChanged += (_, _) => ApplyBandwidthChartColors(); - - _isLoading = false; } /// @@ -746,27 +777,105 @@ private async Task LoadNetworkInterfaces() { IsNetworkInterfaceLoading = true; - // Get all network interfaces... - (await NetworkInterface.GetNetworkInterfacesAsync()).ForEach(NetworkInterfaces.Add); - - // Get the last selected interface, if it is still available on this machine... - if (NetworkInterfaces.Count > 0) + try { - var info = NetworkInterfaces.FirstOrDefault(s => - s.Id == SettingsManager.Current.NetworkInterface_InterfaceId); + // Get all network interfaces... + (await GetNetworkInterfacesAsync()).ForEach(NetworkInterfaces.Add); - SelectedNetworkInterface = info ?? NetworkInterfaces[0]; + // Get the last selected interface, if it is still available on this machine... + SelectNetworkInterfaceAfterLoad(null); + } + catch (Exception ex) + { + Log.Error("Error while loading the network interfaces.", ex); + } + finally + { + IsNetworkInterfaceLoading = false; } - IsNetworkInterfaceLoading = false; + LoadPendingProfile(); + ReloadIfPending(); } #endregion #region Profile host + /// + /// Profile to load after the network interfaces are (re)loaded (see ). + /// + private ProfileInfo _pendingProfile; + + /// + /// Loads a profile (selects its bound network interface and fills in its values). While the network interfaces are + /// (re)loaded, it is loaded afterwards: the first load (e.g. the run command opened the tool, the view model was + /// created right before) has no network interfaces yet, and a reload (e.g. a VPN or USB adapter was connected / + /// removed) can add or remove the bound network interface or select another one, which would replace the values. + /// Any change of the profile selection by the user drops it; configuration actions (and Reset) are disabled while + /// the network interfaces are loaded, so they can't be overridden by it. + /// + private void LoadProfileAfterLoad(ProfileInfo profile) + { + if (IsNetworkInterfaceLoading) + { + _pendingProfile = profile; + return; + } + + _pendingProfile = null; + + LoadProfile(profile); + } + + private void LoadPendingProfile() + { + var profile = _pendingProfile; + _pendingProfile = null; + + // Not if a configuration was started meanwhile (like selecting a profile) or if the profile was changed or + // deleted meanwhile (changed profiles are new objects): the old values would be filled in + if (profile == null || IsConfigurationRunning || + ProfileManager.LoadedProfileFileData?.Groups.Any(x => x.Profiles.Contains(profile)) != true) + return; + + LoadProfile(profile); + } + protected override ApplicationName ApplicationName => ApplicationName.NetworkInterface; + /// + /// Opens a request of the run command (e.g. "networkinterface @home"): selects the profile and fills in its values + /// like a double-click on the profile. The profile is never applied (also not with Enter): the configuration is + /// changed with elevated rights and can disconnect the computer, it is applied with Apply after checking the values. + /// + /// Request with the profile (a request without a profile only opens the tool). + public void Open(ApplicationRequest request) + { + if (request.Profile == null) + return; + + // Not while a configuration is applied (like selecting / double-clicking a profile: the result would be shown + // for another network interface). The run command dialog is closed already, and a status message would be + // replaced by the result of the configuration: a message dialog says why nothing happens. + if (IsConfigurationRunning) + { + _ = DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.NetworkInterface, + string.Format(Strings.ProfileXNotLoadedConfigurationRunning, request.Profile.Name), + ChildWindowIcon.Info); + return; + } + + // Select it in the profile list if it is shown (not hidden by the search / filter): selecting loads it + if (Profiles.Contains(request.Profile) && !Equals(SelectedProfile, request.Profile)) + { + SelectedProfile = request.Profile; + return; + } + + LoadProfileAfterLoad(request.Profile); + } + #endregion #region ICommands & Actions @@ -850,7 +959,7 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Erro /// Gets the command to apply the network configuration. /// public ICommand ApplyConfigurationCommand => - new RelayCommand(_ => ApplyConfigurationAction(), ConfigureCommands_CanExecute); + new RelayCommand(_ => ApplyConfigurationAction(), ApplyConfiguration_CanExecute); /// /// Action to apply the network configuration. @@ -860,16 +969,79 @@ private void ApplyConfigurationAction() _ = ApplyConfiguration(); } + /// + /// Gets the command to load the selected profile again (double-click / Enter in the profile list): selects its + /// network interface and fills in its values, e.g. after Reset or if the profile was selected automatically + /// (clicking the selected profile doesn't change the selection). + /// + public ICommand LoadProfileCommand => + new RelayCommand(_ => LoadProfileAfterLoad(SelectedProfile), LoadProfile_CanExecute); + + private bool LoadProfile_CanExecute(object parameter) => SelectedProfile != null && !IsConfigurationRunning; + /// /// Gets the command to apply the profile configuration. /// - public ICommand ApplyProfileCommand => new RelayCommand(_ => ApplyProfileAction(), ConfigureCommands_CanExecute); + public ICommand ApplyProfileCommand => new RelayCommand(_ => ApplyProfileAction(), ApplyProfile_CanExecute); private void ApplyProfileAction() { _ = ApplyConfigurationFromProfile(); } + /// + /// Gets the command to reset the Configure tab to the current configuration of the selected network interface + /// (e.g. after a profile was selected or values were changed). + /// + public ICommand ResetConfigurationCommand => new RelayCommand(_ => ResetConfigurationAction(), + ResetConfiguration_CanExecute); + + private bool ResetConfiguration_CanExecute(object parameter) => + SelectedNetworkInterface != null && !IsConfigurationRunning && !IsNetworkInterfaceLoading; + + private void ResetConfigurationAction() + { + SetConfigurationDefaults(SelectedNetworkInterface); + } + + /// + /// Gets the command to add a profile with the configuration of the Configure tab, bound to the selected network + /// interface. + /// + public ICommand AddProfileFromConfigurationCommand => new RelayCommand(_ => AddProfileFromConfigurationAction(), + AddProfileFromConfiguration_CanExecute); + + private bool AddProfileFromConfiguration_CanExecute(object parameter) => + AdditionalCommands_CanExecute(parameter) && SelectedNetworkInterface != null; + + private void AddProfileFromConfigurationAction() + { + var networkInterface = SelectedNetworkInterface; + + ProfileInfo profileInfo = new() + { + Name = networkInterface.Name, + // Required by the profile, not used by the Network Interface + Host = ConfigEnableStaticIPAddress + ? ConfigIPAddress?.Trim() + : networkInterface.IPv4Address?.FirstOrDefault()?.Item1.ToString(), + + NetworkInterface_BindToInterface = true, + NetworkInterface_InterfaceId = networkInterface.Id, + NetworkInterface_InterfaceName = networkInterface.Name, + NetworkInterface_EnableStaticIPAddress = ConfigEnableStaticIPAddress, + NetworkInterface_IPAddress = ConfigIPAddress, + NetworkInterface_Subnetmask = ConfigSubnetmask, + NetworkInterface_Gateway = ConfigGateway, + NetworkInterface_EnableStaticDNS = ConfigEnableStaticDNS, + NetworkInterface_PrimaryDNSServer = ConfigPrimaryDNSServer, + NetworkInterface_SecondaryDNSServer = ConfigSecondaryDNSServer + }; + + _ = ProfileDialogManager.ShowAddProfileDialog(Application.Current.MainWindow, this, profileInfo, null, + ApplicationName.NetworkInterface); + } + #region Additional commands private bool AdditionalCommands_CanExecute(object parameter) @@ -877,9 +1049,36 @@ private bool AdditionalCommands_CanExecute(object parameter) return !DialogHelper.IsAnyDialogOpen(); } + /// + /// Configuration actions that don't need a network interface (e.g. flush DNS cache). Only one runs at a time, not + /// while the network interfaces are (re)loaded (like modify vs. refresh in the other tools: a profile selected + /// meanwhile is loaded after the load, see LoadProfileAfterLoad, and would hide the result / switch the adapter). + /// private bool ConfigureCommands_CanExecute(object parameter) => HasPermissionToConfigure && + !IsConfigurationRunning && + !IsNetworkInterfaceLoading && !DialogHelper.IsAnyDialogOpen(); + /// + /// Configuration actions on the selected network interface (release/renew, add/remove IP address). + /// + private bool ConfigureNetworkInterface_CanExecute(object parameter) => + ConfigureCommands_CanExecute(parameter) && SelectedNetworkInterface != null; + + /// + /// Apply the configuration (Configure tab): the network interface must be connected. + /// + private bool ApplyConfiguration_CanExecute(object parameter) => + ConfigureCommands_CanExecute(parameter) && CanConfigure; + + /// + /// Apply the selected profile (profile context menu): same conditions as the Apply button. A profile bound to a + /// network interface doesn't depend on the selected one (checked when it is applied). + /// + private bool ApplyProfile_CanExecute(object parameter) => + ConfigureCommands_CanExecute(parameter) && SelectedProfile != null && + (IsBoundToNetworkInterface(SelectedProfile) || CanConfigure); + /// /// Gets the command to restart the application with administrator privileges. /// @@ -912,13 +1111,21 @@ private void OpenNetworkConnectionsAction() /// /// Gets the command to open IP Scanner. /// - public ICommand IPScannerCommand => new RelayCommand(_ => IPScannerAction(), AdditionalCommands_CanExecute); + public ICommand IPScannerCommand => new RelayCommand(_ => IPScannerAction(), IPScanner_CanExecute); + + /// + /// The IP Scanner needs an IPv4 address with subnet mask (e.g. not for a disconnected adapter). + /// + private bool IPScanner_CanExecute(object parameter) => AdditionalCommands_CanExecute(parameter) && + GetFirstIPv4AddressWithSubnetmask() != null; + + private Tuple GetFirstIPv4AddressWithSubnetmask() => + SelectedNetworkInterface?.IPv4Address?.FirstOrDefault(x => x.Item2 != null); private void IPScannerAction() { - var ipTuple = SelectedNetworkInterface?.IPv4Address.FirstOrDefault(); + var ipTuple = GetFirstIPv4AddressWithSubnetmask(); - // ToDo: Log error in the future if (ipTuple == null) return; @@ -941,7 +1148,7 @@ private void FlushDNSAction() /// /// Gets the command to release and renew IP address. /// - public ICommand ReleaseRenewCommand => new RelayCommand(_ => ReleaseRenewAction(), ConfigureCommands_CanExecute); + public ICommand ReleaseRenewCommand => new RelayCommand(_ => ReleaseRenewAction(), ConfigureNetworkInterface_CanExecute); private void ReleaseRenewAction() { @@ -951,7 +1158,7 @@ private void ReleaseRenewAction() /// /// Gets the command to release IP address. /// - public ICommand ReleaseCommand => new RelayCommand(_ => ReleaseAction(), ConfigureCommands_CanExecute); + public ICommand ReleaseCommand => new RelayCommand(_ => ReleaseAction(), ConfigureNetworkInterface_CanExecute); private void ReleaseAction() { @@ -961,7 +1168,7 @@ private void ReleaseAction() /// /// Gets the command to renew IP address. /// - public ICommand RenewCommand => new RelayCommand(_ => RenewAction(), ConfigureCommands_CanExecute); + public ICommand RenewCommand => new RelayCommand(_ => RenewAction(), ConfigureNetworkInterface_CanExecute); private void RenewAction() { @@ -971,7 +1178,7 @@ private void RenewAction() /// /// Gets the command to release and renew IPv6 address. /// - public ICommand ReleaseRenew6Command => new RelayCommand(_ => ReleaseRenew6Action(), ConfigureCommands_CanExecute); + public ICommand ReleaseRenew6Command => new RelayCommand(_ => ReleaseRenew6Action(), ConfigureNetworkInterface_CanExecute); private void ReleaseRenew6Action() { @@ -981,7 +1188,7 @@ private void ReleaseRenew6Action() /// /// Gets the command to release IPv6 address. /// - public ICommand Release6Command => new RelayCommand(_ => Release6Action(), ConfigureCommands_CanExecute); + public ICommand Release6Command => new RelayCommand(_ => Release6Action(), ConfigureNetworkInterface_CanExecute); private void Release6Action() { @@ -991,7 +1198,7 @@ private void Release6Action() /// /// Gets the command to renew IPv6 address. /// - public ICommand Renew6Command => new RelayCommand(_ => Renew6Action(), ConfigureCommands_CanExecute); + public ICommand Renew6Command => new RelayCommand(_ => Renew6Action(), ConfigureNetworkInterface_CanExecute); private void Renew6Action() { @@ -1002,10 +1209,13 @@ private void Renew6Action() /// Gets the command to add an IPv4 address. /// public ICommand AddIPv4AddressCommand => new RelayCommand(parameter => { _ = AddIPv4AddressAction(); }, - ConfigureCommands_CanExecute); + ConfigureNetworkInterface_CanExecute); private async Task AddIPv4AddressAction() { + // The network interface the dialog is opened for (the selection can change while it is open) + var networkInterface = SelectedNetworkInterface; + var childWindow = new IPAddressAndSubnetmaskChildWindow(); var childWindowViewModel = new IPAddressAndSubnetmaskViewModel(async instance => @@ -1013,7 +1223,7 @@ private async Task AddIPv4AddressAction() childWindow.IsOpen = false; ConfigurationManager.Current.IsChildWindowOpen = false; - await AddIPv4Address(instance.IPAddress, instance.Subnetmask); + await AddIPv4Address(networkInterface, instance.IPAddress, instance.Subnetmask); }, _ => { childWindow.IsOpen = false; @@ -1033,10 +1243,13 @@ private async Task AddIPv4AddressAction() /// Gets the command to remove an IPv4 address. /// public ICommand RemoveIPv4AddressCommand => new RelayCommand(parameter => { _ = RemoveIPv4AddressAction(); }, - ConfigureCommands_CanExecute); + ConfigureNetworkInterface_CanExecute); private async Task RemoveIPv4AddressAction() { + // The network interface the dialog is opened for (the selection can change while it is open) + var networkInterface = SelectedNetworkInterface; + var childWindow = new DropDownChildWindow(); var childWindowViewModel = new DropDownViewModel(async instance => @@ -1044,13 +1257,13 @@ private async Task RemoveIPv4AddressAction() childWindow.IsOpen = false; ConfigurationManager.Current.IsChildWindowOpen = false; - await RemoveIPv4Address(instance.SelectedValue.Split("/")[0]); + await RemoveIPv4Address(networkInterface, instance.SelectedValue.Split("/")[0]); }, _ => { childWindow.IsOpen = false; ConfigurationManager.Current.IsChildWindowOpen = false; }, - [.. SelectedNetworkInterface.IPv4Address.Select(x => $"{x.Item1}/{Subnetmask.ConvertSubnetmaskToCidr(x.Item2)}")], + [.. networkInterface.IPv4Address.Select(x => $"{x.Item1}/{Subnetmask.ConvertSubnetmaskToCidr(x.Item2)}")], Strings.IPv4Address ); @@ -1069,49 +1282,165 @@ [.. SelectedNetworkInterface.IPv4Address.Select(x => $"{x.Item1}/{Subnetmask.Con #region Methods + private void ReloadNetworkInterfacesOnUIThread() + { + Application.Current?.Dispatcher.BeginInvoke(new Action(ReloadNetworkInterfaces)); + } + + /// + /// A reload was requested while the network interfaces were loaded (e.g. after Apply while a reload started by + /// a network change is running, which may have read the interfaces in the middle of the change). + /// + private bool _reloadPending; + private async void ReloadNetworkInterfaces() { - // Avoid multiple reloads + // Avoid multiple reloads at the same time, but reload once more afterwards if (IsNetworkInterfaceLoading) + { + _reloadPending = true; return; + } IsNetworkInterfaceLoading = true; - // Make the user happy, let him see a reload animation (and he cannot spam the reload command) - await Task.Delay(GlobalStaticConfiguration.ApplicationUIRefreshInterval); + try + { + // Make the user happy, let him see a reload animation (and he cannot spam the reload command) + await Task.Delay(GlobalStaticConfiguration.ApplicationUIRefreshInterval); + + // Store the last selected id + var id = SelectedNetworkInterface?.Id; - // Store the last selected id - var id = SelectedNetworkInterface?.Id ?? string.Empty; + // Get all network interfaces... + var networkInterfaces = await GetNetworkInterfacesAsync(); - // Get all network interfaces... - var networkInterfaces = await NetworkInterface.GetNetworkInterfacesAsync(); + // Invoke on UI thread synchronously + Application.Current.Dispatcher.Invoke(() => + { + // Clear the list + NetworkInterfaces.Clear(); - // Invoke on UI thread synchronously - Application.Current.Dispatcher.Invoke(() => + // Add all network interfaces to the list + networkInterfaces.ForEach(NetworkInterfaces.Add); + }); + + SelectNetworkInterfaceAfterLoad(id); + } + catch (Exception ex) + { + // async void: an unhandled exception would crash the application + Log.Error("Error while reloading the network interfaces.", ex); + } + finally { - // Clear the list - NetworkInterfaces.Clear(); + IsNetworkInterfaceLoading = false; + } - // Add all network interfaces to the list - networkInterfaces.ForEach(NetworkInterfaces.Add); - }); + LoadPendingProfile(); + ReloadIfPending(); + } + + /// + /// Selects a network interface after the list was (re)loaded: the preferred one (selected by the user or a profile, + /// also if it is back after it was missing, e.g. a VPN or USB adapter), then the one selected before, then the + /// first one. The selection is not saved, so a fallback doesn't replace the preferred network interface. + /// + /// ID of the network interface selected before the reload. + private void SelectNetworkInterfaceAfterLoad(string previousId) + { + _isSelectingNetworkInterfaceByCode = true; - // Set the last selected interface, if it is still available on this machine... - SelectedNetworkInterface = string.IsNullOrEmpty(id) - ? NetworkInterfaces.FirstOrDefault() - : NetworkInterfaces.FirstOrDefault(x => x.Id == id); + try + { + SelectedNetworkInterface = NetworkInterface.GetNetworkInterfaceToSelect(NetworkInterfaces, + _preferredNetworkInterfaceId, previousId); + } + finally + { + _isSelectingNetworkInterfaceByCode = false; + } - IsNetworkInterfaceLoading = false; + // No network interface left: remove the meter of the removed one (it would look it up every second, also + // after it was resumed when the view becomes visible again) + if (SelectedNetworkInterface != null) + return; + + RemoveBandwidthMeter(); + _selectedNetworkInterfaceId = null; + } + + /// + /// Remembers a network interface selected by the user or configured: saved in the settings (selected again after + /// a restart) and preferred after a reload. + /// + private void RememberNetworkInterface(NetworkInterfaceInfo networkInterface) + { + // Not saved in the screenshot mode (sample network interfaces) + if (!ScreenshotData.IsEnabled) + SettingsManager.Current.NetworkInterface_InterfaceId = networkInterface.Id; + + _preferredNetworkInterfaceId = networkInterface.Id; + } + + /// + /// Gets the network interfaces of this computer, or the sample network interfaces in the screenshot mode + /// (). + /// + private static Task> GetNetworkInterfacesAsync() + { + return ScreenshotData.IsEnabled + ? Task.FromResult(ScreenshotData.CreateNetworkInterfaces()) + : NetworkInterface.GetNetworkInterfacesAsync(); + } + + /// + /// Selects the network interface a profile is bound to: preferred after a reload in this session, but not saved + /// (only looking at a profile doesn't change the network interface selected after a restart, see + /// when it is configured). + /// + private void SelectNetworkInterfaceOfProfile(NetworkInterfaceInfo networkInterface) + { + _preferredNetworkInterfaceId = networkInterface.Id; + _isSelectingNetworkInterfaceByCode = true; + + try + { + SelectedNetworkInterface = networkInterface; + } + finally + { + _isSelectingNetworkInterfaceByCode = false; + } + } + + private void ReloadIfPending() + { + if (!_reloadPending) + return; + + _reloadPending = false; + + ReloadNetworkInterfaces(); } private void SetConfigurationDefaults(NetworkInterfaceInfo info) { + // Both options of a radio button pair are set: the RadioButton group only unchecks the other one while the + // Configure tab is loaded (not if another tab is shown). if (info.DhcpEnabled) { ConfigEnableDynamicIPAddress = true; + ConfigEnableStaticIPAddress = false; + + // Values of another interface or profile don't belong to this one (same as the Windows dialog: empty) + ConfigIPAddress = string.Empty; + ConfigSubnetmask = string.Empty; + ConfigGateway = string.Empty; } else { + ConfigEnableDynamicIPAddress = false; ConfigEnableStaticIPAddress = true; ConfigIPAddress = info.IPv4Address.FirstOrDefault()?.Item1.ToString(); ConfigSubnetmask = info.IPv4Address.FirstOrDefault()?.Item2.ToString(); @@ -1120,12 +1449,17 @@ private void SetConfigurationDefaults(NetworkInterfaceInfo info) : string.Empty; } - if (info.DNSAutoconfigurationEnabled) + if (info.DNSAutoconfigurationEnabled && info.DhcpEnabled) { ConfigEnableDynamicDNS = true; + ConfigEnableStaticDNS = false; + + ConfigPrimaryDNSServer = string.Empty; + ConfigSecondaryDNSServer = string.Empty; } else { + ConfigEnableDynamicDNS = false; ConfigEnableStaticDNS = true; var dnsServers = info.DNSServer.Where(x => x.AddressFamily == AddressFamily.InterNetwork) @@ -1135,111 +1469,220 @@ private void SetConfigurationDefaults(NetworkInterfaceInfo info) } } - private async Task ApplyConfiguration() + /// + /// Selects the network interface the profile is bound to (if it exists on this computer) and fills in the values + /// of the profile on the Configure tab. + /// + private void LoadProfile(ProfileInfo profile) { - IsConfigurationRunning = true; + // The message of a previous action or profile doesn't belong to this profile IsStatusMessageDisplayed = false; - var subnetmask = ConfigSubnetmask; + var boundNetworkInterface = GetBoundNetworkInterface(profile); - // CIDR to subnetmask - if (ConfigEnableStaticIPAddress && subnetmask.StartsWith("/")) - subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; - - // If primary and secondary DNS are empty --> autoconfiguration - if (ConfigEnableStaticDNS && string.IsNullOrEmpty(ConfigPrimaryDNSServer) && - string.IsNullOrEmpty(ConfigSecondaryDNSServer)) - ConfigEnableDynamicDNS = true; - - // When primary DNS is empty, swap it with secondary (if not empty) - if (ConfigEnableStaticDNS && string.IsNullOrEmpty(ConfigPrimaryDNSServer) && - !string.IsNullOrEmpty(ConfigSecondaryDNSServer)) + if (boundNetworkInterface != null) { - ConfigPrimaryDNSServer = ConfigSecondaryDNSServer; - ConfigSecondaryDNSServer = string.Empty; + SelectNetworkInterfaceOfProfile(boundNetworkInterface); } - - var config = new NetworkInterfaceConfig + else if (IsBoundToNetworkInterface(profile)) { - Name = SelectedNetworkInterface.Name, - EnableStaticIPAddress = ConfigEnableStaticIPAddress, - IPAddress = ConfigIPAddress, - Subnetmask = subnetmask, - Gateway = ConfigGateway, - EnableStaticDNS = ConfigEnableStaticDNS, - PrimaryDNSServer = ConfigPrimaryDNSServer, - SecondaryDNSServer = ConfigSecondaryDNSServer - }; + // The values would be applied to the selected network interface by the Apply button (the context menu + // asks first, see ConfirmApplyToSelectedNetworkInterface) + StatusMessage = string.Format(Strings.NetworkInterfaceXOfProfileNotFoundCheckSelected, + profile.NetworkInterface_InterfaceName); + StatusMessageLevel = StatusLevel.Warning; + IsStatusMessageDisplayed = true; + } - try + SetConfigurationFromProfile(profile); + } + + /// + /// Fills in the values of a profile on the Configure tab. + /// + private void SetConfigurationFromProfile(ProfileInfo profile) + { + ConfigEnableDynamicIPAddress = !profile.NetworkInterface_EnableStaticIPAddress; + ConfigEnableStaticIPAddress = profile.NetworkInterface_EnableStaticIPAddress; + ConfigIPAddress = profile.NetworkInterface_IPAddress; + ConfigGateway = profile.NetworkInterface_Gateway; + ConfigSubnetmask = profile.NetworkInterface_Subnetmask; + + // DNS servers can only be obtained automatically with DHCP (older profiles may contain both) + var enableStaticDNS = profile.NetworkInterface_EnableStaticIPAddress || + profile.NetworkInterface_EnableStaticDNS; + ConfigEnableDynamicDNS = !enableStaticDNS; + ConfigEnableStaticDNS = enableStaticDNS; + ConfigPrimaryDNSServer = profile.NetworkInterface_PrimaryDNSServer; + ConfigSecondaryDNSServer = profile.NetworkInterface_SecondaryDNSServer; + } + + private Task ApplyConfiguration() + { + return ApplyConfigurationAsync(SelectedNetworkInterface, NetworkInterfaceConfig.Create( + SelectedNetworkInterface.Name, ConfigEnableStaticIPAddress, ConfigIPAddress, ConfigSubnetmask, ConfigGateway, + ConfigEnableStaticDNS, ConfigPrimaryDNSServer, ConfigSecondaryDNSServer)); + } + + private async Task ApplyConfigurationFromProfile() + { + var profile = SelectedProfile; + var networkInterface = SelectedNetworkInterface; + + // Profile bound to a network interface (matched by ID only, the name is not unique) + if (IsBoundToNetworkInterface(profile)) { - await NetworkInterface.ConfigureNetworkInterfaceAsync(config); + var boundNetworkInterface = GetBoundNetworkInterface(profile); - ReloadNetworkInterfaces(); + if (boundNetworkInterface == null) + { + networkInterface = await ConfirmApplyToSelectedNetworkInterface(profile); - StatusMessage = Strings.NetworkInterfaceConfigurationAppliedSuccessfully; - StatusMessageLevel = StatusLevel.Success; - IsStatusMessageDisplayed = true; + if (networkInterface == null) + return; + } + else + { + networkInterface = boundNetworkInterface; + } } - catch (Exception ex) + + // Checked before the bound network interface is selected: selecting it would replace the values on the + // Configure tab and restart the bandwidth measurement, although nothing is applied + if (networkInterface is not { IsOperational: true }) { - StatusMessage = ex.Message; - StatusMessageLevel = StatusLevel.Error; + StatusMessage = Strings.ConnectTheNetworkCardToConfigureIt; + StatusMessageLevel = StatusLevel.Warning; IsStatusMessageDisplayed = true; + return; } - finally + + // Select it, so the result can be checked on the Information tab + if (networkInterface.Id != SelectedNetworkInterface?.Id) + SelectNetworkInterfaceOfProfile(networkInterface); + + // Show the applied values on the Configure tab (selecting the bound network interface above filled in its + // current configuration) + SetConfigurationFromProfile(profile); + + await ApplyConfigurationAsync(networkInterface, NetworkInterfaceConfig.Create(networkInterface.Name, + profile.NetworkInterface_EnableStaticIPAddress, profile.NetworkInterface_IPAddress, + profile.NetworkInterface_Subnetmask, profile.NetworkInterface_Gateway, + profile.NetworkInterface_EnableStaticDNS, profile.NetworkInterface_PrimaryDNSServer, + profile.NetworkInterface_SecondaryDNSServer)); + } + + /// + /// Gets the network interface a profile is bound to, or if the profile is not bound or the + /// network interface is not found on this computer. + /// + private NetworkInterfaceInfo GetBoundNetworkInterface(ProfileInfo profile) + { + return IsBoundToNetworkInterface(profile) + ? NetworkInterface.FindById(NetworkInterfaces, profile.NetworkInterface_InterfaceId) + : null; + } + + /// + /// Whether a profile is bound to a network interface. A profile from an edited or imported file can have the option + /// enabled without an ID: it is used like a profile that is not bound (no "not found" message without a name / ID). + /// + private static bool IsBoundToNetworkInterface(ProfileInfo profile) => + profile.NetworkInterface_BindToInterface && !string.IsNullOrEmpty(profile.NetworkInterface_InterfaceId); + + /// + /// The network interface of the profile is not found on this computer: ask whether the profile should be applied + /// to the selected network interface instead (only if it can be configured). + /// + /// The selected network interface (current object after the dialog, the list may have been reloaded + /// meanwhile), or if canceled or it is no longer selected. + private async Task ConfirmApplyToSelectedNetworkInterface(ProfileInfo profile) + { + var message = string.Format(Strings.NetworkInterfaceOfProfileXNotFoundOnThisComputer, profile.Name) + + Environment.NewLine + Environment.NewLine + + $"{Strings.Name}: {profile.NetworkInterface_InterfaceName}" + Environment.NewLine + + $"{Strings.ID}: {profile.NetworkInterface_InterfaceId}" + Environment.NewLine + + Environment.NewLine; + + var selectedNetworkInterface = SelectedNetworkInterface; + + if (selectedNetworkInterface is not { IsOperational: true }) { - IsConfigurationRunning = false; + await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.NetworkInterfaceNotFound, + message + Strings.FixNetworkInterfaceOfProfileHint, ChildWindowIcon.Warn); + + return null; } + + if (!await DialogHelper.ShowConfirmationMessageAsync(Application.Current.MainWindow, + Strings.NetworkInterfaceNotFound, + message + string.Format(Strings.ApplyProfileToSelectedNetworkInterfaceXInstead, + selectedNetworkInterface.Name) + Environment.NewLine + Environment.NewLine + + Strings.FixNetworkInterfaceOfProfileHint, ChildWindowIcon.Warn, Strings.Apply)) + return null; + + // Only the network interface named in the dialog (a reload may have selected another one meanwhile) + return SelectedNetworkInterface?.Id == selectedNetworkInterface.Id ? SelectedNetworkInterface : null; } - private async Task ApplyConfigurationFromProfile() + /// + /// Shows a (localized) message if a value of the configuration is not a valid IPv4 address or subnet mask. The + /// model checks it again before running netsh, but its exception is not localized. + /// + /// if the configuration is valid. + private bool ValidateConfiguration(NetworkInterfaceConfig config) { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + // Profiles can contain values that were not validated by the UI (e.g. edited or shared profile files). + var invalidValue = config.GetInvalidValue(); - var subnetmask = SelectedProfile.NetworkInterface_Subnetmask; + if (invalidValue == null) + return true; - // CIDR to subnetmask - if (SelectedProfile.NetworkInterface_EnableStaticIPAddress && subnetmask.StartsWith("/")) - subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; + // An empty value means the IP address or subnet mask of a static IP address is missing + StatusMessage = invalidValue.Length == 0 + ? Strings.NetworkInterfaceConfigIPAddressAndSubnetmaskRequired + : string.Format(Strings.NetworkInterfaceConfigInvalidValueX, invalidValue); + StatusMessageLevel = StatusLevel.Error; + IsStatusMessageDisplayed = true; - var enableStaticDNS = SelectedProfile.NetworkInterface_EnableStaticDNS; + return false; + } - var primaryDNSServer = SelectedProfile.NetworkInterface_PrimaryDNSServer; - var secondaryDNSServer = SelectedProfile.NetworkInterface_SecondaryDNSServer; + private Task ApplyConfigurationAsync(NetworkInterfaceInfo networkInterface, NetworkInterfaceConfig config) + { + if (!ValidateConfiguration(config)) + return Task.CompletedTask; - // If primary and secondary DNS are empty --> autoconfiguration - if (enableStaticDNS && string.IsNullOrEmpty(primaryDNSServer) && string.IsNullOrEmpty(secondaryDNSServer)) - enableStaticDNS = false; + return RunConfigurationAsync(() => NetworkInterface.ConfigureNetworkInterfaceAsync(config), + Strings.NetworkInterfaceConfigurationAppliedSuccessfully, networkInterface); + } - // 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; - } + /// + /// Runs a configuration action (netsh / ipconfig): only one at a time, the success message or the error (of + /// Windows) is shown below the configuration. If a network interface is changed, it is remembered (like a + /// selection by the user: it stays selected after the reload, also if it was only selected as a fallback for a + /// missing one) and the network interfaces are reloaded afterwards (also after an error). + /// + /// Action to run. + /// Message shown if the action succeeded. + /// Network interface that is changed, or if none is + /// changed (e.g. flush DNS cache). + private async Task RunConfigurationAsync(Func action, string successMessage, + NetworkInterfaceInfo networkInterface = null) + { + if (networkInterface != null) + RememberNetworkInterface(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 - }; + IsConfigurationRunning = true; + IsStatusMessageDisplayed = false; try { - await NetworkInterface.ConfigureNetworkInterfaceAsync(config); - - ReloadNetworkInterfaces(); + // Nothing is changed in the screenshot mode (sample network interfaces), only the result is shown + if (!ScreenshotData.IsEnabled) + await action(); - StatusMessage = Strings.NetworkInterfaceConfigurationAppliedSuccessfully; + StatusMessage = successMessage; StatusMessageLevel = StatusLevel.Success; IsStatusMessageDisplayed = true; } @@ -1252,6 +1695,11 @@ private async Task ApplyConfigurationFromProfile() finally { IsConfigurationRunning = false; + + // Also after an error: the commands run one after another and stop at the first error, the ones before + // may have changed the configuration (e.g. IP address set, DNS servers failed). + if (networkInterface != null) + ReloadNetworkInterfaces(); } } @@ -1268,43 +1716,17 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Erro } } - private async Task FlushDNSAsync() + private Task FlushDNSAsync() { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; - - try - { - await NetworkInterface.FlushDnsAsync(); - - StatusMessage = Strings.FlushDNSCacheSuccessfully; - StatusMessageLevel = StatusLevel.Success; - IsStatusMessageDisplayed = true; - } - catch (Exception ex) - { - StatusMessage = ex.Message; - StatusMessageLevel = StatusLevel.Error; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } + return RunConfigurationAsync(NetworkInterface.FlushDnsAsync, Strings.FlushDNSCacheSuccessfully); } - private async Task ReleaseRenewAsync(IPConfigReleaseRenewMode releaseRenewMode) + private Task ReleaseRenewAsync(IPConfigReleaseRenewMode releaseRenewMode) { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + var networkInterface = SelectedNetworkInterface; - try - { - await NetworkInterface.ReleaseRenewAsync(releaseRenewMode, SelectedNetworkInterface.Name); - - ReloadNetworkInterfaces(); - - StatusMessage = releaseRenewMode switch + return RunConfigurationAsync(() => NetworkInterface.ReleaseRenewAsync(releaseRenewMode, networkInterface.Name), + releaseRenewMode switch { IPConfigReleaseRenewMode.ReleaseRenew => Strings.IPv4AddressReleasedAndRenewedSuccessfully, IPConfigReleaseRenewMode.Release => Strings.IPv4AddressReleasedSuccessfully, @@ -1313,94 +1735,70 @@ private async Task ReleaseRenewAsync(IPConfigReleaseRenewMode releaseRenewMode) IPConfigReleaseRenewMode.Release6 => Strings.IPv6AddressReleasedSuccessfully, IPConfigReleaseRenewMode.Renew6 => Strings.IPv6AddressRenewedSuccessfully, _ => string.Empty - }; - StatusMessageLevel = StatusLevel.Success; - IsStatusMessageDisplayed = true; - } - catch (Exception ex) - { - StatusMessage = ex.Message; - StatusMessageLevel = StatusLevel.Error; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } + }, networkInterface); } - private async Task AddIPv4Address(string ipAddress, string subnetmaskOrCidr) + /// + /// Gets the current object of a network interface a dialog was opened for. The list may have been reloaded while + /// the dialog was open (new objects) or the network interface may have been removed (e.g. a USB or VPN adapter): + /// then nothing is changed, instead of changing another network interface that was selected meanwhile. + /// + /// Network interface the dialog was opened for. + /// The current object, or if it no longer exists (a message is shown). + private NetworkInterfaceInfo GetCurrentNetworkInterface(NetworkInterfaceInfo networkInterface) { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + var currentNetworkInterface = NetworkInterface.FindById(NetworkInterfaces, networkInterface.Id); + + if (currentNetworkInterface != null) + return currentNetworkInterface; - var subnetmask = subnetmaskOrCidr; + StatusMessage = string.Format(Strings.NetworkInterfaceXNotFoundNothingChanged, networkInterface.Name); + StatusMessageLevel = StatusLevel.Warning; + IsStatusMessageDisplayed = true; - // CIDR to subnetmask - if (subnetmask.StartsWith("/")) - subnetmask = Subnetmask.GetFromCidr(int.Parse(subnetmask.TrimStart('/'))).Subnetmask; + return null; + } + + private Task AddIPv4Address(NetworkInterfaceInfo networkInterface, string ipAddress, string subnetmaskOrCidr) + { + networkInterface = GetCurrentNetworkInterface(networkInterface); + + if (networkInterface == null) + return Task.CompletedTask; var config = new NetworkInterfaceConfig { - Name = SelectedNetworkInterface.Name, - EnableDhcpStaticIpCoexistence = SelectedNetworkInterface.DhcpEnabled, - IPAddress = ipAddress, - Subnetmask = subnetmask + Name = networkInterface.Name, + EnableDhcpStaticIpCoexistence = networkInterface.DhcpEnabled, + IPAddress = ipAddress.Trim(), + Subnetmask = NetworkInterfaceConfig.ConvertSubnetmaskOrCidr(subnetmaskOrCidr) }; - try - { - await NetworkInterface.AddIPAddressToNetworkInterfaceAsync(config); - - ReloadNetworkInterfaces(); + if (!ValidateConfiguration(config)) + return Task.CompletedTask; - StatusMessage = Strings.IPv4AddressAddedSuccessfully; - StatusMessageLevel = StatusLevel.Success; - IsStatusMessageDisplayed = true; - } - catch (Exception ex) - { - StatusMessage = ex.Message; - StatusMessageLevel = StatusLevel.Error; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } + return RunConfigurationAsync(() => NetworkInterface.AddIPAddressToNetworkInterfaceAsync(config), + Strings.IPv4AddressAddedSuccessfully, networkInterface); } - private async Task RemoveIPv4Address(string ipAddress) + private Task RemoveIPv4Address(NetworkInterfaceInfo networkInterface, string ipAddress) { - IsConfigurationRunning = true; - IsStatusMessageDisplayed = false; + networkInterface = GetCurrentNetworkInterface(networkInterface); + + if (networkInterface == null) + return Task.CompletedTask; var config = new NetworkInterfaceConfig { - Name = SelectedNetworkInterface.Name, + Name = networkInterface.Name, IPAddress = ipAddress }; - try - { - await NetworkInterface.RemoveIPAddressFromNetworkInterfaceAsync(config); + if (!ValidateConfiguration(config)) + return Task.CompletedTask; - ReloadNetworkInterfaces(); - - StatusMessage = Strings.IPv4AddressRemovedSuccessfully; - StatusMessageLevel = StatusLevel.Success; - IsStatusMessageDisplayed = true; - } - catch (Exception ex) - { - StatusMessage = ex.Message; - StatusMessageLevel = StatusLevel.Error; - IsStatusMessageDisplayed = true; - } - finally - { - IsConfigurationRunning = false; - } + return RunConfigurationAsync(() => NetworkInterface.RemoveIPAddressFromNetworkInterfaceAsync(config), + Strings.IPv4AddressRemovedSuccessfully, networkInterface); } private void ResetBandwidthChart() @@ -1486,17 +1884,55 @@ private void BandwidthGoLiveAction() private bool _resetBandwidthStatisticOnNextUpdate; + /// + /// The view is created when it is shown for the first time (without OnViewVisible). + /// + private bool _isViewVisible = true; + private void StartBandwidthMeter(string networkInterfaceId) { + RemoveBandwidthMeter(); + // Reset chart ResetBandwidthChart(); // Reset statistic _resetBandwidthStatisticOnNextUpdate = true; + if (ScreenshotData.IsEnabled) + { + ShowScreenshotBandwidth(networkInterfaceId); + return; + } + _bandwidthMeter = new BandwidthMeter(networkInterfaceId); _bandwidthMeter.UpdateSpeed += BandwidthMeter_UpdateSpeed; - _bandwidthMeter.Start(); + + // Another adapter can be selected while the view is hidden (e.g. by a reload after a network change): start + // the measurement when the view becomes visible (ResumeBandwidthMeter). + if (_isViewVisible) + _bandwidthMeter.Start(); + } + + /// + /// Fills the bandwidth chart and statistics with sample values in the screenshot mode (), + /// instead of a measurement (static, no live updates). Only for a connected network interface. + /// + private void ShowScreenshotBandwidth(string networkInterfaceId) + { + if (NetworkInterface.FindById(NetworkInterfaces, networkInterfaceId) is not { IsOperational: true }) + return; + + var samples = ScreenshotData.CreateBandwidthSamples((int)BandwidthChartWindowSeconds); + + _bandwidthSessionStartTime = samples[0].DateTime; + + foreach (var sample in samples) + BandwidthMeter_UpdateSpeed(this, sample); + + // The statistic started with the first sample (not now) + BandwidthStartTime = samples[0].DateTime; + BandwidthMeasuredTime = samples[^1].DateTime - BandwidthStartTime; } private void ResumeBandwidthMeter() @@ -1513,6 +1949,20 @@ private void ResumeBandwidthMeter() _bandwidthMeter.Start(); } + /// + /// Stops the meter and removes it (with its event handler), e.g. before a meter for another network interface is + /// started or if no network interface is left. + /// + private void RemoveBandwidthMeter() + { + if (_bandwidthMeter == null) + return; + + _bandwidthMeter.Stop(); + _bandwidthMeter.UpdateSpeed -= BandwidthMeter_UpdateSpeed; + _bandwidthMeter = null; + } + private void StopBandwidthMeter() { if (_bandwidthMeter is not { IsRunning: true }) @@ -1526,6 +1976,8 @@ private void StopBandwidthMeter() /// public override void OnViewVisible() { + _isViewVisible = true; + base.OnViewVisible(); ResumeBandwidthMeter(); @@ -1536,6 +1988,8 @@ public override void OnViewVisible() /// public override void OnViewHide() { + _isViewVisible = false; + StopBandwidthMeter(); base.OnViewHide(); diff --git a/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs b/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs index ad719ff64e..a1c2a3e6ad 100644 --- a/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs +++ b/Source/NETworkManager/ViewModels/ProfileHostViewModelBase.cs @@ -78,6 +78,13 @@ public virtual ProfileInfo SelectedProfile } } + /// + /// Whether is set because the profile list was rebuilt (view visible, search, + /// filter, profiles changed: the previous or the first profile is selected again), not by the user. Tools that + /// react to a selection (e.g. fill in values) can ignore these. + /// + protected bool IsProfileSelectedByCode { get; private set; } + /// /// Gets or sets the search text. /// @@ -455,14 +462,26 @@ private void SetProfilesView(ProfileFilterInfo filter, ProfileInfo profile = nul Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group))); + // A profile that was edited meanwhile is a new object: select the edited one + profile = ProfileManager.GetCurrentProfile(profile); + // Set specific profile or first if null - SelectedProfile = null; + IsProfileSelectedByCode = true; - if (profile != null) - SelectedProfile = Profiles.Cast().FirstOrDefault(x => x.Equals(profile)) ?? - Profiles.Cast().FirstOrDefault(); - else - SelectedProfile = Profiles.Cast().FirstOrDefault(); + try + { + SelectedProfile = null; + + if (profile != null) + SelectedProfile = Profiles.Cast().FirstOrDefault(x => x.Equals(profile)) ?? + Profiles.Cast().FirstOrDefault(); + else + SelectedProfile = Profiles.Cast().FirstOrDefault(); + } + finally + { + IsProfileSelectedByCode = false; + } } private void RefreshProfiles() diff --git a/Source/NETworkManager/ViewModels/ProfileViewModel.cs b/Source/NETworkManager/ViewModels/ProfileViewModel.cs index 0d14098b3f..41053f0d27 100644 --- a/Source/NETworkManager/ViewModels/ProfileViewModel.cs +++ b/Source/NETworkManager/ViewModels/ProfileViewModel.cs @@ -1,4 +1,5 @@ using DnsClient; +using log4net; using NETworkManager.Controls; using NETworkManager.Localization.Resources; using NETworkManager.Models; @@ -12,6 +13,7 @@ using NETworkManager.Utilities; using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Net; @@ -26,6 +28,8 @@ namespace NETworkManager.ViewModels; public class ProfileViewModel : ViewModelBase { + private static readonly ILog Log = LogManager.GetLogger(typeof(ProfileViewModel)); + #region Constructor public ProfileViewModel(Action saveCommand, Action cancelHandler, @@ -68,13 +72,32 @@ public ProfileViewModel(Action saveCommand, Action + /// ID and name of the network interface the profile is bound to (loaded from the profile). + /// + private readonly string _networkInterfaceBoundId; + + private readonly string _networkInterfaceBoundName; + + private bool _networkInterfacesLoaded; + + public bool NetworkInterface_BindToInterface + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + + // Only load the network interfaces if they are needed (slows down every profile dialog) + LoadNetworkInterfacesIfNeeded(); + } + } + + /// + /// Network interfaces of this computer to bind the profile to. A bound network interface that is not found on + /// this computer is added (with ), so it is kept when the profile + /// is saved. + /// + public ObservableCollection NetworkInterface_Interfaces { get; } = []; + + public NetworkInterfaceInfo NetworkInterface_SelectedInterface + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// ID of the network interface to save: the selected one, or the one of the profile while the network interfaces + /// are not loaded (yet, or loading failed), so saving doesn't remove the binding. + /// + public string NetworkInterface_BoundInterfaceId => + NetworkInterface_SelectedInterface?.Id ?? _networkInterfaceBoundId; + + /// + /// Name of the network interface to save, see . + /// + public string NetworkInterface_BoundInterfaceName => + NetworkInterface_SelectedInterface?.Name ?? _networkInterfaceBoundName; + + /// + /// Loads the network interfaces if they are needed: Network Interface is enabled and the profile is bound (it runs + /// on every change of these options, but loads only once, see ). + /// + private void LoadNetworkInterfacesIfNeeded() + { + if (NetworkInterface_Enabled && NetworkInterface_BindToInterface) + _ = LoadNetworkInterfacesAsync(); + } + + private async Task LoadNetworkInterfacesAsync() + { + if (_networkInterfacesLoaded) + return; + + _networkInterfacesLoaded = true; + NetworkInterface_InterfacesLoadFailed = false; + + List networkInterfaces; + + try + { + // Sample network interfaces in the screenshot mode (like the Network Interface tool) + networkInterfaces = ScreenshotData.IsEnabled + ? ScreenshotData.CreateNetworkInterfaces() + : await NetworkInterface.GetNetworkInterfacesAsync(); + } + catch (Exception ex) + { + Log.Error("Error while loading the network interfaces.", ex); + + // Loaded again the next time the option is enabled + _networkInterfacesLoaded = false; + NetworkInterface_InterfacesLoadFailed = true; + networkInterfaces = []; + } + + NetworkInterface_Interfaces.Clear(); + networkInterfaces.ForEach(NetworkInterface_Interfaces.Add); + + // Not bound yet: the network interface last selected by the user (or configured) in the Network Interface tool + // (saved in the settings, not one selected by a profile), or the first one if it is not available (like the + // tool after a load, so the drop-down is not empty) + if (string.IsNullOrEmpty(_networkInterfaceBoundId)) + { + NetworkInterface_SelectedInterface ??= NetworkInterface.GetNetworkInterfaceToSelect( + NetworkInterface_Interfaces, SettingsManager.Current.NetworkInterface_InterfaceId, null); + + return; + } + + var boundInterface = NetworkInterface.FindById(NetworkInterface_Interfaces, _networkInterfaceBoundId); + + if (boundInterface == null) + { + // Kept, so the profile can be saved without changing it (not "not found" if the list couldn't be loaded) + boundInterface = new NetworkInterfaceInfo + { + Id = _networkInterfaceBoundId, + Name = _networkInterfaceBoundName, + Description = NetworkInterface_InterfacesLoadFailed ? string.Empty : Strings.NotFoundOnThisComputer + }; + + NetworkInterface_Interfaces.Add(boundInterface); + } + + NetworkInterface_SelectedInterface = boundInterface; + } + + /// + /// The network interfaces could not be loaded (a hint is shown, they are loaded again when the option is enabled + /// again). + /// + public bool NetworkInterface_InterfacesLoadFailed + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); } } diff --git a/Source/NETworkManager/ViewModels/ProfilesViewModel.cs b/Source/NETworkManager/ViewModels/ProfilesViewModel.cs index 821e88860b..f6ff81ef5b 100644 --- a/Source/NETworkManager/ViewModels/ProfilesViewModel.cs +++ b/Source/NETworkManager/ViewModels/ProfilesViewModel.cs @@ -406,6 +406,9 @@ private void SetProfilesView(ProfileFilterInfo filter, GroupInfo group, ProfileI ).OrderBy(x => x.Name) }.View; + // A profile that was edited meanwhile is a new object: select the edited one + profile = ProfileManager.GetCurrentProfile(profile); + // Set specific profile or first if null SelectedProfile = null; diff --git a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs index 39d46b1079..b60d6cf1e5 100644 --- a/Source/NETworkManager/ViewModels/RunCommandViewModel.cs +++ b/Source/NETworkManager/ViewModels/RunCommandViewModel.cs @@ -707,7 +707,8 @@ private void UpdateHint() foreach (var part in command.SyntaxParts) { - if (part.Kind == RunCommandSyntaxPartKind.Profile) + // Target or profile (without a target, the profile is optional: "[@]") + if (part.Kind == RunCommandSyntaxPartKind.Profile && command.SupportsTarget) parts.Add(new RunCommandHintPart("|", false)); parts.Add(new RunCommandHintPart(part.Text, part.Kind == currentPart)); diff --git a/Source/NETworkManager/Views/NetworkInterfaceView.xaml b/Source/NETworkManager/Views/NetworkInterfaceView.xaml index 753aa22229..9488a01cf1 100644 --- a/Source/NETworkManager/Views/NetworkInterfaceView.xaml +++ b/Source/NETworkManager/Views/NetworkInterfaceView.xaml @@ -28,6 +28,8 @@ + @@ -49,8 +51,42 @@ - + + + + + + + + + + + + - + + + + @@ -1289,6 +1375,8 @@ + + +