diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs index 34d986226b..60163118bd 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs +++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs @@ -2170,15 +2170,6 @@ public static string CheckIPGeolocation { } } - /// - /// Looks up a localized string similar to Check is disabled!. - /// - public static string CheckIsDisabled { - get { - return ResourceManager.GetString("CheckIsDisabled", resourceCulture); - } - } - /// /// Looks up a localized string similar to Check your network adapter configuration (dns) and if your dns server is configured correctly.. /// @@ -4108,6 +4099,16 @@ public static string DNSResolver { } } + /// + /// Looks up a localized string similar to Show the DNS server that resolves your requests with edns.ip-api.com. + ///ip-api.com receives your IP address and the IP address of your DNS server.. + /// + public static string DNSResolverWidgetDisabledMessage { + get { + return ResourceManager.GetString("DNSResolverWidgetDisabledMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to DNSSEC. /// @@ -6554,7 +6555,7 @@ public static string HelpMessage_ProfileHostPlaceholder { } /// - /// Looks up a localized string similar to Public IPv4 address that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet).. + /// Looks up a localized string similar to Public IPv4 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet).. /// public static string HelpMessage_PublicIPv4Address { get { @@ -6563,7 +6564,7 @@ public static string HelpMessage_PublicIPv4Address { } /// - /// Looks up a localized string similar to Public IPv6 address that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet).. + /// Looks up a localized string similar to Public IPv6 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet).. /// public static string HelpMessage_PublicIPv6Address { get { @@ -6700,6 +6701,24 @@ public static string HelpMessage_ScanForNetBIOS { } } + /// + /// Looks up a localized string similar to Shows the widget on the dashboard. It only sends a request to ip-api.com if the check is enabled (below, in the welcome dialog or with the "Enable" button of the widget), otherwise it shows what it would request. A hidden widget sends no request.. + /// + public static string HelpMessage_ShowIPApiWidget { + get { + return ResourceManager.GetString("HelpMessage_ShowIPApiWidget", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shows the widget on the dashboard. The status window always shows the network connection.. + /// + public static string HelpMessage_ShowNetworkConnectionWidget { + get { + return ResourceManager.GetString("HelpMessage_ShowNetworkConnectionWidget", resourceCulture); + } + } + /// /// Looks up a localized string similar to Displays the status bar in the bottom-left of the WebView when hovering over a link.. /// @@ -7321,16 +7340,6 @@ public static string IPAddressToDetectLocalIPAddressBasedOnRouting { } } - /// - /// Looks up a localized string similar to ip-api.com rate limit reached (too many requests from your network)! - ///Try again in a few seconds.. - /// - public static string IPApiRateLimitMessage { - get { - return ResourceManager.GetString("IPApiRateLimitMessage", resourceCulture); - } - } - /// /// Looks up a localized string similar to IP endpoint. /// @@ -7349,6 +7358,16 @@ public static string IPGeolocation { } } + /// + /// Looks up a localized string similar to Show the location and the internet provider of your public IP address with ip-api.com. + ///ip-api.com receives your IP address (http, not encrypted).. + /// + public static string IPGeolocationWidgetDisabledMessage { + get { + return ResourceManager.GetString("IPGeolocationWidgetDisabledMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to IP range. /// @@ -9167,6 +9186,15 @@ public static string NetworkConnectionType { } } + /// + /// Looks up a localized string similar to The network connection widget and the status window use these settings to check the internet.. + /// + public static string NetworkConnectionWidgetAndStatusWindowUseTheseSettingsMessage { + get { + return ResourceManager.GetString("NetworkConnectionWidgetAndStatusWindowUseTheseSettingsMessage", resourceCulture); + } + } + /// /// Looks up a localized string similar to Network device. /// @@ -14249,6 +14277,15 @@ public static string ShowUnreachableIPAddressesAndPorts { } } + /// + /// Looks up a localized string similar to Show widget. + /// + public static string ShowWidget { + get { + return ResourceManager.GetString("ShowWidget", resourceCulture); + } + } + /// /// Looks up a localized string similar to Show window contents while dragging. /// @@ -16306,15 +16343,6 @@ public static string WideSubnet { } } - /// - /// Looks up a localized string similar to Widgets. - /// - public static string Widgets { - get { - return ResourceManager.GetString("Widgets", resourceCulture); - } - } - /// /// Looks up a localized string similar to Width. /// @@ -16749,6 +16777,15 @@ public static string XXXDisconnected { } } + /// + /// Looks up a localized string similar to {0} has no IP geolocation for "{1}" ({2}).. + /// + public static string XXXHasNoIPGeolocationForXXXReasonXXX { + get { + return ResourceManager.GetString("XXXHasNoIPGeolocationForXXXReasonXXX", resourceCulture); + } + } + /// /// Looks up a localized string similar to "{0}" is not reachable via ICMP!. /// diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx index 4f716f4d67..916fdb5aff 100644 --- a/Source/NETworkManager.Localization/Resources/Strings.resx +++ b/Source/NETworkManager.Localization/Resources/Strings.resx @@ -3086,17 +3086,14 @@ Enable profile file encryption in Settings>Profile to store credentials secur ICMPv6 - - Check is disabled! - Enter a valid IPv6 address! - Public IPv4 address that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet). + Public IPv4 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv4 address (of the network adapter that is used for the internet). - Public IPv6 address that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet). + Public IPv6 address (not the one of your computer) that is pinged to check the internet connection. The route to it is used to detect the local IPv6 address (of the network adapter that is used for the internet). Public IPv4 address @@ -3750,10 +3747,6 @@ URL: http://ip-api.com/ Check your network connection and try again in a few seconds. - - ip-api.com rate limit reached (too many requests from your network)! -Try again in a few seconds. - HTTP status code @@ -5752,9 +5745,6 @@ Do you want to start the scan? Copy all - - Widgets - All widgets are hidden. You can show them in the settings of the dashboard. @@ -5767,4 +5757,27 @@ Do you want to start the scan? Last test at {0} + + Show the location and the internet provider of your public IP address with ip-api.com. +ip-api.com receives your IP address (http, not encrypted). + + + Show the DNS server that resolves your requests with edns.ip-api.com. +ip-api.com receives your IP address and the IP address of your DNS server. + + + {0} has no IP geolocation for "{1}" ({2}). + + + Show widget + + + Shows the widget on the dashboard. The status window always shows the network connection. + + + Shows the widget on the dashboard. It only sends a request to ip-api.com if the check is enabled (below, in the welcome dialog or with the "Enable" button of the widget), otherwise it shows what it would request. A hidden widget sends no request. + + + The network connection widget and the status window use these settings to check the internet. + \ No newline at end of file diff --git a/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs b/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs index 9af49bd6a3..e6f097e87b 100644 --- a/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs +++ b/Source/NETworkManager.Models/Cloudflare/SpeedTestService.cs @@ -6,6 +6,7 @@ using System.Net; using System.Net.Http; using System.Net.Http.Headers; +using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using log4net; @@ -195,15 +196,28 @@ await TryRequestAsync(() => MeasureLatencyAsync(pings, cancellationToken), failu } var setSucceeded = false; + var setSizeFailed = false; + + // Only failures of this set decide that the size fails (not the latency probes before it, e.g. a short + // Wi-Fi drop). The failures in a row across the sets still end the test when the connection is lost + failures.ConsecutiveInSet = 0; for (var i = 0; i < measurement.Count; i++) { - var (success, (bps, durationMs)) = await TryRequestAsync(() => isDownload + var (success, sizeFailed, (bps, durationMs)) = await TryRequestAsync(() => isDownload ? MeasureDownloadAsync(measurement.Bytes, cancellationToken, liveBps => Emit(progress, SpeedTestPhase.MeasuringDownload, pings, downloadBps, uploadBps, liveBps)) - : MeasureUploadAsync(measurement.Bytes, cancellationToken), failures, cancellationToken) - .ConfigureAwait(false); + : MeasureUploadAsync(measurement.Bytes, cancellationToken), failures, cancellationToken, + () => IsServerReachableAsync(cancellationToken)).ConfigureAwait(false); + + // The server answers small requests, but requests of this size fail without a response: the remaining + // requests of the set would each wait for the timeout too + if (sizeFailed) + { + setSizeFailed = true; + break; + } if (!success) continue; @@ -237,12 +251,18 @@ await TryRequestAsync(() => MeasureLatencyAsync(pings, cancellationToken), failu if (measurement.BypassMinDuration) continue; - // All requests of the set failed (e.g. a proxy rejects uploads of this size): the larger sizes would fail too - if (!setSucceeded || + // All requests of the set failed (e.g. a proxy rejects uploads of this size), or requests of this size fail + // without a response: the larger sizes would fail too + if (!setSucceeded || setSizeFailed || SpeedTestCalculator.IsDirectionFinished(setDurations, BandwidthFinishRequestDurationMs)) finished.Add(measurement.Type); } + // Every request was rejected (e.g. a proxy answers HTTP 403): the error of the test, not an empty result with a + // warning (requests without a response end the test earlier) + if (pings.Count == 0 && downloadBps.Count == 0 && uploadBps.Count == 0 && failures.LastError != null) + ExceptionDispatchInfo.Capture(failures.LastError).Throw(); + // 3. Result return new SpeedTestResult { @@ -343,6 +363,16 @@ private sealed class RequestFailures { public int Total { get; set; } public int Consecutive { get; set; } + + /// + /// Failures in a row without a response in the current download / upload set. + /// + public int ConsecutiveInSet { get; set; } + + /// + /// Error of the last failed request (thrown if no request of the test succeeded). + /// + public Exception LastError { get; set; } } /// @@ -365,12 +395,17 @@ private static void EnsureSuccess(HttpResponseMessage response) /// /// Runs a request of the test like the official library: HTTP 429 is repeated after the delay of the server (up to - /// times), another error skips the request. After - /// failed requests in a row the error is thrown (the test ends). + /// times, then the test ends), another error skips the request. After + /// failed requests in a row without a response the error is thrown (the test ends) - unless the server still + /// answers a small request: then only this size fails (e.g. a proxy that closes the connection of large uploads + /// instead of answering HTTP 413), the rest of the set is skipped and the direction ends. /// - /// false if the request failed and was skipped. - private static async Task<(bool Success, T Value)> TryRequestAsync(Func> request, - RequestFailures failures, CancellationToken cancellationToken) + /// Checks whether the server answers (download / upload), null for the + /// latency probes (they are small requests themselves). + /// Success false if the request failed and was skipped, SizeFailed true if + /// requests of this size fail while the server answers small requests (skip the rest of the set). + private static async Task<(bool Success, bool SizeFailed, T Value)> TryRequestAsync(Func> request, + RequestFailures failures, CancellationToken cancellationToken, Func> isServerReachable = null) { for (var retry = 0;; retry++) { @@ -378,33 +413,96 @@ private static void EnsureSuccess(HttpResponseMessage response) { var value = await request().ConfigureAwait(false); failures.Consecutive = 0; + failures.ConsecutiveInSet = 0; - return (true, value); + return (true, false, value); } catch (TooManyRequestsException ex) when (retry < MaxRetries) { Log.Warn($"Speed test request rate limited (HTTP 429), retry in {ex.RetryAfter.TotalSeconds} s."); await Task.Delay(ex.RetryAfter, cancellationToken).ConfigureAwait(false); } + catch (TooManyRequestsException) + { + // Still rate limited after the retries: the next requests would be too (each waiting up to a minute + // per retry), end the test with the error + Log.Warn("Speed test request still rate limited (HTTP 429) after the retries, the test ends."); + + throw; + } catch (Exception ex) when (ex is HttpRequestException or IOException or TimeoutException) { // Canceled by the user while data was transferred: the transport may report it as an IOException cancellationToken.ThrowIfCancellationRequested(); failures.Total++; + failures.LastError = ex; if (!SpeedTestCalculator.IsConnectionFailure(ex)) + { failures.Consecutive = 0; - else if (++failures.Consecutive >= MaxConsecutiveFailedRequests) - throw; + failures.ConsecutiveInSet = 0; + } + else + { + failures.ConsecutiveInSet++; + + // Also when only the set reaches the limit (download / upload, the counter in a row was reset by + // an earlier check of the server after failed latency probes): no more timeouts of this size + if (++failures.Consecutive >= MaxConsecutiveFailedRequests || + (isServerReachable != null && failures.ConsecutiveInSet >= MaxConsecutiveFailedRequests)) + { + if (isServerReachable == null || !await isServerReachable().ConfigureAwait(false)) + throw; + + failures.Consecutive = 0; + + // The connection works. Only requests of this size failed: skip them (the set fails), otherwise + // (failures of the latency probes before) only this request is skipped + if (failures.ConsecutiveInSet >= MaxConsecutiveFailedRequests) + { + Log.Warn("Speed test requests of this size fail, but the server answers small requests.", + ex); + failures.ConsecutiveInSet = 0; + + return (false, true, default); + } + } + } Log.Warn("Speed test request failed and is skipped.", ex); - return (false, default); + return (false, false, default); } } } + /// + /// Checks whether the server answers a small request (an empty download, not measured). + /// + /// false if there is no response (e.g. the connection was lost). + private async Task IsServerReachableAsync(CancellationToken cancellationToken) + { + try + { + return await WithTimeoutAsync(async timeout => + { + using var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/__down?bytes=0"); + using var response = await _client + .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token) + .ConfigureAwait(false); + + return true; + }, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is HttpRequestException or IOException or TimeoutException) + { + cancellationToken.ThrowIfCancellationRequested(); + + return false; + } + } + private Task MeasureLatencyAsync(List pings, CancellationToken cancellationToken) { return WithTimeoutAsync(async timeout => diff --git a/Source/NETworkManager.Models/IPApi/DNSResolverResult.cs b/Source/NETworkManager.Models/IPApi/DNSResolverResult.cs index f23b2a54ab..950e42b43f 100644 --- a/Source/NETworkManager.Models/IPApi/DNSResolverResult.cs +++ b/Source/NETworkManager.Models/IPApi/DNSResolverResult.cs @@ -1,4 +1,7 @@ -namespace NETworkManager.Models.IPApi; +using System; +using System.Net.Http; + +namespace NETworkManager.Models.IPApi; /// /// Class contains the result of the DNS resolver information retrieval. @@ -15,25 +18,17 @@ public DNSResolverResult(DNSResolverInfo info) } /// - /// Create a new instance of with an error message. + /// Create a new instance of for a failed request. /// - /// Indicates if the DNS resolver information retrieval has failed. - /// Error message if the DNS resolver information retrieval has failed. - public DNSResolverResult(bool hasError, string errorMessage) + /// + /// Error of the request ( with the status code for an HTTP error). + /// + public DNSResolverResult(Exception error) { - HasError = hasError; - ErrorMessage = errorMessage; - } - - /// - /// Create a new instance of with an error message and an error code. - /// - /// Indicates if the DNS resolver information retrieval has failed. - /// Error message if the DNS resolver information retrieval has failed. - /// Error code if the DNS resolver information retrieval has failed. - public DNSResolverResult(bool hasError, string errorMessage, int errorCode) : this(hasError, errorMessage) - { - ErrorCode = errorCode; + HasError = true; + Error = error; + ErrorMessage = error.Message; + ErrorCode = error is HttpRequestException { StatusCode: not null } httpEx ? (int)httpEx.StatusCode : 0; } /// @@ -55,4 +50,9 @@ public DNSResolverResult(bool hasError, string errorMessage, int errorCode) : th /// Error code if the DNS resolver information retrieval has failed. /// public int ErrorCode { get; set; } + + /// + /// Error of the request, mapped to a localized message by the view model. + /// + public Exception Error { get; set; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/IPApi/DNSResolverService.cs b/Source/NETworkManager.Models/IPApi/DNSResolverService.cs index 67c86d04f4..08b4dc0018 100644 --- a/Source/NETworkManager.Models/IPApi/DNSResolverService.cs +++ b/Source/NETworkManager.Models/IPApi/DNSResolverService.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Net.Http; using System.Threading.Tasks; using NETworkManager.Utilities; @@ -17,7 +18,21 @@ public class DNSResolverService : SingletonBase /// private const string BaseUrl = "https://edns.ip-api.com/json"; - private readonly HttpClient _client = new(); + /// + /// Host of the API (shown in messages). + /// + public const string Host = "edns.ip-api.com"; + + /// + /// Time until a request fails without a response (instead of the 100 seconds of , e.g. + /// if a firewall drops the request), like the public IP address request of the network connection widget. + /// + public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(10); + + // A new connection per request (no keep-alive): a check right after a network change (e.g. a VPN connected) must + // not reuse a connection of the old network, which would return the old public IP address + private readonly HttpClient _client = new() + { Timeout = RequestTimeout, DefaultRequestHeaders = { ConnectionClose = true } }; /// /// Gets the IP DNS details from the API asynchronously. @@ -31,17 +46,29 @@ public async Task GetDNSResolverAsync() if (response.IsSuccessStatusCode) { - var json = await response.Content.ReadAsStringAsync(); - var info = JsonConvert.DeserializeObject(json); - - return new DNSResolverResult(DNSResolverInfo.Parse(info)); + return ParseResponse(await response.Content.ReadAsStringAsync()); } - return new DNSResolverResult(true, response.ReasonPhrase, (int)response.StatusCode); + return new DNSResolverResult(new HttpRequestException(response.ReasonPhrase, null, response.StatusCode)); } catch (Exception ex) { - return new DNSResolverResult(true, ex.Message); + return new DNSResolverResult(ex); } } + + /// + /// Parses the answer of the API. + /// + /// Body of the answer. + /// DNS resolver information, an error if the body is empty (e.g. from a proxy or a captive portal). + /// The body is not JSON. + public static DNSResolverResult ParseResponse(string json) + { + var info = JsonConvert.DeserializeObject(json); + + return info == null + ? new DNSResolverResult(new InvalidDataException("The response of the API is empty.")) + : new DNSResolverResult(DNSResolverInfo.Parse(info)); + } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/IPApi/IPGeolocationInfo.cs b/Source/NETworkManager.Models/IPApi/IPGeolocationInfo.cs index 7901ea2d24..e7c357c706 100644 --- a/Source/NETworkManager.Models/IPApi/IPGeolocationInfo.cs +++ b/Source/NETworkManager.Models/IPApi/IPGeolocationInfo.cs @@ -1,4 +1,7 @@ -namespace NETworkManager.Models.IPApi; +using System; +using Newtonsoft.Json; + +namespace NETworkManager.Models.IPApi; /// /// Class contains the IP geolocation information. @@ -10,6 +13,19 @@ public class IPGeolocationInfo /// public string Status { get; set; } + /// + /// Reason if the query failed ( fail), e.g. private range, + /// reserved range or invalid query. + /// + public string Message { get; set; } + + /// + /// ip-api.com has no geolocation for the query (HTTP 200 with fail, e.g. a private + /// IP address), see . + /// + [JsonIgnore] + public bool HasFailed => string.Equals(Status, "fail", StringComparison.OrdinalIgnoreCase); + /// /// Continent where the IP address is located. /// @@ -124,4 +140,54 @@ public class IPGeolocationInfo /// IP address used for the query. /// public string Query { get; set; } + + /// + /// Continent with its code, e.g. Europe (EU). + /// + [JsonIgnore] + public string ContinentWithCode => FormatNameWithCode(Continent, ContinentCode); + + /// + /// Country with its code, e.g. Germany (DE). + /// + [JsonIgnore] + public string CountryWithCode => FormatNameWithCode(Country, CountryCode); + + /// + /// Region with its code, e.g. Hesse (HE). + /// + [JsonIgnore] + public string RegionWithCode => FormatNameWithCode(RegionName, Region); + + /// + /// Offset from UTC, e.g. UTC+01:00. + /// + [JsonIgnore] + public string UtcOffset => FormatUtcOffset(Offset); + + /// + /// Name with its code in brackets, without empty brackets if the code is missing. + /// + /// Name, e.g. Germany. + /// Code, e.g. DE. + /// e.g. Germany (DE), null if both are empty. + public static string FormatNameWithCode(string name, string code) + { + if (string.IsNullOrEmpty(name)) + return string.IsNullOrEmpty(code) ? null : code; + + return string.IsNullOrEmpty(code) ? name : $"{name} ({code})"; + } + + /// + /// Offset from UTC (ip-api.com: seconds, incl. daylight saving time) as text. + /// + /// Offset in seconds, e.g. 3600. + /// e.g. UTC+01:00, UTC+00:00 for 0, UTC-03:30. + public static string FormatUtcOffset(int offsetSeconds) + { + var offset = TimeSpan.FromSeconds(offsetSeconds); + + return $"UTC{(offset < TimeSpan.Zero ? "-" : "+")}{offset:hh\\:mm}"; + } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/IPApi/IPGeolocationResult.cs b/Source/NETworkManager.Models/IPApi/IPGeolocationResult.cs index ba573767bc..c103957528 100644 --- a/Source/NETworkManager.Models/IPApi/IPGeolocationResult.cs +++ b/Source/NETworkManager.Models/IPApi/IPGeolocationResult.cs @@ -1,4 +1,7 @@ -namespace NETworkManager.Models.IPApi; +using System; +using System.Net.Http; + +namespace NETworkManager.Models.IPApi; /// /// Class contains the result of the IP geolocation information retrieval. @@ -34,19 +37,17 @@ public IPGeolocationResult(bool isRateLimitReached, int rateLimitRemainingTime) } /// - /// Create a new instance of with an error message and an error code. + /// Create a new instance of for a failed request. /// - /// Indicates if the IP geolocation information retrieval has failed. - /// Error message if the IP geolocation information retrieval has failed. - /// - /// Error code if the IP geolocation information retrieval has failed (or -1 if exception was - /// thrown). + /// + /// Error of the request ( with the status code for an HTTP error). /// - public IPGeolocationResult(bool hasError, string errorMessage, int errorCode) + public IPGeolocationResult(Exception error) { - HasError = hasError; - ErrorMessage = errorMessage; - ErrorCode = errorCode; + HasError = true; + Error = error; + ErrorMessage = error.Message; + ErrorCode = error is HttpRequestException { StatusCode: not null } httpEx ? (int)httpEx.StatusCode : -1; } /// @@ -78,4 +79,9 @@ public IPGeolocationResult(bool hasError, string errorMessage, int errorCode) /// Error code if the IP geolocation information retrieval has failed. /// public int ErrorCode { get; set; } + + /// + /// Error of the request, mapped to a localized message by the view model. + /// + public Exception Error { get; set; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/IPApi/IPGeolocationService.cs b/Source/NETworkManager.Models/IPApi/IPGeolocationService.cs index 02ef1f96d5..34ba5500b6 100644 --- a/Source/NETworkManager.Models/IPApi/IPGeolocationService.cs +++ b/Source/NETworkManager.Models/IPApi/IPGeolocationService.cs @@ -1,8 +1,10 @@ using System; +using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; +using log4net; using NETworkManager.Utilities; using Newtonsoft.Json; @@ -14,6 +16,8 @@ namespace NETworkManager.Models.IPApi; /// public class IPGeolocationService : SingletonBase { + private static readonly ILog Log = LogManager.GetLogger(typeof(IPGeolocationService)); + /// /// Base URL fo the ip-api free endpoint. /// @@ -25,7 +29,22 @@ public class IPGeolocationService : SingletonBase private const string Fields = "status,message,continent,continentCode,country,countryCode,region,regionName,city,district,zip,lat,lon,timezone,offset,currency,isp,org,as,asname,reverse,mobile,proxy,hosting,query"; - private readonly HttpClient _client = new(); + /// + /// Host of the API (shown in messages). + /// + public const string Host = "ip-api.com"; + + /// + /// Time until a request fails without a response (instead of the 100 seconds of , e.g. + /// if a firewall drops the request or for each hop of the traceroute), like the public IP address request of the + /// network connection widget. + /// + public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(10); + + // A new connection per request (no keep-alive): a check right after a network change (e.g. a VPN connected) must + // not reuse a connection of the old network, which would return the old public IP address + private readonly HttpClient _client = new() + { Timeout = RequestTimeout, DefaultRequestHeaders = { ConnectionClose = true } }; /// /// Indicates whether we have reached the rate limit. @@ -57,10 +76,10 @@ public class IPGeolocationService : SingletonBase public async Task GetIPGeolocationAsync(string ipAddressOrFqdn = "") { if (IsInRateLimit()) - return new IPGeolocationResult(true, _rateLimitRemainingTime); + return new IPGeolocationResult(true, + GetRemainingSeconds(_rateLimitLastReached, _rateLimitRemainingTime, DateTime.Now)); - // If the url is empty, the current IP address from which the request is made is used. - var url = $"{BaseUrl}/{ipAddressOrFqdn}?fields={Fields}"; + var url = GetUrl(ipAddressOrFqdn); try { @@ -69,38 +88,92 @@ public async Task GetIPGeolocationAsync(string ipAddressOrF // Check if the request was successful. if (response.IsSuccessStatusCode) { - // Update rate limit values. + // Update rate limit values. Without them (e.g. removed by a proxy) the answer is still used, the last + // values are kept (a 429 still stops the requests) if (!UpdateRateLimit(response.Headers)) - return new IPGeolocationResult(true, - "The rate limit values couldn't be extracted from the http header. The request was probably corrupted. Try again in a few seconds.", - -1); - - var json = await response.Content.ReadAsStringAsync(); - var info = JsonConvert.DeserializeObject(json); + Log.Warn("The rate limit headers (X-Rl, X-Ttl) of ip-api.com are missing or invalid."); - return new IPGeolocationResult(info); + return ParseResponse(await response.Content.ReadAsStringAsync()); } // Consider the request as failed if the status code is not successful or 429. if ((int)response.StatusCode != 429) - return new IPGeolocationResult(true, response.ReasonPhrase, (int)response.StatusCode); + return new IPGeolocationResult(new HttpRequestException(response.ReasonPhrase, null, + response.StatusCode)); // Code 429 - // We have already reached the rate limit (on the network) - // Since we don't get any information about the remaining time, we set it to the default value. + // We have already reached the rate limit (on the network). The time until the window resets (X-Ttl) is + // used if the answer has it, otherwise the default value. _rateLimitIsReached = true; - _rateLimitRemainingTime = 60; + _rateLimitRemainingTime = response.Headers.TryGetValues("X-Ttl", out var xTtl) && + int.TryParse(xTtl.FirstOrDefault(), out var remainingTime) && remainingTime >= 0 + ? remainingTime + : 60; _rateLimitRemainingRequests = 0; _rateLimitLastReached = DateTime.Now; - return new IPGeolocationResult(true, _rateLimitRemainingTime); + // Like the following requests (incl. the margin), so the time left counts down (61, 60, ...) + return new IPGeolocationResult(true, + GetRemainingSeconds(_rateLimitLastReached, _rateLimitRemainingTime, DateTime.Now)); } catch (Exception ex) { - return new IPGeolocationResult(true, ex.Message, -1); + return new IPGeolocationResult(ex); } } + /// + /// URL of the request (http://ip-api.com/json/{query}?fields=...). + /// + /// IP address or host name, empty for the public IP address of the computer. + /// URL. + public static string GetUrl(string ipAddressOrFqdn) + { + // The base URL ends with a slash (no "json//" for the own IP address) + return $"{BaseUrl}{ipAddressOrFqdn}?fields={Fields}"; + } + + /// + /// Parses the answer of the API. + /// + /// Body of the answer. + /// IP geolocation information, an error if the body is empty (e.g. from a proxy or a captive portal). + /// The body is not JSON. + public static IPGeolocationResult ParseResponse(string json) + { + var info = JsonConvert.DeserializeObject(json); + + return info == null + ? new IPGeolocationResult(new InvalidDataException("The response of the API is empty.")) + : new IPGeolocationResult(info); + } + + /// + /// End of the rate limit: the time window (X-Ttl) plus one second of margin. + /// + /// Time when the rate limit was reached. + /// Seconds until the time window resets (X-Ttl, 60 after HTTP 429). + /// Time from which requests are sent again. + private static DateTime GetRateLimitEnd(DateTime lastReached, int remainingTime) + { + return lastReached.AddSeconds(remainingTime + 1); + } + + /// + /// Seconds until requests are sent again (shown as "try again in ... seconds"), counting down while the rate + /// limit is reached instead of the whole time window. + /// + /// Time when the rate limit was reached. + /// Seconds until the time window resets (X-Ttl, 60 after HTTP 429). + /// Current time. + /// Seconds, rounded up, at least 1. + public static int GetRemainingSeconds(DateTime lastReached, int remainingTime, DateTime now) + { + var seconds = (int)Math.Ceiling((GetRateLimitEnd(lastReached, remainingTime) - now).TotalSeconds); + + return Math.Max(1, seconds); + } + /// /// Checks whether the rate limit is reached. /// @@ -115,7 +188,7 @@ private bool IsInRateLimit() var lastReached = _rateLimitLastReached; // We are still in the rate limit - if (lastReached.AddSeconds(_rateLimitRemainingTime + 1) >= DateTime.Now) + if (GetRateLimitEnd(lastReached, _rateLimitRemainingTime) >= DateTime.Now) return true; // We are not in the rate limit anymore @@ -124,6 +197,24 @@ private bool IsInRateLimit() return false; } + /// + /// Reads the rate limit from the headers of the response. + /// + /// Headers of the response. + /// Requests left in the time window (X-Rl). + /// Seconds until the time window resets (X-Ttl). + /// true if both headers are present and valid. + public static bool TryParseRateLimit(HttpHeaders headers, out int remainingRequests, out int remainingTime) + { + remainingRequests = 0; + remainingTime = 0; + + return headers.TryGetValues("X-Rl", out var xRl) && + int.TryParse(xRl.FirstOrDefault(), out remainingRequests) && + headers.TryGetValues("X-Ttl", out var xTtl) && + int.TryParse(xTtl.FirstOrDefault(), out remainingTime); + } + /// /// Updates the rate limit values. /// @@ -131,17 +222,7 @@ private bool IsInRateLimit() /// True if the update was successful, false otherwise. private bool UpdateRateLimit(HttpHeaders headers) { - // Parse header data - if (!headers.TryGetValues("X-Rl", out var xRl)) - return false; - - if (!int.TryParse(xRl.ToArray()[0], out var remainingRequests)) - return false; - - if (!headers.TryGetValues("X-Ttl", out var xTtl)) - return false; - - if (!int.TryParse(xTtl.ToArray()[0], out var remainingTime)) + if (!TryParseRateLimit(headers, out var remainingRequests, out var remainingTime)) return false; _rateLimitRemainingTime = remainingTime; diff --git a/Source/NETworkManager.Tests/IPApi/DNSResolverServiceTests.cs b/Source/NETworkManager.Tests/IPApi/DNSResolverServiceTests.cs new file mode 100644 index 0000000000..906d09e7ba --- /dev/null +++ b/Source/NETworkManager.Tests/IPApi/DNSResolverServiceTests.cs @@ -0,0 +1,42 @@ +using NETworkManager.Models.IPApi; +using Xunit; + +namespace NETworkManager.Tests.IPApi; + +public class DNSResolverServiceTests +{ + [Fact] + public void ResponseIsParsed() + { + var result = DNSResolverService.ParseResponse( + "{\"dns\":{\"ip\":\"198.51.100.53\",\"geo\":\"Germany - Example ISP\"},\"edns\":{\"ip\":\"203.0.113.0\",\"geo\":\"Germany - Example ISP\"}}"); + + Assert.False(result.HasError); + Assert.Equal("198.51.100.53", result.Info.DnsIp); + Assert.Equal("Germany - Example ISP", result.Info.DnsGeo); + Assert.Equal("203.0.113.0", result.Info.EdnsIp); + } + + [Fact] + public void ResponseWithoutEDNSIsParsed() + { + // The resolver doesn't send the client subnet + var result = DNSResolverService.ParseResponse("{\"dns\":{\"ip\":\"198.51.100.53\",\"geo\":\"Germany\"}}"); + + Assert.False(result.HasError); + Assert.Equal("198.51.100.53", result.Info.DnsIp); + Assert.Null(result.Info.EdnsIp); + Assert.Null(result.Info.EdnsGeo); + } + + [Theory] + [InlineData("")] + [InlineData("null")] + public void EmptyResponseIsAnError(string json) + { + var result = DNSResolverService.ParseResponse(json); + + Assert.True(result.HasError); + Assert.Null(result.Info); + } +} diff --git a/Source/NETworkManager.Tests/IPApi/IPApiResultTests.cs b/Source/NETworkManager.Tests/IPApi/IPApiResultTests.cs new file mode 100644 index 0000000000..1fd51e6338 --- /dev/null +++ b/Source/NETworkManager.Tests/IPApi/IPApiResultTests.cs @@ -0,0 +1,58 @@ +using System; +using System.Net; +using System.Net.Http; +using NETworkManager.Models.IPApi; +using Xunit; + +namespace NETworkManager.Tests.IPApi; + +public class IPApiResultTests +{ + [Fact] + public void IPGeolocationResultOfAnHttpErrorHasTheStatusCode() + { + var error = new HttpRequestException("Service Unavailable", null, HttpStatusCode.ServiceUnavailable); + + var result = new IPGeolocationResult(error); + + Assert.True(result.HasError); + Assert.Same(error, result.Error); + Assert.Equal(503, result.ErrorCode); + Assert.Equal("Service Unavailable", result.ErrorMessage); + } + + [Fact] + public void IPGeolocationResultWithoutResponseHasNoStatusCode() + { + var error = new TimeoutException(); + + var result = new IPGeolocationResult(error); + + Assert.True(result.HasError); + Assert.Same(error, result.Error); + Assert.Equal(-1, result.ErrorCode); + } + + [Fact] + public void DNSResolverResultOfAnHttpErrorHasTheStatusCode() + { + var error = new HttpRequestException("Bad Gateway", null, HttpStatusCode.BadGateway); + + var result = new DNSResolverResult(error); + + Assert.True(result.HasError); + Assert.Same(error, result.Error); + Assert.Equal(502, result.ErrorCode); + Assert.Equal("Bad Gateway", result.ErrorMessage); + } + + [Fact] + public void DNSResolverResultWithoutResponseHasNoStatusCode() + { + var result = new DNSResolverResult(new HttpRequestException("No such host is known.")); + + Assert.True(result.HasError); + Assert.Equal(0, result.ErrorCode); + Assert.Null(result.Info); + } +} diff --git a/Source/NETworkManager.Tests/IPApi/IPGeolocationInfoTests.cs b/Source/NETworkManager.Tests/IPApi/IPGeolocationInfoTests.cs new file mode 100644 index 0000000000..0e8bfa603a --- /dev/null +++ b/Source/NETworkManager.Tests/IPApi/IPGeolocationInfoTests.cs @@ -0,0 +1,39 @@ +using NETworkManager.Models.IPApi; +using Xunit; + +namespace NETworkManager.Tests.IPApi; + +public class IPGeolocationInfoTests +{ + [Theory] + [InlineData(0, "UTC+00:00")] // e.g. London in winter (was shown as "-/-") + [InlineData(3600, "UTC+01:00")] + [InlineData(19800, "UTC+05:30")] + [InlineData(-12600, "UTC-03:30")] + [InlineData(-36000, "UTC-10:00")] + [InlineData(50400, "UTC+14:00")] + public void UtcOffsetIsFormatted(int offsetSeconds, string expected) + { + Assert.Equal(expected, IPGeolocationInfo.FormatUtcOffset(offsetSeconds)); + } + + [Theory] + [InlineData("Hesse", "HE", "Hesse (HE)")] + [InlineData("Hesse", "", "Hesse")] + [InlineData("Hesse", null, "Hesse")] + [InlineData("", "HE", "HE")] + [InlineData(null, null, null)] + [InlineData("", "", null)] + public void NameWithCodeHasNoEmptyBrackets(string name, string code, string expected) + { + Assert.Equal(expected, IPGeolocationInfo.FormatNameWithCode(name, code)); + } + + [Fact] + public void RegionWithCodeUsesTheRegionName() + { + var info = new IPGeolocationInfo { RegionName = "Hesse", Region = "HE" }; + + Assert.Equal("Hesse (HE)", info.RegionWithCode); + } +} diff --git a/Source/NETworkManager.Tests/IPApi/IPGeolocationServiceTests.cs b/Source/NETworkManager.Tests/IPApi/IPGeolocationServiceTests.cs new file mode 100644 index 0000000000..92e3dd9d9f --- /dev/null +++ b/Source/NETworkManager.Tests/IPApi/IPGeolocationServiceTests.cs @@ -0,0 +1,119 @@ +using System; +using System.Net.Http; +using NETworkManager.Models.IPApi; +using Xunit; + +namespace NETworkManager.Tests.IPApi; + +public class IPGeolocationServiceTests +{ + private static readonly DateTime LastReached = new(2026, 11, 26, 12, 0, 0); + + [Fact] + public void RemainingSecondsRightAfterTheRateLimitIsTheWindowWithMargin() + { + Assert.Equal(61, IPGeolocationService.GetRemainingSeconds(LastReached, 60, LastReached)); + } + + [Fact] + public void RemainingSecondsCountDown() + { + // Not the whole window again ("try again in 60 seconds" 50 seconds later) + Assert.Equal(11, IPGeolocationService.GetRemainingSeconds(LastReached, 60, LastReached.AddSeconds(50))); + } + + [Fact] + public void RemainingSecondsAreRoundedUp() + { + Assert.Equal(2, IPGeolocationService.GetRemainingSeconds(LastReached, 10, LastReached.AddSeconds(9.5))); + } + + [Fact] + public void RemainingSecondsAreAtLeastOne() + { + Assert.Equal(1, IPGeolocationService.GetRemainingSeconds(LastReached, 10, LastReached.AddSeconds(11))); + Assert.Equal(1, IPGeolocationService.GetRemainingSeconds(LastReached, 10, LastReached.AddMinutes(5))); + } + + [Theory] + [InlineData("", "http://ip-api.com/json/?fields=")] + [InlineData("8.8.8.8", "http://ip-api.com/json/8.8.8.8?fields=")] + [InlineData("2001:db8::1", "http://ip-api.com/json/2001:db8::1?fields=")] + [InlineData("example.com", "http://ip-api.com/json/example.com?fields=")] + public void UrlHasOneSlashBeforeTheQuery(string query, string expectedStart) + { + Assert.StartsWith(expectedStart, IPGeolocationService.GetUrl(query)); + } + + [Fact] + public void ResponseIsParsed() + { + var result = IPGeolocationService.ParseResponse( + "{\"status\":\"success\",\"country\":\"Germany\",\"countryCode\":\"DE\",\"offset\":3600,\"query\":\"203.0.113.10\"}"); + + Assert.False(result.HasError); + Assert.Equal("Germany", result.Info.Country); + Assert.Equal(3600, result.Info.Offset); + Assert.Equal("203.0.113.10", result.Info.Query); + } + + [Fact] + public void FailedQueryHasTheReason() + { + // HTTP 200, no error of the request: the IP Geolocation tool shows the reason, the traceroute an empty hop + var result = IPGeolocationService.ParseResponse( + "{\"status\":\"fail\",\"message\":\"private range\",\"query\":\"192.168.1.1\"}"); + + Assert.False(result.HasError); + Assert.True(result.Info.HasFailed); + Assert.Equal("private range", result.Info.Message); + } + + [Fact] + public void SuccessfulQueryHasNotFailed() + { + Assert.False(IPGeolocationService.ParseResponse("{\"status\":\"success\"}").Info.HasFailed); + } + + [Theory] + [InlineData("")] + [InlineData("null")] + public void EmptyResponseIsAnError(string json) + { + Assert.True(IPGeolocationService.ParseResponse(json).HasError); + } + + private static HttpResponseMessage CreateResponse(string xRl, string xTtl) + { + var response = new HttpResponseMessage(); + + if (xRl != null) + response.Headers.Add("X-Rl", xRl); + + if (xTtl != null) + response.Headers.Add("X-Ttl", xTtl); + + return response; + } + + [Fact] + public void RateLimitIsReadFromTheHeaders() + { + Assert.True(IPGeolocationService.TryParseRateLimit(CreateResponse("44", "59").Headers, + out var remainingRequests, out var remainingTime)); + Assert.Equal(44, remainingRequests); + Assert.Equal(59, remainingTime); + } + + [Theory] + [InlineData(null, "59")] + [InlineData("44", null)] + [InlineData(null, null)] + [InlineData("many", "59")] + [InlineData("44", "")] + public void RateLimitWithoutValidHeadersIsNotRead(string xRl, string xTtl) + { + // e.g. removed by a proxy: the answer is used anyway + Assert.False(IPGeolocationService.TryParseRateLimit(CreateResponse(xRl, xTtl).Headers, out _, out _)); + } +} diff --git a/Source/NETworkManager/NavigationManager.cs b/Source/NETworkManager/NavigationManager.cs index 72a25b6734..f7bbf261c6 100644 --- a/Source/NETworkManager/NavigationManager.cs +++ b/Source/NETworkManager/NavigationManager.cs @@ -35,6 +35,22 @@ public static void Open(ApplicationRequest request) ApplicationRequested?.Invoke(null, request); } + /// + /// Opens an application with a target (IP address or host name), e.g. from the context menu of a value ("open in + /// other tool"). DNS Lookup and RDAP get their own request (record type / query type from the target). + /// + /// Application to open. + /// IP address or host name. + public static void Open(ApplicationName application, string target) + { + Open(application switch + { + ApplicationName.DNSLookup => new DNSLookupRequest { Target = target }, + ApplicationName.RDAP => new RDAPRequest { Target = target }, + _ => new ApplicationRequest(application) { Target = target } + }); + } + /// /// Opens the settings of the current application. /// diff --git a/Source/NETworkManager/Resources/ContextMenu/ContextMenu.xaml b/Source/NETworkManager/Resources/ContextMenu/ContextMenu.xaml index 8e465f6520..4ece0d3248 100644 --- a/Source/NETworkManager/Resources/ContextMenu/ContextMenu.xaml +++ b/Source/NETworkManager/Resources/ContextMenu/ContextMenu.xaml @@ -1,7 +1,8 @@  + xmlns:localization="clr-namespace:NETworkManager.Localization.Resources;assembly=NETworkManager.Localization" + xmlns:models="clr-namespace:NETworkManager.Models;assembly=NETworkManager.Models"> @@ -94,4 +95,146 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs b/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs index 051705a8db..c238541a4d 100644 --- a/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs +++ b/Source/NETworkManager/ViewModels/ConnectionCheckItem.cs @@ -220,13 +220,11 @@ private void OpenApplicationAction(object parameter) if (parameter is not ApplicationName applicationName || Target == null) return; - NavigationManager.Open(applicationName switch - { - ApplicationName.DNSLookup => new DNSLookupRequest { Target = Target }, - ApplicationName.RDAP => new RDAPRequest { Target = Target }, - ApplicationName.WebConsole => new ApplicationRequest(applicationName) - { Target = WebConsoleUrlHelper.CreateUrl(Target, Enumerable.Empty()) }, - _ => new ApplicationRequest(applicationName) { Target = Target } - }); + // The router's web interface as URL + if (applicationName == ApplicationName.WebConsole) + NavigationManager.Open(new ApplicationRequest(applicationName) + { Target = WebConsoleUrlHelper.CreateUrl(Target, Enumerable.Empty()) }); + else + NavigationManager.Open(applicationName, Target); } } diff --git a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs index d5aa014d4b..d34534ddfa 100644 --- a/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs +++ b/Source/NETworkManager/ViewModels/DashboardSettingsViewModel.cs @@ -1,3 +1,4 @@ +using System.ComponentModel; using NETworkManager.Settings; namespace NETworkManager.ViewModels; @@ -275,6 +276,22 @@ public DashboardSettingsViewModel() LoadSettings(); _isLoading = false; + + // The checks can also be enabled in the widgets (the settings view is created once) + SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged; + } + + private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) + { + switch (e.PropertyName) + { + case nameof(SettingsInfo.Dashboard_CheckIPApiIPGeolocation): + CheckIPApiIPGeolocationEnabled = SettingsManager.Current.Dashboard_CheckIPApiIPGeolocation; + break; + case nameof(SettingsInfo.Dashboard_CheckIPApiDNSResolver): + CheckIPApiDNSResolverEnabled = SettingsManager.Current.Dashboard_CheckIPApiDNSResolver; + break; + } } /// diff --git a/Source/NETworkManager/ViewModels/IPApiDNSResolverWidgetViewModel.cs b/Source/NETworkManager/ViewModels/IPApiDNSResolverWidgetViewModel.cs index cec3d50ef9..eb614d6fc4 100644 --- a/Source/NETworkManager/ViewModels/IPApiDNSResolverWidgetViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPApiDNSResolverWidgetViewModel.cs @@ -1,5 +1,11 @@ +using System; +using System.Text; using System.Threading.Tasks; using System.Windows.Input; +using log4net; +using NETworkManager.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Models; using NETworkManager.Models.IPApi; using NETworkManager.Settings; using NETworkManager.Utilities; @@ -13,6 +19,13 @@ public class IPApiDNSResolverWidgetViewModel : ViewModelBase { #region Variables + /// + /// A check was requested while a check was running (see ). + /// + private bool _recheckPending; + + private static readonly ILog Log = LogManager.GetLogger(typeof(IPApiDNSResolverWidgetViewModel)); + /// /// Gets or sets a value indicating whether the check is running. /// @@ -45,17 +58,75 @@ private set } } + /// + /// Gets the time of the last successful check, null before it and while checking (the values belong to it). + /// + public DateTime? LastCheckTime + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Message of the last check, e.g. an error or the rate limit (shown below the header). + /// + public string StatusMessage + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + public StatusLevel StatusMessageLevel + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + public bool IsStatusMessageDisplayed + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + #endregion #region Constructor, load settings /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. The dashboard starts the check (the + /// widget is created when it is shown the first time). /// public IPApiDNSResolverWidgetViewModel() { LoadSettings(); - Check(); } /// @@ -75,15 +146,87 @@ private void LoadSettings() /// public ICommand CheckCommand => new RelayCommand(_ => Check(), _ => !IsRunning); + /// + /// Gets the command to copy all values as text, e.g. for a support request. + /// + public ICommand CopyAllCommand => new RelayCommand(_ => CopyAllAction(), _ => !IsRunning && Result?.Info != null); + + /// + /// Gets the command to open the IP address of the DNS server in another tool (parameter: ). + /// + public ICommand OpenDNSServerCommand => new RelayCommand(parameter => OpenApplication(parameter, Result?.Info?.DnsIp), + _ => !string.IsNullOrEmpty(Result?.Info?.DnsIp)); + + /// + /// Gets the command to open the EDNS client subnet in another tool (parameter: ). + /// + public ICommand OpenEDNSCommand => new RelayCommand(parameter => OpenApplication(parameter, Result?.Info?.EdnsIp), + _ => !string.IsNullOrEmpty(Result?.Info?.EdnsIp)); + + /// + /// Opens a value in another tool (context menu, parameter: ). + /// + private static void OpenApplication(object parameter, string target) + { + if (parameter is ApplicationName application && !string.IsNullOrEmpty(target)) + NavigationManager.Open(application, target); + } + + /// + /// Gets the command to enable the DNS resolver check (setting Dashboard_CheckIPApiDNSResolver, off by default: ip-api.com receives + /// the IP address) and to check right away. + /// + public ICommand EnableCheckCommand => new RelayCommand(_ => EnableCheckAction()); + + private void CopyAllAction() + { + var info = Result.Info; + var text = new StringBuilder(); + + foreach (var (title, ip, geo) in new[] + { + (Strings.DNS, info.DnsIp, info.DnsGeo), + (Strings.EDNS, info.EdnsIp, info.EdnsGeo) + }) + { + if (text.Length > 0) + text.AppendLine(); + + text.AppendLine(title); + text.AppendLine($"{Strings.IPAddress}: {FormatValue(ip)}"); + text.AppendLine($"{Strings.Geolocation}: {FormatValue(geo)}"); + } + + ClipboardHelper.SetClipboard(text.ToString().TrimEnd()); + } + + // Like the widget: "-/-" for an empty value (e.g. no EDNS client subnet) + private static string FormatValue(string value) => string.IsNullOrEmpty(value) ? "-/-" : value; + + private void EnableCheckAction() + { + SettingsManager.Current.Dashboard_CheckIPApiDNSResolver = true; + + Check(); + } + #endregion #region Methods /// - /// Checks the DNS resolver. + /// Checks the DNS resolver (also called by the dashboard, e.g. after a network change). /// - private void Check() + public void Check() { + // Already checking, e.g. the network changed right after the widget was created: the running request may use + // the old network, check again once it has finished + if (IsRunning) + { + _recheckPending = true; + return; + } + _ = CheckAsync(); } @@ -92,22 +235,64 @@ private void Check() /// private async Task CheckAsync() { - // Check is disabled via settings + // Check is disabled via settings (the dashboard checks again when it is shown after the setting changed): no + // values, message or time of an earlier check next to the "Enable" button if (!SettingsManager.Current.Dashboard_CheckIPApiDNSResolver) + { + IsStatusMessageDisplayed = false; + Result = null; + LastCheckTime = null; + return; + } IsRunning = true; + IsStatusMessageDisplayed = false; Result = null; + LastCheckTime = null; - // Takes at least the refresh interval, so the reload animation is visible and the check can't be spammed - - // the request runs at the same time - Result = await TaskHelper.WithMinimumDurationAsync( - () => ScreenshotData.IsEnabled - ? Task.FromResult(ScreenshotData.CreateDNSResolverResult()) - : DNSResolverService.GetInstance().GetDNSResolverAsync(), - GlobalStaticConfiguration.ApplicationUIRefreshInterval); + try + { + // Takes at least the refresh interval, so the reload animation is visible and the check can't be spammed - + // the request runs at the same time + var result = await TaskHelper.WithMinimumDurationAsync( + () => ScreenshotData.IsEnabled + ? Task.FromResult(ScreenshotData.CreateDNSResolverResult()) + : DNSResolverService.GetInstance().GetDNSResolverAsync(), + GlobalStaticConfiguration.ApplicationUIRefreshInterval); - IsRunning = false; + if (result.HasError) + { + Log.Error($"edns.ip-api.com error: {result.ErrorMessage}, error code: {result.ErrorCode}"); + + StatusMessage = WebRequestErrorMessage.Get(DNSResolverService.Host, DNSResolverService.RequestTimeout, + result.Error); + StatusMessageLevel = StatusLevel.Error; + IsStatusMessageDisplayed = true; + } + else + { + Result = result; + LastCheckTime = DateTime.Now; + } + } + finally + { + IsRunning = false; + + // Enable the refresh button (CanExecute is otherwise only evaluated on the next input) + CommandManager.InvalidateRequerySuggested(); + } + + // A check requested in the meantime (e.g. a network change). A hidden widget doesn't check anything: it is + // checked when it is shown again (the setting marks the dashboard as outdated) + if (_recheckPending) + { + _recheckPending = false; + + if (SettingsManager.Current.Dashboard_ShowDNSResolverWidget) + Check(); + } } #endregion diff --git a/Source/NETworkManager/ViewModels/IPApiIPGeolocationWidgetViewModel.cs b/Source/NETworkManager/ViewModels/IPApiIPGeolocationWidgetViewModel.cs index 1df73bd600..09787712f7 100644 --- a/Source/NETworkManager/ViewModels/IPApiIPGeolocationWidgetViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPApiIPGeolocationWidgetViewModel.cs @@ -1,6 +1,12 @@ -using System.Threading.Tasks; +using System; +using System.Globalization; +using System.Text; +using System.Threading.Tasks; using System.Windows.Input; using log4net; +using NETworkManager.Controls; +using NETworkManager.Localization.Resources; +using NETworkManager.Models; using NETworkManager.Models.IPApi; using NETworkManager.Settings; using NETworkManager.Utilities; @@ -14,6 +20,11 @@ public class IPApiIPGeolocationWidgetViewModel : ViewModelBase { #region Variables + /// + /// A check was requested while a check was running (see ). + /// + private bool _recheckPending; + private static readonly ILog Log = LogManager.GetLogger(typeof(IPApiIPGeolocationWidgetViewModel)); /// @@ -48,17 +59,75 @@ private set } } + /// + /// Gets the time of the last successful check, null before it and while checking (the values belong to it). + /// + public DateTime? LastCheckTime + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + /// + /// Message of the last check, e.g. an error or the rate limit (shown below the header). + /// + public string StatusMessage + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + public StatusLevel StatusMessageLevel + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + + public bool IsStatusMessageDisplayed + { + get; + private set + { + if (value == field) + return; + + field = value; + OnPropertyChanged(); + } + } + #endregion #region Constructor, load settings /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. The dashboard starts the check (the + /// widget is created when it is shown the first time). /// public IPApiIPGeolocationWidgetViewModel() { LoadSettings(); - Check(); } /// @@ -77,15 +146,111 @@ private void LoadSettings() /// public ICommand CheckCommand => new RelayCommand(_ => Check(), _ => !IsRunning); + /// + /// Gets the command to copy all values as text, e.g. for a support request. + /// + public ICommand CopyAllCommand => new RelayCommand(_ => CopyAllAction(), _ => !IsRunning && Result?.Info != null); + + /// + /// Gets the command to open the public IP address in another tool (parameter: ). + /// + public ICommand OpenIPAddressCommand => new RelayCommand(parameter => OpenApplication(parameter, Result?.Info?.Query), + _ => !string.IsNullOrEmpty(Result?.Info?.Query)); + + /// + /// Gets the command to open the PTR record in another tool (parameter: ). + /// + public ICommand OpenPTRRecordCommand => new RelayCommand(parameter => OpenApplication(parameter, Result?.Info?.Reverse), + _ => !string.IsNullOrEmpty(Result?.Info?.Reverse)); + + /// + /// Opens a value in another tool (context menu, parameter: ). + /// + private static void OpenApplication(object parameter, string target) + { + if (parameter is ApplicationName application && !string.IsNullOrEmpty(target)) + NavigationManager.Open(application, target); + } + + /// + /// Gets the command to enable the IP geolocation check (setting Dashboard_CheckIPApiIPGeolocation, off by default: ip-api.com receives + /// the IP address) and to check right away. + /// + public ICommand EnableCheckCommand => new RelayCommand(_ => EnableCheckAction()); + + private void CopyAllAction() + { + var info = Result.Info; + var text = new StringBuilder(); + + text.AppendLine(Strings.Location); + + foreach (var (label, value) in new[] + { + (Strings.Continent, info.ContinentWithCode), + (Strings.Country, info.CountryWithCode), + (Strings.Region, info.RegionWithCode), + (Strings.City, info.City), + (Strings.District, info.District), + (Strings.ZipCode, info.Zip), + (Strings.Latitude, FormatCoordinate(info.Lat)), + (Strings.Longitude, FormatCoordinate(info.Lon)), + (Strings.Timezone, info.Timezone), + (Strings.Offset, info.UtcOffset), + (Strings.Currency, info.Currency) + }) + text.AppendLine($"{label}: {FormatValue(value)}"); + + text.AppendLine(); + text.AppendLine(Strings.Network); + + foreach (var (label, value) in new[] + { + (Strings.IPAddress, info.Query), + (Strings.PTRRecord, info.Reverse), + (Strings.ISP, info.Isp), + (Strings.Organization, info.Org), + (Strings.ASN, info.As), + (Strings.ASName, info.Asname), + (Strings.Hosting, info.Hosting ? Strings.Yes : Strings.No), + (Strings.Proxy, info.Proxy ? Strings.Yes : Strings.No), + (Strings.Mobile, info.Mobile ? Strings.Yes : Strings.No) + }) + text.AppendLine($"{label}: {FormatValue(value)}"); + + ClipboardHelper.SetClipboard(text.ToString().TrimEnd()); + } + + // Like the widget: "-/-" for an empty value (and 0 for a coordinate, which ip-api.com returns without a location) + private static string FormatValue(string value) => string.IsNullOrEmpty(value) ? "-/-" : value; + + private static string FormatCoordinate(double value) => + value == 0 ? "-/-" : value.ToString(CultureInfo.CurrentCulture); + + private void EnableCheckAction() + { + SettingsManager.Current.Dashboard_CheckIPApiIPGeolocation = true; + + Check(); + } + #endregion #region Methods /// - /// Checks the IP geolocation. + /// Checks the IP geolocation (also called by the dashboard, e.g. after a network change). /// - private void Check() + public void Check() { + // Already checking, e.g. the network changed right after the widget was created: the running request may use + // the old network, check again once it has finished + if (IsRunning) + { + _recheckPending = true; + return; + } + _ = CheckAsync(); } @@ -94,30 +259,86 @@ private void Check() /// private async Task CheckAsync() { - // Check is disabled via settings + // Check is disabled via settings (the dashboard checks again when it is shown after the setting changed): no + // values, message or time of an earlier check next to the "Enable" button if (!SettingsManager.Current.Dashboard_CheckIPApiIPGeolocation) + { + IsStatusMessageDisplayed = false; + Result = null; + LastCheckTime = null; + return; + } IsRunning = true; + IsStatusMessageDisplayed = false; Result = null; + LastCheckTime = null; - // Takes at least the refresh interval, so the reload animation is visible and the check can't be spammed - - // the request runs at the same time - Result = await TaskHelper.WithMinimumDurationAsync( - () => ScreenshotData.IsEnabled - ? Task.FromResult(ScreenshotData.CreateIPGeolocationResult()) - : IPGeolocationService.GetInstance().GetIPGeolocationAsync(), - GlobalStaticConfiguration.ApplicationUIRefreshInterval); + try + { + // Takes at least the refresh interval, so the reload animation is visible and the check can't be spammed - + // the request runs at the same time + var result = await TaskHelper.WithMinimumDurationAsync( + () => ScreenshotData.IsEnabled + ? Task.FromResult(ScreenshotData.CreateIPGeolocationResult()) + : IPGeolocationService.GetInstance().GetIPGeolocationAsync(), + GlobalStaticConfiguration.ApplicationUIRefreshInterval); + + if (result.HasError) + { + Log.Error($"ip-api.com error: {result.ErrorMessage}, error code: {result.ErrorCode}"); - // Log error - if (Result.HasError) - Log.Error($"ip-api.com error: {Result.ErrorMessage}, error code: {Result.ErrorCode}"); + ShowStatusMessage(WebRequestErrorMessage.Get(IPGeolocationService.Host, + IPGeolocationService.RequestTimeout, result.Error), StatusLevel.Error); + } + else if (result.RateLimitIsReached) + { + Log.Warn($"ip-api.com rate limit reached. Try again in {result.RateLimitRemainingTime} seconds."); - // Log rate limit - if (Result.RateLimitIsReached) - Log.Warn($"ip-api.com rate limit reached. Try again in {Result.RateLimitRemainingTime} seconds."); + // Like the IP Geolocation tool and the traceroute + ShowStatusMessage( + $"{IPGeolocationService.Host} {string.Format(Strings.RateLimitReachedTryAgainInXSeconds, result.RateLimitRemainingTime)}", + StatusLevel.Warning); + } + else if (result.Info.HasFailed) + { + // No geolocation for the public IP address (HTTP 200, e.g. a proxy / NAT64), like the IP Geolocation tool + Log.Warn($"ip-api.com has no geolocation for {result.Info.Query}: {result.Info.Message}"); + + ShowStatusMessage(string.Format(Strings.XXXHasNoIPGeolocationForXXXReasonXXX, IPGeolocationService.Host, + result.Info.Query, result.Info.Message), StatusLevel.Warning); + } + else + { + Result = result; + LastCheckTime = DateTime.Now; + } + } + finally + { + IsRunning = false; + + // Enable the refresh button (CanExecute is otherwise only evaluated on the next input) + CommandManager.InvalidateRequerySuggested(); + } - IsRunning = false; + // A check requested in the meantime (e.g. a network change). A hidden widget doesn't check anything: it is + // checked when it is shown again (the setting marks the dashboard as outdated) + if (_recheckPending) + { + _recheckPending = false; + + if (SettingsManager.Current.Dashboard_ShowIPGeolocationWidget) + Check(); + } + } + + private void ShowStatusMessage(string message, StatusLevel level) + { + StatusMessage = message; + StatusMessageLevel = level; + IsStatusMessageDisplayed = true; } #endregion diff --git a/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs b/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs index 2e0a540f32..421ccef5ef 100644 --- a/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPGeolocationViewModel.cs @@ -258,7 +258,9 @@ private async Task Query() { Log.Error($"ip-api.com error: {result.ErrorMessage}, error code: {result.ErrorCode}"); - StatusMessage = $"ip-api.com: {result.ErrorMessage}"; + // Translated (the exception text of .NET is logged), like the IP geolocation widget of the dashboard + StatusMessage = WebRequestErrorMessage.Get(IPGeolocationService.Host, + IPGeolocationService.RequestTimeout, result.Error); StatusMessageLevel = StatusLevel.Error; IsStatusMessageDisplayed = true; @@ -277,6 +279,19 @@ private async Task Query() return; } + // No geolocation for the query (HTTP 200, e.g. a private IP address): the reason instead of an empty result + if (result.Info.HasFailed) + { + Log.Warn($"ip-api.com has no geolocation for {Host}: {result.Info.Message}"); + + StatusMessage = string.Format(Strings.XXXHasNoIPGeolocationForXXXReasonXXX, IPGeolocationService.Host, + Host, result.Info.Message); + StatusMessageLevel = StatusLevel.Warning; + IsStatusMessageDisplayed = true; + + return; + } + Result = result.Info; IsResultVisible = true; @@ -289,8 +304,11 @@ private async Task Query() StatusMessageLevel = StatusLevel.Error; IsStatusMessageDisplayed = true; } - - IsRunning = false; + finally + { + // Also after an error or the rate limit (early return), otherwise the tab stays busy + IsRunning = false; + } } /// diff --git a/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs b/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs index 20fe336a18..3459ec39d4 100644 --- a/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs +++ b/Source/NETworkManager/ViewModels/NetworkConnectionWidgetViewModel.cs @@ -32,7 +32,10 @@ public class NetworkConnectionWidgetViewModel : ViewModelBase /// /// Shared, timeout-bound HTTP client used to detect the public IPv4/IPv6 address. /// - private static readonly HttpClient PublicIPHttpClient = new() { Timeout = TimeSpan.FromSeconds(10) }; + // A new connection per request (no keep-alive): a check right after a network change (e.g. a VPN connected) must + // not reuse a connection of the old network, which would return the old public IP address + private static readonly HttpClient PublicIPHttpClient = new() + { Timeout = TimeSpan.FromSeconds(10), DefaultRequestHeaders = { ConnectionClose = true } }; /// /// Data sent with the ping of the gateway and the public IP address. diff --git a/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs b/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs index ca97056c97..b085dfa807 100644 --- a/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs +++ b/Source/NETworkManager/ViewModels/SpeedTestWidgetViewModel.cs @@ -1,6 +1,5 @@ using System; using System.Collections.ObjectModel; -using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -374,24 +373,6 @@ private void ShowStatusMessage(string message, StatusLevel level) IsStatusMessageDisplayed = true; } - /// - /// Localized message for an error of the speed test (the exception text is logged). - /// - private static string GetErrorMessage(Exception ex) - { - var message = ex switch - { - TimeoutException => string.Format(Strings.XXXDidNotRespondWithinXXXSecondsMessage, SpeedTestService.Host, - SpeedTestService.RequestTimeout.TotalSeconds), - HttpRequestException { StatusCode: not null } httpEx => string.Format(Strings.CouldNotConnectToXXXReasonXXX, - SpeedTestService.Host, $"{Strings.HTTPStatusCode} {(int)httpEx.StatusCode}"), - _ => string.Format(Strings.CouldNotConnectToXXXMessage, SpeedTestService.Host) - }; - - // One message with its hint (a new line would look like a second message), wraps if the widget is narrow - return $"{message} {Strings.CheckNetworkConnectionTryAgainMessage}"; - } - /// /// Adds a sample (one completed request) to a sparkline and extends its X axis to the samples. /// @@ -507,7 +488,9 @@ private async Task RunAsync() { // Partial results remain visible, like after a cancel Log.Error("Speed test failed.", ex); - ShowStatusMessage(GetErrorMessage(ex), StatusLevel.Error); + ShowStatusMessage( + WebRequestErrorMessage.Get(SpeedTestService.Host, SpeedTestService.RequestTimeout, ex), + StatusLevel.Error); } finally { diff --git a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs index 58a06ddba3..e60b181c86 100644 --- a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs @@ -5,6 +5,7 @@ using NETworkManager.Localization.Resources; using NETworkManager.Models; using NETworkManager.Models.Export; +using NETworkManager.Models.IPApi; using NETworkManager.Models.Network; using NETworkManager.Models.RDAP; using NETworkManager.Settings; @@ -149,6 +150,11 @@ public IList SelectedResults private bool _ipGeolocationRateLimitIsReached; + /// + /// The error of the IP geolocation was shown (once per trace, e.g. not for every hop while ip-api.com is down). + /// + private bool _ipGeolocationErrorIsShown; + /// /// Gets or sets a value indicating whether the status message is displayed. /// @@ -401,6 +407,7 @@ private void StopTrace() private async Task StartTrace() { _ipGeolocationRateLimitIsReached = false; + _ipGeolocationErrorIsShown = false; StatusMessage = string.Empty; StatusMessageLevel = StatusLevel.None; IsStatusMessageDisplayed = false; @@ -542,7 +549,14 @@ private void Traceroute_HopReceived(object sender, TracerouteHopReceivedArgs e) Log.Error( $"ip-api.com error: {e.Args.IPGeolocationResult.ErrorMessage}, error code: {e.Args.IPGeolocationResult.ErrorCode}"); - DisplayStatusMessage($"ip-api.com: {e.Args.IPGeolocationResult.ErrorMessage}"); + // Translated (the exception text of .NET is logged), like the IP geolocation widget of the dashboard + if (!_ipGeolocationErrorIsShown) + { + _ipGeolocationErrorIsShown = true; + + DisplayStatusMessage(WebRequestErrorMessage.Get(IPGeolocationService.Host, + IPGeolocationService.RequestTimeout, e.Args.IPGeolocationResult.Error)); + } } // Check rate limit diff --git a/Source/NETworkManager/Views/DashboardSettingsView.xaml b/Source/NETworkManager/Views/DashboardSettingsView.xaml index bde05ddeb6..6494d29bbe 100644 --- a/Source/NETworkManager/Views/DashboardSettingsView.xaml +++ b/Source/NETworkManager/Views/DashboardSettingsView.xaml @@ -9,7 +9,30 @@ xmlns:validators="clr-namespace:NETworkManager.Validators;assembly=NETworkManager.Validators" mc:Ignorable="d" d:DataContext="{d:DesignInstance viewModels:DashboardSettingsViewModel}"> - + + + + + + - - - + + + + + + - + + @@ -86,7 +118,8 @@ - + + @@ -109,7 +142,8 @@ Margin="0,0,0,10" Foreground="{DynamicResource MahApps.Brushes.Gray3}" /> + Text="{Binding Result.Info.DnsIp, Converter={StaticResource StringNullOrEmptyToStringConverter}}" FontFamily="{StaticResource Fonts.Family.Mono}" + ContextMenu="{StaticResource OpenIPAddressContextMenu}" Tag="{Binding OpenDNSServerCommand}" /> @@ -117,43 +151,12 @@ Margin="0,20,0,10" Foreground="{DynamicResource MahApps.Brushes.Gray3}" /> + Text="{Binding Result.Info.EdnsIp, Converter={StaticResource StringNullOrEmptyToStringConverter}}" FontFamily="{StaticResource Fonts.Family.Mono}" + ContextMenu="{StaticResource OpenSubnetAddressContextMenu}" Tag="{Binding OpenEDNSCommand}" /> - - - - - - - - - - - - - - - - - - @@ -162,11 +165,32 @@ Style="{StaticResource MessageTextBlock}" /> - + + + + + + + + + + - + + @@ -89,10 +121,8 @@ - - - - + + @@ -126,32 +156,14 @@ - - - - - - - - + - - - - - - - - + - - - - - - - - + @@ -172,7 +184,7 @@ Text="{Binding Result.Info.Timezone, Converter={StaticResource StringNullOrEmptyToStringConverter}}" /> + Text="{Binding Result.Info.UtcOffset, Mode=OneWay, Converter={StaticResource StringNullOrEmptyToStringConverter}}" /> @@ -199,10 +211,12 @@ Margin="0,0,0,10" Foreground="{DynamicResource MahApps.Brushes.Gray3}" /> + Text="{Binding Result.Info.Query, Converter={StaticResource StringNullOrEmptyToStringConverter}}" + ContextMenu="{StaticResource OpenIPAddressContextMenu}" Tag="{Binding OpenIPAddressCommand}" /> + Text="{Binding Result.Info.Reverse, Converter={StaticResource StringNullOrEmptyToStringConverter}}" FontFamily="{StaticResource Fonts.Family.Mono}" + ContextMenu="{StaticResource OpenDNSNameContextMenu}" Tag="{Binding OpenPTRRecordCommand}" /> @@ -226,55 +240,6 @@ Text="{Binding Result.Info.Mobile, Converter={StaticResource BooleanToStringConverter}}" /> - - - - - - - - - - - - - - - - - - - - - - - - - @@ -283,9 +248,32 @@ Style="{StaticResource MessageTextBlock}" /> - + + + +