From 92e4b0de94d86eeb94384dda5066f358b784ffc7 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 29 Nov 2026 01:33:06 +0100 Subject: [PATCH 01/17] Ping Monitor: async ping loop, keep pinging on errors, history limit, host limit - B2/B12/B10: HostMonitor (Models) replaces the blocking Ping loop (Task.Run + sync Send + Thread.Sleep): SendPingAsync + Task.Delay with the token, Stopped is raised in finally (also if paused before start), Pause is immediate. Probe-agnostic (IHostMonitorProbe, ICMP probe only), prepared for TCP / HTTP. - N1: every state change of a host happens on the UI thread (one BeginInvoke per ping as before), late events of a previous run are ignored. - B4: an exception (PingException) counts as lost ping (IPStatus.Unknown) with the message as tooltip; the host keeps pinging. - B7: the known hostname is passed to the monitor, the PTR record is only resolved without one. - R2: removed PingCompleted / PingExceptionArgs; Ping is a static helper. - B3 + T5: new setting PingMonitor_HistoryHours (default 24, 1-168), PingMonitorHistory.Trim removes outdated pings in batches. - B1: confirmation above 256 hosts, error above 4096. Co-Authored-By: Claude Opus 5.5 --- .../Resources/Strings.Designer.cs | 42 +++- .../Resources/Strings.resx | 16 +- .../Network/HostMonitor.cs | 171 ++++++++++++++++ .../Network/ICMPHostMonitorProbe.cs | 52 +++++ .../Network/IHostMonitorProbe.cs | 33 +++ Source/NETworkManager.Models/Network/Ping.cs | 191 +----------------- .../Network/PingExceptionArgs.cs | 15 -- .../Network/PingMonitorHistory.cs | 39 ++++ .../Network/PingReceivedArgs.cs | 16 +- .../GlobalStaticConfiguration.cs | 8 + .../NETworkManager.Settings/SettingsInfo.cs | 16 ++ .../Network/PingMonitorHistoryTests.cs | 63 ++++++ .../ViewModels/PingMonitorHostViewModel.cs | 48 ++++- .../PingMonitorSettingsViewModel.cs | 20 ++ .../ViewModels/PingMonitorViewModel.cs | 143 +++++++------ .../Views/PingMonitorSettingsView.xaml | 13 ++ Website/docs/application/ping-monitor.md | 13 +- Website/docs/changelog/next-release.md | 7 + 18 files changed, 628 insertions(+), 278 deletions(-) create mode 100644 Source/NETworkManager.Models/Network/HostMonitor.cs create mode 100644 Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs create mode 100644 Source/NETworkManager.Models/Network/IHostMonitorProbe.cs delete mode 100644 Source/NETworkManager.Models/Network/PingExceptionArgs.cs create mode 100644 Source/NETworkManager.Models/Network/PingMonitorHistory.cs create mode 100644 Source/NETworkManager.Tests/Network/PingMonitorHistoryTests.cs diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 3476a91987..8182e8a631 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -6363,7 +6363,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 { @@ -6657,6 +6657,15 @@ public static string HelpMessage_PingHostsBeforeScan { } } + /// + /// Looks up a localized string similar to Pings older than this are removed from the history of a host (export, chart when returning to live mode). The counters (received, lost, packet loss) include all pings since the host was started.. + /// + public static string HelpMessage_PingMonitorHistoryHours { + get { + return ResourceManager.GetString("HelpMessage_PingMonitorHistoryHours", resourceCulture); + } + } + /// /// Looks up a localized string similar to Pings a public IP address with every check of the network connection (dashboard and status window) to see if the internet is reachable. The target receives a ping (ICMP echo request). /// @@ -7003,6 +7012,15 @@ public static string History { } } + /// + /// Looks up a localized string similar to History (hours). + /// + public static string HistoryInHours { + get { + return ResourceManager.GetString("HistoryInHours", resourceCulture); + } + } + /// /// Looks up a localized string similar to Hop. /// @@ -10651,6 +10669,17 @@ public static string PingMonitor { } } + /// + /// Looks up a localized string similar to {0} hosts will be added. Each host is pinged continuously and has its own chart, this needs a lot of resources. + /// + ///Do you want to add the hosts?. + /// + public static string PingMonitorManyHostsMessage { + get { + return ResourceManager.GetString("PingMonitorManyHostsMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Notification. /// @@ -10660,6 +10689,15 @@ public static string PingMonitorNotification { } } + /// + /// Looks up a localized string similar to {0} hosts cannot be monitored at once (maximum {1}). Split the input into smaller ranges.. + /// + public static string PingMonitorTooManyHostsMessage { + get { + return ResourceManager.GetString("PingMonitorTooManyHostsMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Ping public IP address. /// @@ -11041,7 +11079,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 { diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index ff1ae46fe0..1bb25f3f83 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5917,4 +5917,18 @@ Own row: above the speed test. Open Windows Settings > Privacy & security > Location and enable access for Desktop Apps / NETworkManager. The widget shows the connection a few seconds later, a restart is not needed. - \ No newline at end of file + + {0} hosts will be added. Each host is pinged continuously and has its own chart, this needs a lot of resources. + +Do you want to add the hosts? + + + {0} hosts cannot be monitored at once (maximum {1}). Split the input into smaller ranges. + + + History (hours) + + + Pings older than this are removed from the history of a host (export, chart when returning to live mode). The counters (received, lost, packet loss) include all pings since the host was started. + + diff --git a/Source/NETworkManager.Models/Network/HostMonitor.cs b/Source/NETworkManager.Models/Network/HostMonitor.cs new file mode 100644 index 0000000000..8d2e0c30aa --- /dev/null +++ b/Source/NETworkManager.Models/Network/HostMonitor.cs @@ -0,0 +1,171 @@ +using System; +using System.Net; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; +using log4net; +using NETworkManager.Utilities; + +namespace NETworkManager.Models.Network; + +/// +/// Checks a host continuously (Ping Monitor): one check of the , then +/// , until it is canceled. Fully asynchronous - no thread is blocked while waiting for a +/// reply or between the checks, and a cancellation stops it right away. +/// +/// +/// The events are raised on a thread pool thread. +/// +public sealed class HostMonitor +{ + private static readonly ILog Log = LogManager.GetLogger(typeof(HostMonitor)); + + private readonly IHostMonitorProbe _probe; + + /// + /// Creates a new monitor for a host. + /// + /// IP address of the host. + /// Known hostname (e.g. typed by the user), null or empty to resolve the PTR record. + /// Check of the host (e.g. ). + public HostMonitor(IPAddress ipAddress, string hostname, IHostMonitorProbe probe) + { + IPAddress = ipAddress; + Hostname = hostname; + _probe = probe; + } + + /// + /// IP address of the host. + /// + public IPAddress IPAddress { get; } + + /// + /// Hostname of the host (the known one, otherwise the PTR record once it is resolved). + /// + public string Hostname { get; private set; } + + /// + /// Time in milliseconds to wait between the checks. Default is 1000 ms. + /// + public int WaitTime { get; init; } = 1000; + + #region Events + + /// + /// Occurs after each check. A check that failed with an exception is reported with + /// and the message (). + /// + public event EventHandler PingReceived; + + /// + /// Occurs when the PTR record of the host was resolved (only if no hostname was known). + /// + public event EventHandler HostnameResolved; + + /// + /// Occurs when the monitor has stopped (canceled, or an unexpected error). Always the last event. + /// + public event EventHandler Stopped; + + #endregion + + /// + /// Starts the monitor in the background. It runs until the token is canceled. + /// + /// Token to stop the monitor. + public void Start(CancellationToken cancellationToken) + { + // On the thread pool, not on the caller's (UI) thread. The token is deliberately not passed to Task.Run: a + // token canceled before the task starts would skip RunAsync - and Stopped would never be raised. + _ = Task.Run(() => RunAsync(cancellationToken), CancellationToken.None); + } + + /// + /// Runs the monitor until the token is canceled. Never throws; is raised on every exit. + /// + /// Token to stop the monitor. + /// Task that completes when the monitor has stopped. + public async Task RunAsync(CancellationToken cancellationToken) + { + try + { + if (string.IsNullOrEmpty(Hostname)) + await ResolveHostnameAsync().ConfigureAwait(false); + + while (!cancellationToken.IsCancellationRequested) + { + var timestamp = DateTime.Now; + + PingInfo pingInfo; + string errorMessage = null; + + try + { + pingInfo = await _probe.ProbeAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + // E.g. a PingException while the network adapter / VPN is gone: counted as lost, keep checking + pingInfo = new PingInfo(timestamp, IPAddress, IPStatus.Unknown); + errorMessage = GetErrorMessage(ex); + } + + // One IP address instance for the whole history, with the hostname of the host + pingInfo.IPAddress = IPAddress; + pingInfo.Hostname = Hostname; + + PingReceived?.Invoke(this, new PingReceivedArgs(pingInfo, errorMessage)); + + await Task.Delay(WaitTime, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + // Canceled while waiting + } + catch (Exception ex) + { + Log.Error($"Host monitor of {IPAddress} stopped because of an unexpected error", ex); + } + finally + { + Stopped?.Invoke(this, EventArgs.Empty); + } + } + + /// + /// Resolves the PTR record of the host. A failed lookup is ignored (the host is shown without hostname). + /// + private async Task ResolveHostnameAsync() + { + try + { + var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(IPAddress).ConfigureAwait(false); + + if (dnsResult.HasError) + return; + + Hostname = dnsResult.Value; + + HostnameResolved?.Invoke(this, new HostnameArgs(Hostname)); + } + catch (Exception ex) + { + Log.Warn($"Could not resolve the PTR record of {IPAddress}", ex); + } + } + + /// + /// Message of a failed check. The message of a is generic ("An exception occurred + /// during a Ping request."), the inner exception has the reason. + /// + private static string GetErrorMessage(Exception ex) + { + return ex is PingException { InnerException: not null } ? ex.InnerException.Message : ex.Message; + } +} diff --git a/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs b/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs new file mode 100644 index 0000000000..06fd725e5b --- /dev/null +++ b/Source/NETworkManager.Models/Network/ICMPHostMonitorProbe.cs @@ -0,0 +1,52 @@ +using System; +using System.Net; +using System.Net.NetworkInformation; +using System.Threading; +using System.Threading.Tasks; + +namespace NETworkManager.Models.Network; + +/// +/// Checks a host with one ICMP echo request (ping) per call. +/// +public sealed class ICMPHostMonitorProbe : IHostMonitorProbe +{ + private readonly IPAddress _ipAddress; + private readonly TimeSpan _timeout; + private readonly byte[] _buffer; + private readonly PingOptions _options; + + /// + /// Creates a new ICMP probe. + /// + /// IP address of the host. + /// Time in milliseconds to wait for a reply. + /// Size of the data sent with the echo request in bytes. + /// Time to live of the echo request. + /// Don't fragment the echo request. + public ICMPHostMonitorProbe(IPAddress ipAddress, int timeout, int bufferSize, int ttl, bool dontFragment) + { + _ipAddress = ipAddress; + _timeout = TimeSpan.FromMilliseconds(timeout); + _buffer = new byte[bufferSize]; + _options = new PingOptions { Ttl = ttl, DontFragment = dontFragment }; + } + + /// + public string Name => "ICMP"; + + /// + public async Task ProbeAsync(CancellationToken cancellationToken) + { + using var ping = new System.Net.NetworkInformation.Ping(); + + var timestamp = DateTime.Now; + + var pingReply = await ping.SendPingAsync(_ipAddress, _timeout, _buffer, _options, cancellationToken) + .ConfigureAwait(false); + + return pingReply.Status == IPStatus.Success + ? PingInfo.FromSuccessfulReply(timestamp, pingReply) + : new PingInfo(timestamp, _ipAddress, pingReply.Status); + } +} diff --git a/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs b/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs new file mode 100644 index 0000000000..daec5343ad --- /dev/null +++ b/Source/NETworkManager.Models/Network/IHostMonitorProbe.cs @@ -0,0 +1,33 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace NETworkManager.Models.Network; + +/// +/// One check of a host monitored by (e.g. an ICMP echo request). The monitor calls it +/// once per interval, so a probe only has to check the host once. +/// +/// +/// Only ICMP () exists so far. Further methods (e.g. TCP connect, HTTP) are +/// planned; they return the same result type, its status is the +/// that matches the outcome (e.g. Success, TimedOut). +/// +public interface IHostMonitorProbe +{ + /// + /// Short name of the method, shown as tag next to the host (e.g. ICMP). + /// + string Name { get; } + + /// + /// Checks the host once. + /// + /// Token to stop the check (the monitor was paused or closed). + /// Result of the check (timestamp, status and round-trip time). + /// The check was canceled. + /// + /// Other exceptions (e.g. while the network adapter is + /// gone) are counted as failed check by the monitor, which keeps checking. + /// + Task ProbeAsync(CancellationToken cancellationToken); +} diff --git a/Source/NETworkManager.Models/Network/Ping.cs b/Source/NETworkManager.Models/Network/Ping.cs index b6844513d8..67a8b7d6ce 100644 --- a/Source/NETworkManager.Models/Network/Ping.cs +++ b/Source/NETworkManager.Models/Network/Ping.cs @@ -1,193 +1,12 @@ -using System; -using System.Net; -using System.Net.NetworkInformation; -using System.Threading; -using System.Threading.Tasks; -using NETworkManager.Utilities; +using System.Net.NetworkInformation; namespace NETworkManager.Models.Network; /// -/// Provides functionality to ping a network host. +/// Helpers for pings. The continuous ping of the Ping Monitor is . /// -public sealed class Ping +public static class Ping { - #region Variables - - /// - /// The time in milliseconds to wait between ping requests. Default is 1000ms. - /// - public int WaitTime = 1000; - - /// - /// The time in milliseconds to wait for a reply. Default is 4000ms. - /// - public int Timeout = 4000; - - /// - /// The size in bytes of the buffer to send with the ping request. Default is 32 bytes. - /// - public int BufferSize = 32; - - /// - /// The Time to Live (TTL) value for the ping request. Default is 64. - /// - public int TTL = 64; - - /// - /// Indicates whether to prevent fragmentation of the data packets. Default is true. - /// - public bool DontFragment = true; - - private const int ExceptionCancelCount = 3; - - #endregion - - #region Events - - /// - /// Occurs when a ping reply is received. - /// - public event EventHandler PingReceived; - - private void OnPingReceived(PingReceivedArgs e) - { - PingReceived?.Invoke(this, e); - } - - /// - /// Occurs when the ping operation is completed. - /// - public event EventHandler PingCompleted; - - private void OnPingCompleted() - { - PingCompleted?.Invoke(this, EventArgs.Empty); - } - - /// - /// Occurs when a ping exception is thrown. - /// - public event EventHandler PingException; - - private void OnPingException(PingExceptionArgs e) - { - PingException?.Invoke(this, e); - } - - /// - /// Occurs when the hostname is resolved. - /// - public event EventHandler HostnameResolved; - - private void OnHostnameResolved(HostnameArgs e) - { - HostnameResolved?.Invoke(this, e); - } - - /// - /// Occurs when the user has canceled the operation. - /// - public event EventHandler UserHasCanceled; - - private void OnUserHasCanceled() - { - UserHasCanceled?.Invoke(this, EventArgs.Empty); - } - - #endregion - - #region Methods - - /// - /// Sends ping requests to the specified IP address asynchronously. - /// - /// The IP address to ping. - /// The token to monitor for cancellation requests. - public void SendAsync(IPAddress ipAddress, CancellationToken cancellationToken) - { - Task.Run(async () => - { - var hostname = string.Empty; - - // Try to resolve PTR - var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(ipAddress); - - if (!dnsResult.HasError) - { - hostname = dnsResult.Value; - - OnHostnameResolved(new HostnameArgs(hostname)); - } - - var errorCount = 0; - - var buffer = new byte[BufferSize]; - - var options = new PingOptions - { - Ttl = TTL, - DontFragment = DontFragment - }; - - using (var ping = new System.Net.NetworkInformation.Ping()) - { - do - { - try - { - // Get timestamp - var timestamp = DateTime.Now; - - // Send ping - var pingReply = ping.Send(ipAddress, Timeout, buffer, options); - - // Reset the error count (if no exception was thrown) - errorCount = 0; - - if (pingReply is not { Status: IPStatus.Success }) - { - if (pingReply != null) - OnPingReceived(new PingReceivedArgs( - new PingInfo(timestamp, pingReply.Address, hostname, pingReply.Status))); - } - else - { - OnPingReceived(new PingReceivedArgs( - PingInfo.FromSuccessfulReply(timestamp, pingReply, hostname))); - } - } - catch (PingException ex) - { - errorCount++; - - if (errorCount == ExceptionCancelCount) - { - OnPingException(new PingExceptionArgs(ex.Message, ex.InnerException)); - - break; - } - } - - // If ping is canceled... dont wait for example 5 seconds - for (var i = 0; i < WaitTime; i += 100) - { - Thread.Sleep(100); - - if (cancellationToken.IsCancellationRequested) - break; - } - } while (!cancellationToken.IsCancellationRequested); - } - - if (cancellationToken.IsCancellationRequested) - OnUserHasCanceled(); - // Currently not used (ping will run until the user cancels it) - else - OnPingCompleted(); - }, cancellationToken); - } - /// /// Converts the ping time to a string representation (e.g. <1 ms, 4 ms), -/- without a /// reply. @@ -202,6 +21,4 @@ public static string TimeToString(IPStatus status, long time) return time == 0 ? "<1 ms" : $"{time} ms"; } - - #endregion -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Network/PingExceptionArgs.cs b/Source/NETworkManager.Models/Network/PingExceptionArgs.cs deleted file mode 100644 index 3783a1560a..0000000000 --- a/Source/NETworkManager.Models/Network/PingExceptionArgs.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace NETworkManager.Models.Network; - -public class PingExceptionArgs : EventArgs -{ - public PingExceptionArgs(string message, Exception innerException) - { - Message = message; - InnerException = innerException; - } - - public string Message { get; set; } - public Exception InnerException { get; set; } -} \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/PingMonitorHistory.cs b/Source/NETworkManager.Models/Network/PingMonitorHistory.cs new file mode 100644 index 0000000000..c3f263d880 --- /dev/null +++ b/Source/NETworkManager.Models/Network/PingMonitorHistory.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace NETworkManager.Models.Network; + +/// +/// History of the pings of a host in the Ping Monitor (export, chart after "Live"), limited by age. +/// +public static class PingMonitorHistory +{ + /// + /// Removes the pings older than . To avoid copying the list on every ping, the pings are + /// only removed once the oldest one is 1 % of too old (e.g. about every 15 minutes for + /// 24 hours), then all outdated pings at once. + /// + /// Pings, the oldest first. + /// Current time. + /// Maximum age of a ping. + /// Number of removed pings. + public static int Trim(List history, DateTime now, TimeSpan maxAge) + { + if (history.Count == 0) + return 0; + + var cutoff = now - maxAge; + + if (history[0].Timestamp >= cutoff - maxAge / 100) + return 0; + + var count = 0; + + while (count < history.Count && history[count].Timestamp < cutoff) + count++; + + history.RemoveRange(0, count); + + return count; + } +} diff --git a/Source/NETworkManager.Models/Network/PingReceivedArgs.cs b/Source/NETworkManager.Models/Network/PingReceivedArgs.cs index 1506cb2c68..c40d7d5315 100644 --- a/Source/NETworkManager.Models/Network/PingReceivedArgs.cs +++ b/Source/NETworkManager.Models/Network/PingReceivedArgs.cs @@ -3,21 +3,29 @@ namespace NETworkManager.Models.Network; /// -/// Contains the information of a received ping in a . +/// Contains the result of a check of a . /// public class PingReceivedArgs : EventArgs { /// /// Creates a new instance of with the given . /// - /// - public PingReceivedArgs(PingInfo args) + /// Result of the check. + /// Message if the check failed with an error (e.g. no network), otherwise null. + public PingReceivedArgs(PingInfo args, string errorMessage = null) { Args = args; + ErrorMessage = errorMessage; } /// /// Ping information. /// public PingInfo Args { get; } -} \ No newline at end of file + + /// + /// Message if the check failed with an error (status ), + /// otherwise null. + /// + public string ErrorMessage { get; } +} diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs index ab0de0ef02..7123a0c78d 100644 --- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs +++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs @@ -313,8 +313,16 @@ public static class GlobalStaticConfiguration public static int PingMonitor_WaitTime => 1000; // ms public static bool PingMonitor_ExpandHostView => false; public static int PingMonitor_ChartTime => 120; // s + public static int PingMonitor_HistoryHours => 24; // h public static ExportFileType PingMonitor_ExportFileType => ExportFileType.Csv; + /// + /// Every host is pinged continuously and has its own chart: ask before adding many hosts at once and refuse + /// even more (e.g. a /16 subnet). + /// + public static long PingMonitor_ConfirmHostCount => 256; + public static long PingMonitor_MaxHostCount => 4096; + // Ping Monitor (notifications) public static bool PingMonitor_ShowNotificationPopup => true; public static bool PingMonitor_NotificationSound => false; diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs index 53b8196a49..02803bb418 100644 --- a/Source/NETworkManager.Settings/SettingsInfo.cs +++ b/Source/NETworkManager.Settings/SettingsInfo.cs @@ -2363,6 +2363,22 @@ public int PingMonitor_ChartTime } } = GlobalStaticConfiguration.PingMonitor_ChartTime; + /// + /// Hours the pings of a host are kept in the history (export, chart after "Live"). + /// + public int PingMonitor_HistoryHours + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } = GlobalStaticConfiguration.PingMonitor_HistoryHours; + public bool PingMonitor_ShowNotificationPopup { get; diff --git a/Source/NETworkManager.Tests/Network/PingMonitorHistoryTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorHistoryTests.cs new file mode 100644 index 0000000000..62b0d6c2a7 --- /dev/null +++ b/Source/NETworkManager.Tests/Network/PingMonitorHistoryTests.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using NETworkManager.Models.Network; +using Xunit; + +namespace NETworkManager.Tests.Network; + +public class PingMonitorHistoryTests +{ + private static readonly DateTime Now = new(2026, 11, 29, 12, 0, 0); + + private static List History(params int[] minutesAgo) => + minutesAgo.Select(x => new PingInfo(Now.AddMinutes(-x), IPAddress.Loopback, IPStatus.Success)).ToList(); + + [Fact] + public void EmptyHistoryIsKept() + { + var history = new List(); + + Assert.Equal(0, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + } + + [Fact] + public void PingsWithinTheLimitAreKept() + { + var history = History(59, 30, 0); + + Assert.Equal(0, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Equal(3, history.Count); + } + + [Fact] + public void SlightlyOutdatedPingsAreRemovedLater() + { + // 1 % of an hour = 36 seconds - the list isn't copied for every ping + var history = History(60, 30, 0); + history[0].Timestamp = Now.AddHours(-1).AddSeconds(-20); + + Assert.Equal(0, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Equal(3, history.Count); + } + + [Fact] + public void AllOutdatedPingsAreRemovedInOrder() + { + var history = History(120, 90, 61, 59, 0); + + Assert.Equal(3, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Equal([Now.AddMinutes(-59), Now], history.Select(x => x.Timestamp)); + } + + [Fact] + public void AllPingsCanBeRemoved() + { + var history = History(180, 120); + + Assert.Equal(2, PingMonitorHistory.Trim(history, Now, TimeSpan.FromHours(1))); + Assert.Empty(history); + } +} diff --git a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs index 8409ed640a..1ba3efc0a7 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs @@ -1,3 +1,4 @@ +using log4net; using NETworkManager.Controls; using NETworkManager.Converters; using NETworkManager.Localization.Resources; @@ -30,6 +31,8 @@ public class PingMonitorHostViewModel : ProfileHostViewModelBase { #region Variables + private static readonly ILog Log = LogManager.GetLogger(typeof(PingMonitorHostViewModel)); + private CancellationTokenSource _cancellationTokenSource; private string _group = Strings.Hosts; // Default group name @@ -339,6 +342,42 @@ private void AddStatusMessage(string message, StatusLevel level) /// public async Task Start() { + // Every host is pinged continuously and has its own chart - ask before adding many hosts and refuse a too + // large input (e.g. a /16 subnet) instead of freezing the application + long hostCount; + + try + { + hostCount = HostRangeHelper.GetHostCount(HostRangeHelper.CreateListFromInput(Host)); + } + catch (Exception ex) + { + Log.Error("Error while counting the hosts", ex); + + StatusMessage = ex.Message; + StatusMessageLevel = StatusLevel.Error; + IsStatusMessageDisplayed = true; + + return; + } + + if (hostCount > GlobalStaticConfiguration.PingMonitor_MaxHostCount) + { + StatusMessage = string.Format(Strings.PingMonitorTooManyHostsMessage, hostCount.ToString("N0"), + GlobalStaticConfiguration.PingMonitor_MaxHostCount.ToString("N0")); + StatusMessageLevel = StatusLevel.Error; + IsStatusMessageDisplayed = true; + + return; + } + + // The ping command can't be executed while the dialog is open (Ping_CanExecute) + if (hostCount > GlobalStaticConfiguration.PingMonitor_ConfirmHostCount && + !await DialogHelper.ShowConfirmationMessageAsync(Application.Current.MainWindow, Strings.PingMonitor, + string.Format(Strings.PingMonitorManyHostsMessage, hostCount.ToString("N0")), ChildWindowIcon.Warn, + Strings.Add)) + return; + IsStatusMessageDisplayed = false; IsRunning = true; @@ -486,18 +525,15 @@ private void Hosts_CollectionChanged(object sender, NotifyCollectionChangedEvent /// changes, so the per-group up/down summary re-evaluates. /// /// - /// / - /// are updated directly from each host's background ping loop (not marshaled to the UI - /// thread), so this handler can be invoked concurrently for multiple hosts. The increment - /// is marshaled to the UI thread so it's never lost - and never silently suppressed by the - /// property setter's equality check - to a concurrent write from another host. + /// The state of a host is only changed on the UI thread (see + /// ), so this handler is never called concurrently. /// private void HostViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName is not (nameof(PingMonitorViewModel.IsReachable) or nameof(PingMonitorViewModel.IsRunning))) return; - Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => HostsChangeVersion++); + HostsChangeVersion++; } #endregion diff --git a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs index f3692fbaa7..f862d0f26b 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorSettingsViewModel.cs @@ -144,6 +144,25 @@ public int ChartTime } } + /// + /// Gets or sets the hours the pings of a host are kept in the history. + /// + public int HistoryHours + { + get; + set + { + if (value == field) + return; + + if (!_isLoading) + SettingsManager.Current.PingMonitor_HistoryHours = value; + + field = value; + OnPropertyChanged(); + } + } + /// /// Gets or sets a value indicating whether a notification popup is shown on status change. /// @@ -264,6 +283,7 @@ private void LoadSettings() WaitTime = SettingsManager.Current.PingMonitor_WaitTime; ExpandHostView = SettingsManager.Current.PingMonitor_ExpandHostView; ChartTime = SettingsManager.Current.PingMonitor_ChartTime; + HistoryHours = SettingsManager.Current.PingMonitor_HistoryHours; ShowNotificationPopup = SettingsManager.Current.PingMonitor_ShowNotificationPopup; NotificationSound = SettingsManager.Current.PingMonitor_NotificationSound; NotificationSuccessThreshold = SettingsManager.Current.PingMonitor_NotificationSuccessThreshold; diff --git a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs index 5ea49d17c2..5663ff6eba 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs @@ -66,6 +66,7 @@ public PingMonitorViewModel(Guid hostId, Action removeHostByGuid, private static readonly ILog Log = LogManager.GetLogger(typeof(PingMonitorViewModel)); private CancellationTokenSource _cancellationTokenSource; + private HostMonitor _hostMonitor; private int _maxPingValues; private int _sessionId; private bool _updatingAxisFromCode; @@ -404,7 +405,8 @@ private set } /// - /// Gets the error message if an error occurs. + /// Gets the error message of the last ping, if it failed with an error (e.g. no network). Cleared by the next ping + /// without an error. /// public string ErrorMessage { @@ -420,7 +422,7 @@ private set } /// - /// Gets or sets a value indicating whether the error message is displayed. + /// Gets or sets a value indicating whether the error message is displayed (instead of the status icon). /// public bool IsErrorMessageDisplayed { @@ -523,7 +525,12 @@ private void GoLiveAction() /// public void Start() { + // The previous run must have ended (Stopped) - otherwise two loops would update this host + if (IsRunning) + return; + IsErrorMessageDisplayed = false; + ErrorMessage = null; IsRunning = true; IsLiveMode = true; @@ -556,21 +563,21 @@ public void Start() UpdateMaxPingValues(); - var ping = new Ping + var probe = new ICMPHostMonitorProbe(IPAddress, SettingsManager.Current.PingMonitor_Timeout, + GlobalStaticConfiguration.LimitICMPBuffer(SettingsManager.Current.PingMonitor_Buffer), + SettingsManager.Current.PingMonitor_TTL, SettingsManager.Current.PingMonitor_DontFragment); + + // The known hostname (typed, from DNS or resolved before) is kept, the PTR record is only resolved without one + _hostMonitor = new HostMonitor(IPAddress, Hostname, probe) { - Timeout = SettingsManager.Current.PingMonitor_Timeout, - BufferSize = GlobalStaticConfiguration.LimitICMPBuffer(SettingsManager.Current.PingMonitor_Buffer), - TTL = SettingsManager.Current.PingMonitor_TTL, - DontFragment = SettingsManager.Current.PingMonitor_DontFragment, WaitTime = SettingsManager.Current.PingMonitor_WaitTime }; - ping.PingReceived += Ping_PingReceived; - ping.PingException += Ping_PingException; - ping.HostnameResolved += Ping_HostnameResolved; - ping.UserHasCanceled += Ping_UserHasCanceled; + _hostMonitor.PingReceived += HostMonitor_PingReceived; + _hostMonitor.HostnameResolved += HostMonitor_HostnameResolved; + _hostMonitor.Stopped += HostMonitor_Stopped; - ping.SendAsync(IPAddress, _cancellationTokenSource.Token); + _hostMonitor.Start(_cancellationTokenSource.Token); } /// @@ -662,11 +669,29 @@ await DialogHelper.ShowMessageAsync(Application.Current.MainWindow, Strings.Erro #region Events /// - /// Handles the PingReceived event. Updates statistics and the chart. + /// Handles the PingReceived event (thread pool thread): the ping is processed on the UI thread, where every state of + /// this host is changed (statistics, status, history, chart), so nothing is changed concurrently. + /// + /// The host monitor that sent the ping. + /// The instance containing the event data. + private void HostMonitor_PingReceived(object sender, PingReceivedArgs e) + { + // Null exception may occur when the application is closing + Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => + { + // A late ping of a previous run (or of a closed host) + if (!ReferenceEquals(sender, _hostMonitor)) + return; + + OnPingReceived(e); + }); + } + + /// + /// Updates statistics, status, history and the chart with a ping. Runs on the UI thread. /// - /// The source of the event. /// The instance containing the event data. - private void Ping_PingReceived(object sender, PingReceivedArgs e) + private void OnPingReceived(PingReceivedArgs e) { // Calculate statistics Transmitted++; @@ -742,67 +767,63 @@ private void Ping_PingReceived(object sender, PingReceivedArgs e) PacketLoss = Math.Round((double)Lost / Transmitted * 100, 2); TimeMs = e.Args.Time; - // Null exception may occur when the application is closing - var capturedSession = _sessionId; - Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => - { - if (_sessionId != capturedSession) - return; - - // Add to history - on the UI thread, like every other access to it (export, GoLiveAction) - _pingInfoList.Add(e.Args); - - // While the user is inspecting the chart (zoomed/panned, i.e. not live), keep - // the chart frozen: ignore new samples here so the view does not move and the - // buffer does not grow. The sample is still recorded in the history above and - // becomes visible again when the user returns to live mode (see GoLiveAction). - if (!IsLiveMode) - return; + // A ping that failed with an error (e.g. no network) is counted as lost, the host keeps being pinged. The error + // is shown (status icon tooltip) until a ping works again. + ErrorMessage = e.ErrorMessage; + IsErrorMessageDisplayed = e.ErrorMessage != null; + + // Add to history, limited by age (PingMonitor_HistoryHours) + _pingInfoList.Add(e.Args); + PingMonitorHistory.Trim(_pingInfoList, DateTime.Now, + TimeSpan.FromHours(SettingsManager.Current.PingMonitor_HistoryHours)); + + // While the user is inspecting the chart (zoomed/panned, i.e. not live), keep + // the chart frozen: ignore new samples here so the view does not move and the + // buffer does not grow. The sample is still recorded in the history above and + // becomes visible again when the user returns to live mode (see GoLiveAction). + if (!IsLiveMode) + return; - _pingValues.Add(timeInfo); - if (_pingValues.Count > _maxPingValues) - _pingValues.RemoveAt(0); + _pingValues.Add(timeInfo); + if (_pingValues.Count > _maxPingValues) + _pingValues.RemoveAt(0); - UpdateXAxisWindow(timeInfo.DateTime); - UpdateYAxis(); - }); + UpdateXAxisWindow(timeInfo.DateTime); + UpdateYAxis(); } /// - /// Handles the UserHasCanceled event. Stops the monitoring. + /// Handles the Stopped event of the host monitor (paused, closed or an unexpected error). /// - /// The source of the event. + /// The host monitor that stopped. /// The instance containing the event data. - private void Ping_UserHasCanceled(object sender, EventArgs e) + private void HostMonitor_Stopped(object sender, EventArgs e) { - IsRunning = false; - } - - /// - /// Handles the HostnameResolved event. Updates the hostname and title if necessary. - /// - /// The source of the event. - /// The instance containing the event data. - private void Ping_HostnameResolved(object sender, HostnameArgs e) - { - // Update title if name was not set in the constructor - if (string.IsNullOrEmpty(Hostname)) - Title = $"{DNSClientHelper.SanitizeHostname(e.Hostname)} # {IPAddress}"; + // After the pings of this run (same priority, processed in order) + Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => + { + if (!ReferenceEquals(sender, _hostMonitor)) + return; - Hostname = e.Hostname; + IsRunning = false; + }); } /// - /// Handles the PingException event. Stops the monitoring and displays the error. + /// Handles the HostnameResolved event (only raised without a known hostname). Updates the hostname and title. /// - /// The source of the event. - /// The instance containing the event data. - private void Ping_PingException(object sender, PingExceptionArgs e) + /// The host monitor that resolved the hostname. + /// The instance containing the event data. + private void HostMonitor_HostnameResolved(object sender, HostnameArgs e) { - IsRunning = false; + Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, () => + { + if (!ReferenceEquals(sender, _hostMonitor)) + return; - ErrorMessage = e.Message; - IsErrorMessageDisplayed = true; + Title = $"{DNSClientHelper.SanitizeHostname(e.Hostname)} # {IPAddress}"; + Hostname = e.Hostname; + }); } /// diff --git a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml index 8e0a388a1e..4578ea4b25 100644 --- a/Source/NETworkManager/Views/PingMonitorSettingsView.xaml +++ b/Source/NETworkManager/Views/PingMonitorSettingsView.xaml @@ -29,6 +29,19 @@ + + + + + + @@ -77,6 +161,7 @@ + @@ -200,7 +285,95 @@ Visibility="{Binding Path=IsStatusMessageDisplayed, Converter={StaticResource ResourceKey=BooleanToVisibilityCollapsedConverter}}" Margin="0,10,0,0" /> - + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -247,6 +425,9 @@ RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type TypeName=ItemsControl}}" /> + @@ -267,6 +448,9 @@ RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type TypeName=ItemsControl}}" /> + @@ -288,6 +472,9 @@ RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type TypeName=ItemsControl}}" /> + @@ -298,6 +485,11 @@ + + @@ -331,48 +523,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -393,7 +544,12 @@ - + + /// + /// Restores the state of a group (expanded / collapsed by the user): the group containers are created again when + /// the hosts are filtered. + /// + private void GroupExpander_Loaded(object sender, RoutedEventArgs e) + { + if (sender is Expander { Tag: { } group } expander) + expander.IsExpanded = _viewModel.IsGroupExpanded(group.ToString()); + } + + private void GroupExpander_Expanded(object sender, RoutedEventArgs e) + { + // Only the group itself, not the expander of a host inside it (routed event) + if (ReferenceEquals(e.OriginalSource, sender) && sender is Expander { Tag: { } group }) + _viewModel.SetGroupExpanded(group.ToString(), true); + } + + private void GroupExpander_Collapsed(object sender, RoutedEventArgs e) + { + if (ReferenceEquals(e.OriginalSource, sender) && sender is Expander { Tag: { } group }) + _viewModel.SetGroupExpanded(group.ToString(), false); + } + private void GroupActionsButton_Click(object sender, RoutedEventArgs e) { var button = (Button)sender; diff --git a/Website/docs/application/ping-monitor.md b/Website/docs/application/ping-monitor.md index 2a78aa460e..8045bca5e8 100644 --- a/Website/docs/application/ping-monitor.md +++ b/Website/docs/application/ping-monitor.md @@ -55,18 +55,35 @@ You can interact with the chart to inspect past results: When you zoom or pan, the chart leaves live mode and stops scrolling. A **Live** button then appears in the top-right corner of the chart — click it to return to live mode and resume auto-scrolling. +### Toolbar + +Above the monitored hosts: + +| Element | Description | +| ------- | ----------- | +| **Search** | Shows only the hosts whose title, IP address, hostname or group contains the text | +| Status filter | **All**, **Up**, **Down** or **Paused** hosts (e.g. only the hosts that are down). A host that was just added (pending) is only shown with **All**. The list is updated when a host changes its status. | +| Summary | Number of all hosts and how many are up, down and paused | +| **Expand all** / **Collapse all** | Expands or collapses the charts of the shown hosts (the setting [Expand host view](#expand-host-view) is the default for new hosts) | +| **Resume all** / **Pause all** / **Close all** | Resumes, pauses or closes all hosts (also the hidden ones). **Close all** asks for confirmation if more than one host is monitored. | + +The search and the status filter only hide hosts: hidden hosts keep being pinged and notified, and the group header counts all hosts of the group. + ### Groups Hosts are grouped by their profile group (or **Hosts** if none is set). Each group header shows a live count of hosts that are up, down and paused (**Paused** is only shown while at least one host in the group is paused). A host that was just added or resumed is pending (gray icon) and counted neither as up nor as down until its status is established by the [Success threshold](#success-threshold) / [Failure threshold](#failure-threshold). -Click/tap the **⋮** icon on the right of a group header to open its action menu: +Click/tap the **⋮** icon on the right of a group header, or right-click the group header, to open its action menu: | Action | Description | |--------|-------------| | **Start** | Starts every host in the group that isn't currently running | | **Pause** | Pauses every host in the group that's currently running | +| **Expand all** / **Collapse all** | Expands or collapses the charts of the shown hosts of the group | | **Close** | Stops and removes every host in the group | +A collapsed group stays collapsed while the hosts are filtered. + ### Context menu Right-click a monitored host (anywhere except the chart) to open the context menu: diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 779965acb5..54f27b16c4 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -100,6 +100,8 @@ Release date: **xx.xx.2026** - Status changes of several hosts within one second (e.g. an uplink outage) are shown as one notification instead of one per host: up to three hosts one per line (`10.0.0.5 (server) · Down`), otherwise the counters (e.g. `12 Down`), with the group as title if all hosts are in the same group. A host that goes down and up again within this second is not notified. The sound is played once per notification. See [Notifications](../application/ping-monitor.md#notifications). - New actions in the context menu of a host: **Pause** / **Resume**, **Close** and open the host (hostname, otherwise IP address) in **Port Scanner**, **Traceroute**, **DNS Lookup**, **Remote Desktop**, **PowerShell**, **PuTTY** and **TigerVNC**. See [Context menu](../application/ping-monitor.md#context-menu). - Minimum, average and maximum round-trip time and the jitter of all replies since the host was started: in the tooltip of the counters (received, lost, packet loss) and in **Copy**. +- New toolbar above the hosts: **Search** (title, IP address, hostname, group), a status filter (**All** / **Up** / **Down** / **Paused**, e.g. to show only the hosts that are down; updated when a host changes its status), a summary of all hosts (e.g. `12 Hosts · 10 Up · 1 Down · 1 Paused`) and buttons to expand / collapse the charts of the shown hosts and to resume, pause or close all hosts (with a confirmation for more than one host). Hidden hosts keep being pinged and notified; the group header counts all hosts of the group. See [Toolbar](../application/ping-monitor.md#toolbar). +- The actions of a group (**Start** / **Pause** / **Close group**, new: expand / collapse the charts of its hosts) also open with a right-click on the group header. A collapsed group stays collapsed when the hosts are filtered. ## Bug Fixes **Tabs** From a517757565911187bbc7b5fd8f342c4f276d59ac Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 29 Nov 2026 01:48:46 +0100 Subject: [PATCH 06/17] Ping Monitor: drop unused session id, ignore events after a host is closed Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/ViewModels/PingMonitorViewModel.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs index cd1ca88a5f..5be6ff7f03 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs @@ -68,7 +68,6 @@ public PingMonitorViewModel(Guid hostId, Action removeHostByGuid, private CancellationTokenSource _cancellationTokenSource; private HostMonitor _hostMonitor; private int _maxPingValues; - private int _sessionId; private bool _updatingAxisFromCode; public readonly Guid HostId; @@ -622,8 +621,6 @@ public void Start() IsRunning = true; IsLiveMode = true; - _sessionId++; - // Reset history _pingInfoList = []; @@ -886,6 +883,9 @@ private void HostMonitor_HostnameResolved(object sender, HostnameArgs e) /// public void Cleanup() { + // Late events of the (stopped) monitor are ignored + _hostMonitor = null; + SettingsManager.Current.PropertyChanged -= SettingsManager_PropertyChanged; AppearanceManager.ThemeResourcesChanged -= AppearanceManager_ThemeResourcesChanged; } From 0e2cd93869399913edd232616d54f166e9ce29c3 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 29 Nov 2026 02:05:43 +0100 Subject: [PATCH 07/17] Ping Monitor: header like the other tools, status check boxes, summaries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Header "Monitored hosts" (like the result header of the other tools): Up / Down / Paused check boxes (like the WiFi bands) and search on the right, actions for all hosts in a ⋮ menu with text (same pattern as the groups) instead of five icon buttons. - Same summary below the header and in every group header: "x Hosts · ● x Up · ● x Down · ● x Paused" with status dots, zeros shown (converter: "Hosts", no "PausedVisibility" anymore). - PingMonitorHostFilter: three flags instead of PingMonitorStatusFilter; pending hosts are shown with Up or Down (+ tests). Co-Authored-By: Claude Opus 5.5 --- .../PingMonitorGroupSummaryConverter.cs | 15 +- .../Resources/Strings.Designer.cs | 18 + .../Resources/Strings.resx | 6 + .../Network/PingMonitorHostFilter.cs | 56 +-- .../PingMonitorGroupSummaryConverterTests.cs | 9 +- .../Network/PingMonitorHostFilterTests.cs | 27 +- .../ViewModels/PingMonitorHostViewModel.cs | 118 ++++++- .../Views/PingMonitorHostView.xaml | 333 ++++++++++-------- .../Views/PingMonitorHostView.xaml.cs | 4 +- Website/docs/application/ping-monitor.md | 16 +- Website/docs/changelog/next-release.md | 2 +- 11 files changed, 372 insertions(+), 232 deletions(-) diff --git a/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs b/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs index b8c874ed10..b2cb5d9c7d 100644 --- a/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs +++ b/Source/NETworkManager.Converters/PingMonitorGroupSummaryConverter.cs @@ -2,18 +2,16 @@ using System.Collections; using System.Globalization; using System.Linq; -using System.Windows; using System.Windows.Data; using NETworkManager.Models.Network; namespace NETworkManager.Converters; /// -/// Formats the count of hosts up (reachable), down (unreachable) or paused (not running) within -/// a Ping Monitor group, selected via ConverterParameter ("Up", "Down", "Paused" - formats the +/// Formats the count of all hosts, the hosts up (reachable), down (unreachable) or paused (not running) within +/// a Ping Monitor group, selected via ConverterParameter ("Hosts", "Up", "Down", "Paused" - formats the /// count with the format string bound as the third value, e.g. Strings.XUp = "{0} Up", so the -/// word order can be translated - or "PausedVisibility", which instead returns a -/// so the paused count can be hidden while zero). +/// word order can be translated). Pending hosts (status not established yet) are only counted in "Hosts". /// /// /// Bound as a with the as the first @@ -28,8 +26,9 @@ public sealed class PingMonitorGroupSummaryConverter : IMultiValueConverter public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values.Length == 0 || values[0] is not CollectionViewGroup group) - return parameter as string == "PausedVisibility" ? Visibility.Collapsed : string.Empty; + return string.Empty; + var total = 0; var up = 0; var down = 0; var paused = 0; @@ -42,6 +41,8 @@ public object Convert(object[] values, Type targetType, object parameter, Cultur foreach (var host in hosts) { + total++; + if (!host.IsRunning) paused++; else if (host.IsPending) @@ -56,10 +57,10 @@ public object Convert(object[] values, Type targetType, object parameter, Cultur return parameter as string switch { + "Hosts" => string.Format(culture, format, total), "Up" => string.Format(culture, format, up), "Down" => string.Format(culture, format, down), "Paused" => string.Format(culture, format, paused), - "PausedVisibility" => paused > 0 ? Visibility.Visible : Visibility.Collapsed, _ => string.Empty }; } diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index cb3bfbda55..ef68b9570c 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -429,6 +429,15 @@ public static string Action { } } + /// + /// Looks up a localized string similar to Actions. + /// + public static string Actions { + get { + return ResourceManager.GetString("Actions", resourceCulture); + } + } + /// /// Looks up a localized string similar to Active connections. /// @@ -9203,6 +9212,15 @@ public static string Model { } } + /// + /// Looks up a localized string similar to Monitored hosts. + /// + public static string MonitoredHosts { + get { + return ResourceManager.GetString("MonitoredHosts", resourceCulture); + } + } + /// /// Looks up a localized string similar to Move. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index 3d06bc39aa..e0cd7f8828 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -5948,4 +5948,10 @@ Do you want to add the hosts? Do you want to close all hosts? + + Monitored hosts + + + Actions + diff --git a/Source/NETworkManager.Models/Network/PingMonitorHostFilter.cs b/Source/NETworkManager.Models/Network/PingMonitorHostFilter.cs index 5bffd93110..3e5d66cc9f 100644 --- a/Source/NETworkManager.Models/Network/PingMonitorHostFilter.cs +++ b/Source/NETworkManager.Models/Network/PingMonitorHostFilter.cs @@ -4,34 +4,8 @@ namespace NETworkManager.Models.Network; /// -/// Status filter of the hosts in the Ping Monitor. -/// -public enum PingMonitorStatusFilter -{ - /// - /// All hosts. - /// - All, - - /// - /// Running hosts that are up. - /// - Up, - - /// - /// Running hosts that are down. - /// - Down, - - /// - /// Paused hosts. - /// - Paused -} - -/// -/// Filter of the hosts shown in the Ping Monitor (search and status). Only the display is filtered: hidden hosts -/// keep being pinged and notified. +/// Filter of the hosts shown in the Ping Monitor (status check boxes and search). Only the display is filtered: +/// hidden hosts keep being pinged and notified. /// public static class PingMonitorHostFilter { @@ -39,21 +13,27 @@ public static class PingMonitorHostFilter /// Checks whether a host is shown. /// /// Status of the host. - /// Status filter. A pending host (status not established yet) is only shown for All. + /// Show the running hosts that are up. + /// Show the running hosts that are down. + /// Show the paused hosts. /// Search text, null or empty for all hosts. /// Searched values of the host (e.g. title, IP address, hostname, group), null values are /// skipped. /// True if the host is shown. - public static bool Matches(IPingMonitorHostStatus host, PingMonitorStatusFilter statusFilter, string search, - params string[] values) + /// + /// A pending host (running, status not established yet) is shown with up or down, so a host that was just + /// added doesn't disappear until its status is known. + /// + public static bool Matches(IPingMonitorHostStatus host, bool showUp, bool showDown, bool showPaused, + string search, params string[] values) { - var statusMatches = statusFilter switch - { - PingMonitorStatusFilter.Up => host.IsRunning && !host.IsPending && host.IsReachable, - PingMonitorStatusFilter.Down => host.IsRunning && !host.IsPending && !host.IsReachable, - PingMonitorStatusFilter.Paused => !host.IsRunning, - _ => true - }; + var statusMatches = !host.IsRunning + ? showPaused + : host.IsPending + ? showUp || showDown + : host.IsReachable + ? showUp + : showDown; if (!statusMatches) return false; diff --git a/Source/NETworkManager.Tests/Converters/PingMonitorGroupSummaryConverterTests.cs b/Source/NETworkManager.Tests/Converters/PingMonitorGroupSummaryConverterTests.cs index d2bf302968..ffb89a40f2 100644 --- a/Source/NETworkManager.Tests/Converters/PingMonitorGroupSummaryConverterTests.cs +++ b/Source/NETworkManager.Tests/Converters/PingMonitorGroupSummaryConverterTests.cs @@ -1,6 +1,5 @@ using System; using System.Globalization; -using System.Windows; using System.Windows.Data; using NETworkManager.Converters; using NETworkManager.Models.Network; @@ -32,6 +31,7 @@ private static void SkipUnlessWindows() } [Theory] + [InlineData("Hosts", "5")] [InlineData("Up", "2")] [InlineData("Down", "1")] [InlineData("Paused", "1")] @@ -42,13 +42,6 @@ public void CountsTheHostsOfTheGroup(string parameter, string expected) Assert.Equal(expected, Convert(parameter)); } - [Fact] - public void PausedIsVisibleWithPausedHosts() - { - SkipUnlessWindows(); - - Assert.Equal(Visibility.Visible, Convert("PausedVisibility")); - } [Fact] public void CountsAllHostsOfTheGroupAlsoIfFiltered() diff --git a/Source/NETworkManager.Tests/Network/PingMonitorHostFilterTests.cs b/Source/NETworkManager.Tests/Network/PingMonitorHostFilterTests.cs index 5e929c972c..3ba5da1d55 100644 --- a/Source/NETworkManager.Tests/Network/PingMonitorHostFilterTests.cs +++ b/Source/NETworkManager.Tests/Network/PingMonitorHostFilterTests.cs @@ -13,16 +13,20 @@ private sealed record Host(string Group, bool IsRunning, bool IsPending, bool Is private static readonly Host Paused = new("a", false, false, true); [Theory] - [InlineData(PingMonitorStatusFilter.All, true, true, true, true)] - [InlineData(PingMonitorStatusFilter.Up, true, false, false, false)] - [InlineData(PingMonitorStatusFilter.Down, false, true, false, false)] - [InlineData(PingMonitorStatusFilter.Paused, false, false, false, true)] - public void StatusFilter(PingMonitorStatusFilter filter, bool up, bool down, bool pending, bool paused) + // showUp, showDown, showPaused -> up, down, pending, paused shown + [InlineData(true, true, true, true, true, true, true)] + [InlineData(true, false, false, true, false, true, false)] + [InlineData(false, true, false, false, true, true, false)] + [InlineData(false, false, true, false, false, false, true)] + [InlineData(false, true, true, false, true, true, true)] + [InlineData(false, false, false, false, false, false, false)] + public void StatusFilter(bool showUp, bool showDown, bool showPaused, bool up, bool down, bool pending, + bool paused) { - Assert.Equal(up, PingMonitorHostFilter.Matches(Up, filter, null)); - Assert.Equal(down, PingMonitorHostFilter.Matches(Down, filter, null)); - Assert.Equal(pending, PingMonitorHostFilter.Matches(Pending, filter, null)); - Assert.Equal(paused, PingMonitorHostFilter.Matches(Paused, filter, null)); + Assert.Equal(up, PingMonitorHostFilter.Matches(Up, showUp, showDown, showPaused, null)); + Assert.Equal(down, PingMonitorHostFilter.Matches(Down, showUp, showDown, showPaused, null)); + Assert.Equal(pending, PingMonitorHostFilter.Matches(Pending, showUp, showDown, showPaused, null)); + Assert.Equal(paused, PingMonitorHostFilter.Matches(Paused, showUp, showDown, showPaused, null)); } [Theory] @@ -35,13 +39,12 @@ public void StatusFilter(PingMonitorStatusFilter filter, bool up, bool down, boo public void SearchIsCaseInsensitive(string search, bool expected) { Assert.Equal(expected, - PingMonitorHostFilter.Matches(Up, PingMonitorStatusFilter.All, search, "server-01", "10.0.0.1", null, - "Office")); + PingMonitorHostFilter.Matches(Up, true, true, true, search, "server-01", "10.0.0.1", null, "Office")); } [Fact] public void SearchAndStatusMustBothMatch() { - Assert.False(PingMonitorHostFilter.Matches(Up, PingMonitorStatusFilter.Down, "server", "server-01")); + Assert.False(PingMonitorHostFilter.Matches(Up, false, true, true, "server", "server-01")); } } diff --git a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs index a7e486b559..387b5f00d3 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorHostViewModel.cs @@ -87,10 +87,10 @@ public string Search } /// - /// Gets or sets the status filter (all, up, down, paused). Only the display is filtered, hidden hosts keep being - /// pinged. + /// Gets or sets a value indicating whether the hosts that are up (and pending hosts) are shown (status filter). Only the display is filtered, + /// hidden hosts keep being pinged. /// - public PingMonitorStatusFilter StatusFilter + public bool ShowUp { get; set @@ -103,7 +103,45 @@ public PingMonitorStatusFilter StatusFilter ApplyFilter(); } - } + } = true; + + /// + /// Gets or sets a value indicating whether the hosts that are down (and pending hosts) are shown (status filter). Only the display is filtered, + /// hidden hosts keep being pinged. + /// + public bool ShowDown + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + + ApplyFilter(); + } + } = true; + + /// + /// Gets or sets a value indicating whether the paused hosts are shown (status filter). Only the display is filtered, + /// hidden hosts keep being pinged. + /// + public bool ShowPaused + { + get; + set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + + ApplyFilter(); + } + } = true; /// /// Gets a value indicating whether hosts are monitored but none matches the search / status filter. @@ -122,9 +160,57 @@ private set } /// - /// Gets the summary of all hosts, e.g. "12 Hosts · 10 Up · 1 Down · 1 Paused". + /// Gets the number of monitored hosts (all hosts, also the ones hidden by the filter). /// - public string Summary + public int HostsTotal + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the number of hosts that are up (all hosts, also the ones hidden by the filter). + /// + public int HostsUp + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the number of hosts that are down (all hosts, also the ones hidden by the filter). + /// + public int HostsDown + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Gets the number of paused hosts (all hosts, also the ones hidden by the filter). + /// + public int HostsPaused { get; private set @@ -293,8 +379,9 @@ public PingMonitorHostViewModel() HostsView = CollectionViewSource.GetDefaultView(Hosts); HostsView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(PingMonitorView.Group))); HostsView.SortDescriptions.Add(new SortDescription(nameof(PingMonitorView.Group), ListSortDirection.Ascending)); - HostsView.Filter = o => o is PingMonitorView host && PingMonitorHostFilter.Matches(host, StatusFilter, Search, - host.ViewModel.Title, host.ViewModel.IPAddress.ToString(), host.ViewModel.Hostname, host.Group); + HostsView.Filter = o => o is PingMonitorView host && PingMonitorHostFilter.Matches(host, ShowUp, ShowDown, + ShowPaused, Search, host.ViewModel.Title, host.ViewModel.IPAddress.ToString(), host.ViewModel.Hostname, + host.Group); Hosts.CollectionChanged += Hosts_CollectionChanged; _searchDelay = new SearchDelay(GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan, ApplyFilter); @@ -487,7 +574,7 @@ private void UpdateIsNothingFound() } /// - /// Updates the summary of all hosts (not only the shown ones). + /// Updates the counters of all hosts (not only the shown ones). Pending hosts are counted in the total only. /// private void UpdateSummary() { @@ -507,13 +594,10 @@ private void UpdateSummary() down++; } - List parts = - [string.Format(Strings.XHosts, Hosts.Count), string.Format(Strings.XUp, up), string.Format(Strings.XDown, down)]; - - if (paused > 0) - parts.Add(string.Format(Strings.XPaused, paused)); - - Summary = string.Join(" · ", parts); + HostsTotal = Hosts.Count; + HostsUp = up; + HostsDown = down; + HostsPaused = paused; } /// @@ -826,7 +910,7 @@ or nameof(PingMonitorViewModel.IsPending))) UpdateSummary(); // Filter again (delayed) if the status decides whether the host is shown - if (StatusFilter != PingMonitorStatusFilter.All && !_statusFilterTimer.IsEnabled) + if (!(ShowUp && ShowDown && ShowPaused) && !_statusFilterTimer.IsEnabled) _statusFilterTimer.Start(); } diff --git a/Source/NETworkManager/Views/PingMonitorHostView.xaml b/Source/NETworkManager/Views/PingMonitorHostView.xaml index be4502e929..a85920fed2 100644 --- a/Source/NETworkManager/Views/PingMonitorHostView.xaml +++ b/Source/NETworkManager/Views/PingMonitorHostView.xaml @@ -17,7 +17,6 @@ xmlns:wpfHelpers="clr-namespace:NETworkManager.Utilities.WPF;assembly=NETworkManager.Utilities.WPF" xmlns:utilities="clr-namespace:NETworkManager.Utilities;assembly=NETworkManager.Utilities" xmlns:networkManager="clr-namespace:NETworkManager" - xmlns:network="clr-namespace:NETworkManager.Models.Network;assembly=NETworkManager.Models" xmlns:hostControls="clr-namespace:NETworkManager.Views.Controls" mc:Ignorable="d" d:DataContext="{d:DesignInstance viewModels:PingMonitorHostViewModel}"> @@ -285,93 +284,151 @@ Visibility="{Binding Path=IsStatusMessageDisplayed, Converter={StaticResource ResourceKey=BooleanToVisibilityCollapsedConverter}}" Margin="0,10,0,0" /> - + + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + @@ -409,96 +466,94 @@ Style="{StaticResource ResourceKey=DefaultTextBlock}" FontSize="16" FontWeight="SemiBold" VerticalAlignment="Center" /> + - + Orientation="Horizontal" + VerticalAlignment="Center"> + - + - - - + + + - + Style="{StaticResource ResourceKey=DefaultTextBlock}" + Foreground="{DynamicResource ResourceKey=MahApps.Brushes.Gray5}" + Margin="6,0,6,0" /> + + - + - - - + + + - + Style="{StaticResource ResourceKey=DefaultTextBlock}" + Foreground="{DynamicResource ResourceKey=MahApps.Brushes.Gray5}" + Margin="6,0,6,0" /> + + - + - - - + + + - - + + + + + + - - - + + + - +