From 1e54d33b3a05866f9bc310b7ed32697880278676 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:21:59 +0100 Subject: [PATCH 01/44] Export: shared field list and CSV / XML / JSON writer (E1) Every export defines its columns once as ExportField and is written by one generic writer (ExportManager.Export), which also holds the common format rules (invariant culture, RFC 4180 quoting, dates, MAC addresses, lists, JSON types). Lookup (OUI / Port) uses it first, output unchanged. Adds ExportTestHelper and tests for the format rules. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.OUIInfo.cs | 91 +----- .../Export/ExportManager.PortLookupInfo.cs | 98 +----- .../Export/ExportManager.cs | 300 +++++++++++++++++- .../Export/ExportManagerTests.cs | 103 ++++++ .../Export/ExportTestHelper.cs | 181 +++++++++++ Website/docs/changelog/next-release.md | 1 + 6 files changed, 599 insertions(+), 175 deletions(-) create mode 100644 Source/NETworkManager.Tests/Export/ExportManagerTests.cs create mode 100644 Source/NETworkManager.Tests/Export/ExportTestHelper.cs diff --git a/Source/NETworkManager.Models/Export/ExportManager.OUIInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.OUIInfo.cs index f68e80df71..6f0b407d04 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.OUIInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.OUIInfo.cs @@ -1,94 +1,27 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Lookup; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of an . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine($"{nameof(OUIInfo.MACAddress)},{nameof(OUIInfo.Vendor)}"); - - foreach (var info in collection) - stringBuilder.AppendLine($"{info.MACAddress},{CsvHelper.QuoteString(info.Vendor)}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] OUIInfoExportFields = + [ + new(nameof(OUIInfo.MACAddress), x => x.MACAddress), + new(nameof(OUIInfo.Vendor), x => x.Vendor, true) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.Lookup.ToString(), - new XElement(nameof(OUIInfo) + "s", - from info in collection - select - new XElement(nameof(OUIInfo), - new XElement(nameof(OUIInfo.MACAddress), info.MACAddress), - new XElement(nameof(OUIInfo.Vendor), info.Vendor))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].MACAddress, - collection[i].Vendor - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, OUIInfoExportFields, ApplicationName.Lookup); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.PortLookupInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.PortLookupInfo.cs index 5568d0c315..31c4a58494 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.PortLookupInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.PortLookupInfo.cs @@ -1,99 +1,29 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Lookup; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of a . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(PortLookupInfo.Number)},{nameof(PortLookupInfo.Protocol)},{nameof(PortLookupInfo.Service)},{nameof(PortLookupInfo.Description)}"); - - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Number},{info.Protocol},{CsvHelper.QuoteString(info.Service)},{CsvHelper.QuoteString(info.Description)}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] PortLookupInfoExportFields = + [ + new(nameof(PortLookupInfo.Number), x => x.Number), + new(nameof(PortLookupInfo.Protocol), x => x.Protocol), + new(nameof(PortLookupInfo.Service), x => x.Service, true), + new(nameof(PortLookupInfo.Description), x => x.Description, true) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.Lookup.ToString(), - new XElement(nameof(PortLookupInfo) + "s", - from info in collection - select - new XElement(nameof(PortLookupInfo), - new XElement(nameof(PortLookupInfo.Number), info.Number), - new XElement(nameof(PortLookupInfo.Protocol), info.Protocol), - new XElement(nameof(PortLookupInfo.Service), info.Service), - new XElement(nameof(PortLookupInfo.Description), info.Description))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].Number, - Protocol = collection[i].Protocol.ToString(), - collection[i].Service, - collection[i].Description - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, PortLookupInfoExportFields, ApplicationName.Lookup); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index d502f50509..700469f1e1 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -1,11 +1,40 @@ -using System.IO; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net.NetworkInformation; +using System.Numerics; +using System.Text; using System.Xml.Linq; +using NETworkManager.Utilities; +using Newtonsoft.Json; namespace NETworkManager.Models.Export; /// /// This class will provide methods to export text or objects to files like csv, xml, json or plain text. /// +/// +/// Every exported type defines its columns once as a list of (e.g. +/// PingInfoExportFields), the CSV, XML and JSON files are written from this list by +/// . The values have the same format in every tool and are never translated: +/// +/// Names: CSV column = XML element = JSON key, in the same order. Released columns never move, new ones +/// are appended at the end. +/// Empty value (null): empty in CSV, empty element in XML, null in JSON. +/// Numbers with a decimal point (invariant culture), without a unit (e.g. ping time in ms, offset in +/// s - the unit is documented). Bools as True / False (CSV), true / false (XML). +/// JSON: numbers and bools as JSON numbers / bools, everything else as text. +/// Date and time: local time as yyyy-MM-dd HH:mm:ss.fff, time span as [-][d.]hh:mm:ss[.fffffff]. +/// Enums as their (English) name (e.g. Success, flags: ICMP, TCP). +/// MAC addresses as AA:BB:CC:DD:EE:FF. +/// Lists (e.g. IP addresses) as one text, separated by ; . +/// CSV: text that may contain a comma (e.g. hostname, description) is always quoted, any other value +/// only if it contains a comma, a quote or a line break (RFC 4180). +/// +/// public static partial class ExportManager { /// @@ -14,21 +43,21 @@ public static partial class ExportManager private static readonly XDeclaration DefaultXDeclaration = new("1.0", "utf-8", "yes"); /// - /// Method to export text to a file. + /// Format of a date and time in the exported files. /// - /// Path to the export file. - /// Text to export. - public static void Export(string filePath, string content) - { - CreateTxt(content, filePath); - } + private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; + + /// + /// Separator of the values of a list (e.g. IP addresses) in the exported files. + /// + private const string ListSeparator = "; "; /// - /// Create a text file from the given content. + /// Method to export text to a file. /// - /// Content of the text file. /// Path to the export file. - private static void CreateTxt(string content, string filePath) + /// Text to export. + public static void Export(string filePath, string content) { File.WriteAllText(filePath, content); } @@ -49,4 +78,251 @@ public static string GetFileExtensionAsString(ExportFileType fileExtension) _ => string.Empty }; } -} \ No newline at end of file + + #region Fields + + /// + /// Exported column (CSV) / element (XML) / key (JSON) of an object. + /// + /// Type of the exported objects. + /// Name of the column / element / key. + /// + /// Gets the value of an object (e.g. a string, a number, a bool, an enum, an IP address, a date or a list), + /// null for an empty value. Formatted by the writer, see . + /// + /// The value is always quoted in the CSV file (text that may contain a comma). + private sealed record ExportField(string Name, Func GetValue, bool IsQuoted = false); + + /// + /// Value with a list of objects that have fields of their own (e.g. the ports of a host): in the CSV file the + /// values of an item are separated by / and the items by ;, in the XML file every item is an + /// element (), in the JSON file an array of objects. + /// + /// Type of the items. + /// Name of the XML element of an item. + /// Items to export. + /// Exported fields of an item. + private sealed record ExportList( + string ItemName, + IEnumerable Items, + IReadOnlyList> Fields) : IExportList + { + /// + public IEnumerable> GetItems() + { + return Items.Select(item => Fields.Select(field => (field.Name, field.GetValue(item)))); + } + } + + /// + /// Non-generic access to an for the writers. + /// + private interface IExportList + { + /// + /// Name of the XML element of an item. + /// + string ItemName { get; } + + /// + /// Gets the names and values of the fields of every item. + /// + IEnumerable> GetItems(); + } + + #endregion + + #region Writer + + /// + /// Exports the objects with the given fields to a CSV, XML or JSON file. + /// + /// Type of the exported objects. + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects to export. + /// Exported fields (columns) of an object. + /// Tool of the objects (root element of the XML file). + private static void Export(string filePath, ExportFileType fileType, IEnumerable collection, + IReadOnlyList> fields, ApplicationName applicationName) + { + switch (fileType) + { + case ExportFileType.Csv: + CreateCsv(filePath, collection, fields); + break; + case ExportFileType.Xml: + CreateXml(filePath, collection, fields, applicationName); + break; + case ExportFileType.Json: + CreateJson(filePath, collection, fields); + break; + case ExportFileType.Txt: + default: + throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); + } + } + + /// + /// Creates a CSV file: header with the names of the fields, one line per object. + /// + private static void CreateCsv(string filePath, IEnumerable collection, IReadOnlyList> fields) + { + var stringBuilder = new StringBuilder(); + + stringBuilder.AppendLine(string.Join(",", fields.Select(field => field.Name))); + + foreach (var info in collection) + stringBuilder.AppendLine(string.Join(",", fields.Select(field => + { + var fieldValue = field.GetValue(info); + + var value = fieldValue is IExportList list + ? string.Join(";", list.GetItems().Select(item => string.Join("/", item.Select(x => ToText(x.Value))))) + : ToText(fieldValue); + + return field.IsQuoted || IsQuoteRequired(value) ? CsvHelper.QuoteString(value) : value; + }))); + + File.WriteAllText(filePath, stringBuilder.ToString()); + } + + /// + /// Creates a XML file: <Tool><Types><Type> with one element per field. + /// + private static void CreateXml(string filePath, IEnumerable collection, IReadOnlyList> fields, + ApplicationName applicationName) + { + var name = typeof(T).Name; + + var document = new XDocument(DefaultXDeclaration, + new XElement(applicationName.ToString(), + new XElement(name + "s", + from info in collection + select new XElement(name, + from field in fields + from element in ToXmlElements(field.Name, field.GetValue(info)) + select element)))); + + document.Save(filePath); + } + + /// + /// Gets the XML element(s) of a value: one element, or one per item of an (no element + /// for the list itself). + /// + private static IEnumerable ToXmlElements(string name, object value) + { + if (value is IExportList list) + return list.GetItems().Select(item => + new XElement(list.ItemName, item.Select(x => new XElement(x.Name, ToXmlValue(x.Value))))); + + return [new XElement(name, ToXmlValue(value))]; + } + + /// + /// Gets the value of a XML element: bools as XML bools (true / false), everything else as text. + /// + private static object ToXmlValue(object value) + { + return value is bool ? value : ToText(value); + } + + /// + /// Creates a JSON file: array with one object per exported object. + /// + private static void CreateJson(string filePath, IEnumerable collection, + IReadOnlyList> fields) + { + var jsonData = collection + .Select(info => ToJsonObject(fields.Select(field => (field.Name, field.GetValue(info))))) + .ToArray(); + + File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + } + + /// + /// Gets the JSON object of the values (names in the order of the fields). + /// + private static Dictionary ToJsonObject(IEnumerable<(string Name, object Value)> values) + { + var jsonObject = new Dictionary(); + + foreach (var (name, value) in values) + jsonObject.Add(name, value switch + { + IExportList list => list.GetItems().Select(ToJsonObject).ToArray(), + null or bool => value, + _ when IsNumber(value) => value, + _ => ToText(value) + }); + + return jsonObject; + } + + #endregion + + #region Format + + /// + /// Formats a value as text for the CSV / XML file (and non-number values in the JSON file), see + /// . + /// + /// Value to format. + /// Formatted value, null for an empty value. + private static string ToText(object value) + { + return value switch + { + null => null, + string text => text, + DateTime dateTime => dateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture), + TimeSpan timeSpan => timeSpan.ToString("c", CultureInfo.InvariantCulture), + PhysicalAddress physicalAddress => ToText(physicalAddress), + IEnumerable list => string.Join(ListSeparator, list.Cast().Select(ToText)), + IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString() + }; + } + + /// + /// Formats a MAC address as AA:BB:CC:DD:EE:FF (any length, e.g. 8 bytes of a tunnel adapter). + /// + /// MAC address to format. + /// Formatted MAC address, null if it is empty. + private static string ToText(PhysicalAddress physicalAddress) + { + var bytes = physicalAddress.GetAddressBytes(); + + return bytes.Length == 0 ? null : string.Join(":", bytes.Select(x => x.ToString("X2"))); + } + + /// + /// Checks if a value is a number (exported as JSON number). + /// + private static bool IsNumber(object value) + { + return value is byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal + or BigInteger; + } + + /// + /// Checks if a CSV value must be quoted (RFC 4180): it contains a comma, a quote or a line break. + /// + private static bool IsQuoteRequired(string value) + { + return value != null && value.IndexOfAny([',', '"', '\r', '\n']) >= 0; + } + + /// + /// Checks if a ping got a reply (time, TTL and bytes are only set with a reply). + /// + /// Status of the ping. + /// True if the ping got a reply (also of a traceroute hop). + private static bool HasPingReply(IPStatus status) + { + return status is IPStatus.Success or IPStatus.TtlExpired; + } + + #endregion +} diff --git a/Source/NETworkManager.Tests/Export/ExportManagerTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerTests.cs new file mode 100644 index 0000000000..6e1006bfe3 --- /dev/null +++ b/Source/NETworkManager.Tests/Export/ExportManagerTests.cs @@ -0,0 +1,103 @@ +using System; +using System.IO; +using NETworkManager.Models.Export; +using NETworkManager.Models.Lookup; +using NETworkManager.Models.Network; +using Newtonsoft.Json.Linq; +using Xunit; +using static NETworkManager.Tests.Export.ExportTestHelper; + +namespace NETworkManager.Tests.Export; + +/// +/// Format rules of the shared CSV / XML / JSON writer (tested with the Lookup exports). +/// +public class ExportManagerTests +{ + [Fact] + public void PortLookup_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new PortLookupInfo(443, TransportProtocol.Tcp, "https", "http protocol over TLS/SSL")])); + + AssertConsistent(files, "Number,Protocol,Service,Description"); + } + + [Fact] + public void OUI_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [new OUIInfo("00:11:22", "Cisco Systems, Inc")])); + + AssertConsistent(files, "MACAddress,Vendor"); + } + + [Fact] + public void Csv_TextWithCommaAndQuote_Quoted() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new PortLookupInfo(443, TransportProtocol.Tcp, "https", "Secure, \"TLS\"")])); + + Assert.Equal("443,Tcp,\"https\",\"Secure, \"\"TLS\"\"\"", files.CsvLines[1]); + Assert.Equal("Secure, \"TLS\"", files.CsvValue("Description")); + } + + [Fact] + public void Csv_ValueWithCommaNotMarkedAsText_Quoted() + { + // The MAC address column is not quoted - a value with a comma must still not break the line + var files = ExportAll((f, t) => ExportManager.Export(f, t, [new OUIInfo("00,11", "Vendor")])); + + Assert.Equal("\"00,11\",\"Vendor\"", files.CsvLines[1]); + } + + [Fact] + public void Empty_IsEmpty() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [new OUIInfo("00:11:22", null)])); + + Assert.Equal("", files.CsvValue("Vendor")); + Assert.Equal("", files.XmlValue("Vendor")); + Assert.Equal(JTokenType.Null, files.JsonValue("Vendor").Type); + } + + [Fact] + public void Json_NumberAsNumber_EnumAsText() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new PortLookupInfo(53, TransportProtocol.Udp, "domain", "DNS")])); + + Assert.Equal(JTokenType.Integer, files.JsonValue("Number").Type); + Assert.Equal("Udp", (string)files.JsonValue("Protocol")); + Assert.Equal("Udp", files.XmlValue("Protocol")); + Assert.Equal("Udp", files.CsvValue("Protocol")); + } + + [Fact] + public void Xml_Structure() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [new OUIInfo("00:11:22", "Vendor")])); + + Assert.StartsWith("", files.Xml); + Assert.Contains("", files.Xml); + Assert.Contains("", files.Xml); + Assert.Equal("OUIInfo", files.XmlItems[0].Name.LocalName); + } + + [Fact] + public void NoItems_HeaderOnly() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, Array.Empty())); + + Assert.Single(files.CsvLines); + Assert.Empty(files.XmlItems); + Assert.Empty(files.JsonItems); + } + + [Fact] + public void Txt_NotSupported() + { + Assert.Throws(() => + ExportManager.Export(Path.Combine(Path.GetTempPath(), "export.txt"), ExportFileType.Txt, + Array.Empty())); + } +} diff --git a/Source/NETworkManager.Tests/Export/ExportTestHelper.cs b/Source/NETworkManager.Tests/Export/ExportTestHelper.cs new file mode 100644 index 0000000000..7b3a28c1b9 --- /dev/null +++ b/Source/NETworkManager.Tests/Export/ExportTestHelper.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml.Linq; +using NETworkManager.Models.Export; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace NETworkManager.Tests.Export; + +/// +/// Helpers to test the exports of : export to a temporary file, parse the CSV / XML / JSON +/// file and check the format rules shared by all tools. +/// +internal static class ExportTestHelper +{ + /// + /// Exported files of one export (CSV, XML and JSON) - created with the de-DE culture (decimal comma), so a value + /// formatted with the current culture would break the CSV file. + /// + internal sealed record ExportFiles(string Csv, string Xml, string Json) + { + /// CSV header (column names). + public IReadOnlyList CsvHeader => ParseCsvLine(CsvLines[0]); + + /// CSV lines without the header, parsed into the values. + public IReadOnlyList> CsvRows => CsvLines.Skip(1).Select(ParseCsvLine).ToList(); + + /// Raw CSV lines incl. the header. + public IReadOnlyList CsvLines => + Csv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + + /// Elements of the exported objects in the XML file. + public IReadOnlyList XmlItems => XDocument.Parse(Xml).Root!.Elements().Single().Elements().ToList(); + + /// Exported objects in the JSON file. + public IReadOnlyList JsonItems => JArray.Parse(Json).Cast().ToList(); + } + + /// + /// Exports with every file type (CSV, XML, JSON) using the de-DE culture. + /// + /// Export method (file path, file type), e.g. (f, t) => ExportManager.Export(f, t, items). + public static ExportFiles ExportAll(Action export) + { + var culture = CultureInfo.CurrentCulture; + + try + { + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + + return new ExportFiles(Export(export, ExportFileType.Csv), Export(export, ExportFileType.Xml), + Export(export, ExportFileType.Json)); + } + finally + { + CultureInfo.CurrentCulture = culture; + } + } + + /// + /// Exports to a temporary file and returns its content. + /// + private static string Export(Action export, ExportFileType fileType) + { + var filePath = Path.GetTempFileName(); + + try + { + export(filePath, fileType); + + return File.ReadAllText(filePath); + } + finally + { + File.Delete(filePath); + } + } + + /// + /// Checks the rules every export must follow: the expected columns (names and order), the same names in the + /// CSV header, the XML elements and the JSON keys, and one CSV value per column in every row. + /// + /// Exported files. + /// Expected CSV header (released columns must not move). + public static void AssertConsistent(ExportFiles files, string expectedHeader) + { + var header = expectedHeader.Split(','); + + Assert.Equal(header, files.CsvHeader); + + foreach (var row in files.CsvRows) + Assert.Equal(header.Length, row.Count); + + foreach (var item in files.XmlItems) + Assert.Equal(header, item.Elements().Select(x => x.Name.LocalName)); + + foreach (var item in files.JsonItems) + Assert.Equal(header, item.Properties().Select(x => x.Name)); + } + + /// + /// Gets the value of a column of the first CSV row. + /// + public static string CsvValue(this ExportFiles files, string column) + { + var index = files.CsvHeader.ToList().IndexOf(column); + + Assert.True(index >= 0, $"Column {column} not found"); + + return files.CsvRows[0][index]; + } + + /// + /// Gets the value of an element of the first XML item. + /// + public static string XmlValue(this ExportFiles files, string element) + { + return files.XmlItems[0].Element(element)!.Value; + } + + /// + /// Gets the value of a key of the first JSON item. + /// + public static JToken JsonValue(this ExportFiles files, string key) + { + return files.JsonItems[0][key]!; + } + + /// + /// Parses a CSV line (RFC 4180: quoted values may contain commas and doubled quotes). + /// + public static IReadOnlyList ParseCsvLine(string line) + { + var values = new List(); + var value = new StringBuilder(); + var isQuoted = false; + + for (var i = 0; i < line.Length; i++) + { + var c = line[i]; + + if (isQuoted) + { + if (c == '"' && i + 1 < line.Length && line[i + 1] == '"') + { + value.Append('"'); + i++; + } + else if (c == '"') + { + isQuoted = false; + } + else + { + value.Append(c); + } + } + else if (c == '"') + { + isQuoted = true; + } + else if (c == ',') + { + values.Add(value.ToString()); + value.Clear(); + } + else + { + value.Append(c); + } + } + + values.Add(value.ToString()); + + return values; + } +} diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 55d37ec050..4afcf6f444 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -467,5 +467,6 @@ Release date: **xx.xx.2026** - Added a unit test project (xUnit) with tests for the run command parser and the history lists. [#3644](https://github.com/BornToBeRoot/NETworkManager/pull/3644) - Reworked the GitHub issue templates as forms (bug report, feature request, question) that ask for the relevant information (e.g. affected feature, version, installation, Windows version, log), with links to the documentation, discussions, translations and security advisories. Simplified the pull request template and removed the Copilot summary section. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Faster CI: AppVeyor no longer builds a branch a second time when a PR is open, skips changes that only affect the documentation / website, builds ARM64 only for releases and now runs the unit tests. The website is only built for PRs that change it and builds about 3x faster (Docusaurus Faster). Dependabot also updates the GitHub Actions, and CodeQL also scans the workflows. Website changes are only merged automatically if the website builds. Dependabot major updates are no longer merged automatically. Removed the stale bot. [#3675](https://github.com/BornToBeRoot/NETworkManager/pull/3675) +- The exports (CSV, XML, JSON) of all tools define their columns once and are written by one shared writer, so the three formats can't drift apart and every tool formats the same kind of value the same way (not translated). Added unit tests for the exports. - Language files updated via [#transifex](https://github.com/BornToBeRoot/NETworkManager/pulls?q=author%3Aapp%2Ftransifex-integration) - Dependencies updated via [#dependabot](https://github.com/BornToBeRoot/NETworkManager/pulls?q=author%3Aapp%2Fdependabot) From aafd786101c251b7007be5b35f2cb3b2b0b40764 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:22:41 +0100 Subject: [PATCH 02/44] Export: WiFi uses the shared writer (E2) WiFiNetworkExportField removed, list renamed to WiFiNetworkInfoExportFields. JSON: bools and numbers native, XML: time spans like CSV, CSV: invariant culture. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.WiFiNetworkInfo.cs | 106 +----------------- Website/docs/changelog/next-release.md | 1 + 2 files changed, 7 insertions(+), 100 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs index d33a86bf35..3d43f04109 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs @@ -1,34 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Exported column (CSV) / element (XML, JSON key) of a WiFi network, see . + /// Exported fields of a . The released columns come first, new ones are appended at + /// the end, so the position of a column never changes. /// - /// Name of the column / element. - /// Gets the value of a network (e.g. a string, a number, an enum or a time span). - /// The value is quoted in the CSV file (text that may contain a comma, e.g. the SSID). - private sealed record WiFiNetworkExportField( - string Name, - Func GetValue, - bool IsQuoted = false); - - /// - /// Exported values of a WiFi network - one list for CSV, XML and JSON. The released columns come first, new ones - /// are appended at the end, so the position of a column never changes. - /// - private static readonly WiFiNetworkExportField[] WiFiNetworkExportFields = + private static readonly ExportField[] WiFiNetworkInfoExportFields = [ new(nameof(WiFiNetworkInfo.Bssid), x => x.Bssid), new(nameof(WiFiNetworkInfo.AvailableNetwork.Ssid), x => x.AvailableNetwork.Ssid, true), @@ -56,7 +37,7 @@ private sealed record WiFiNetworkExportField( new("ChannelWidthEstimated", x => x.IsChannelBandwidthEstimated), new(nameof(WiFiNetworkInfo.Vendor), x => x.Vendor, true), // Change since the previous scan of the same adapter (empty without a previous scan / change) - new(nameof(WiFiNetworkInfo.Change), x => x.Change == WiFiNetworkChange.None ? null : x.Change.ToString()) + new(nameof(WiFiNetworkInfo.Change), x => x.Change == WiFiNetworkChange.None ? null : x.Change) ]; /// @@ -67,81 +48,6 @@ private sealed record WiFiNetworkExportField( /// Objects as to export. public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine(string.Join(",", WiFiNetworkExportFields.Select(field => field.Name))); - - foreach (var info in collection) - stringBuilder.AppendLine(string.Join(",", WiFiNetworkExportFields.Select(field => - { - var value = Convert.ToString(field.GetValue(info), CultureInfo.CurrentCulture); - - return field.IsQuoted ? CsvHelper.QuoteString(value) : value; - }))); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Creates a XML file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.WiFi.ToString(), - new XElement(nameof(WiFiNetworkInfo) + "s", - from info in collection - select new XElement(nameof(WiFiNetworkInfo), - from field in WiFiNetworkExportFields - select new XElement(field.Name, field.GetValue(info)))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) - { - var jsonData = collection - .Select(info => WiFiNetworkExportFields.ToDictionary(field => field.Name, field => - { - var value = field.GetValue(info); - - // Numbers (frequency), text and empty values as they are, other values (enums, time spans, signal bars, - // RSSI) as text like in the CSV file - return value is null or int or string ? value : Convert.ToString(value, CultureInfo.CurrentCulture); - })) - .ToArray(); - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, WiFiNetworkInfoExportFields, ApplicationName.WiFi); } } diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 4afcf6f444..1bfef0d8ce 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -301,6 +301,7 @@ Release date: **xx.xx.2026** - Fixed the icon of the adapter selection (connected / disconnected) keeping the state of when the adapters were loaded. It is updated after each scan, e.g. after connecting or disconnecting. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Fixed `F5` scanning and **Automatically update every** refreshing the networks behind an open dialog (e.g. **Connect...** or **Export...**). The auto refresh waits until the dialog is closed. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Fixed the CSV export breaking the row of a network whose SSID contains a comma or a quote. SSID, security and vendor are quoted. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- Fixed the export formatting values differently per format: the JSON export contains `IsWiFiDirect`, `IsConnected`, `ChannelWidthEstimated` as `true` / `false` and `SignalBars`, `NetworkRssiInDecibelMilliwatts` as numbers instead of text, the XML export `BeaconInterval` and `Uptime` like the CSV export (e.g. `00:00:00.1024000`) instead of `PT0.1024S`, and the CSV export decimals with a point in every language. - Fixed a network being marked as **Connected** that the selected adapter isn't connected to, if the computer has several WiFi adapters and the selected one was disconnected. An error while reading the connected network no longer ends the scan. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Fixed the connection status message (e.g. "Connecting to ...") being hidden too early, while still connecting, if a previous message (e.g. after connecting or disconnecting) was shown shortly before. Each message is now shown for 15 seconds. [#3638](https://github.com/BornToBeRoot/NETworkManager/pull/3638) - Fixed the adapter list and the auto refresh keeping a removed adapter (e.g. an unplugged USB adapter) after **Refresh** found no adapter or failed: "No WiFi adapters found" is shown now. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) From bf78b053b9f3230a221d747815459bd1789e0ed7 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:24:50 +0100 Subject: [PATCH 03/44] Export: IP Scanner uses the shared writer (E3) GetFields / GetFieldNames / ExportField replaced by GetIPScannerHostInfoExportFields(options) (the header no longer needs a placeholder host). The port fields are defined once (PortInfoExportFields, ExportList). Ping time as number (ms), time / TTL / bytes empty without a reply. Tests moved to Tests/Export, new tests for ping values and ports. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.IPScannerHostInfo.cs | 613 +++++++----------- .../ExportManagerIPScannerTests.cs | 84 ++- Website/docs/changelog/next-release.md | 1 + 3 files changed, 333 insertions(+), 365 deletions(-) rename Source/NETworkManager.Tests/{Network => Export}/ExportManagerIPScannerTests.cs (66%) diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs index 7c938be4df..f24e63c353 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs @@ -1,364 +1,249 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Xml.Linq; -using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; - -namespace NETworkManager.Models.Export; - -public static partial class ExportManager -{ - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - /// - /// Options of the scan the hosts are from. Values of disabled probes are exported as empty values instead of - /// their placeholders (e.g. port status "Closed" if the port scan was disabled). - /// - public static void Export(string filePath, ExportFileType fileType, - IReadOnlyList collection, IPScannerResultOptions options) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, options, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, options, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, options, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Value of an exported column (CSV) / element (XML, JSON key), see . - /// - /// Name of the column / element. - /// Value (e.g. a bool, an enum or a string), null for an empty value. - /// The value is quoted in the CSV file (text that may contain a comma). - private sealed record ExportField(string Name, object Value, bool IsQuoted = false); - - /// - /// Gets the exported values of a host - one list for CSV, XML and JSON. The released columns come first, new - /// ones are appended at the end, so the position of a column never changes. Values of a probe that is still - /// running (export during a scan, or a scan canceled before the probe finished) or disabled are placeholders - - /// exported as empty values instead of a result. The ports are a (joined in the CSV - /// file, one element per port in XML / JSON). - /// - /// Host to export. - /// Options of the scan the host is from. - /// Values in the order of the columns. - private static List GetFields(IPScannerHostInfo info, IPScannerResultOptions options) - { - var ping = GetPingInfo(info, options); - var netBIOSInfo = GetNetBIOSInfo(info, options); - var certificate = GetWebCertificate(info, options); - - // Windows host information: null (empty values) if disabled, "" if the host had none - var windows = options.WindowsEnabled ? info.Windows : null; - - string IfEnabled(bool isEnabled, string value) => isEnabled ? value : null; - - string IfWindows(Func value) => - options.WindowsEnabled ? windows == null ? string.Empty : value(windows) ?? string.Empty : null; - - // Number / bool like WebStatusCode / WebCertificateSelfSigned: null without a value - object IfWindowsValue(Func value) => windows == null ? null : value(windows); - - return - [ - new(nameof(IPScannerHostInfo.IsReachable), info.IsReachable), - new(nameof(PingInfo.IPAddress), info.PingInfo.IPAddress), - new(nameof(IPScannerHostInfo.Hostname), info.Hostname, true), - new("PingStatus", ping?.Status), - new(nameof(PingInfo.Timestamp), - ping == null ? null : DateTimeHelper.DateTimeToFullDateTimeString(ping.Timestamp)), - new(nameof(PingInfo.Time), ping == null ? null : Ping.TimeToString(ping.Status, ping.Time, true)), - new(nameof(PingInfo.TTL), ping?.TTL), - new(nameof(PingInfo.Bytes), ping?.Bytes), - new("PortStatus", GetPortStatus(info, options)), - new(nameof(IPScannerHostInfo.Ports), info.Ports != null && options.PortScanEnabled ? info.Ports : [], true), - new("NetBIOSIsReachable", netBIOSInfo?.IsReachable), - new("NetBIOSIPAddress", netBIOSInfo?.IPAddress), - new("NetBIOSComputerName", netBIOSInfo?.ComputerName, true), - new("NetBIOSUserName", netBIOSInfo?.UserName, true), - new("NetBIOSGroupName", netBIOSInfo?.GroupName, true), - new("NetBIOSMACAddress", netBIOSInfo?.MACAddress), - new("NetBIOSVendor", netBIOSInfo?.Vendor, true), - new(nameof(IPScannerHostInfo.MACAddress), info.MACAddress), - new(nameof(IPScannerHostInfo.Vendor), info.Vendor, true), - // Added later - after the released columns, so their position doesn't change - new(nameof(IPScannerHostInfo.DNSHostname), info.DNSHostname, true), - new(nameof(IPScannerHostInfo.DetectedBy), GetDetectedBy(info), true), - new(nameof(IPScannerHostInfo.OSGuess), GetOSGuess(info, options)), - new(nameof(IPScannerHostInfo.Role), GetRole(info), true), - new(nameof(IPScannerHostInfo.MDNSHostname), IfEnabled(options.MDNSEnabled, info.MDNSHostname), true), - new(nameof(IPScannerHostInfo.WebTitle), IfEnabled(IsWebPageRead(options), info.WebTitle), true), - new(nameof(IPScannerHostInfo.WebURL), IfEnabled(IsWebPageRead(options), info.WebURL), true), - new(nameof(IPScannerHostInfo.SNMPName), IfEnabled(options.SNMPEnabled, info.SNMPName), true), - new(nameof(IPScannerHostInfo.SNMPDescription), IfEnabled(options.SNMPEnabled, info.SNMPDescription), true), - new(nameof(IPScannerHostInfo.SNMPLocation), IfEnabled(options.SNMPEnabled, info.SNMPLocation), true), - new(nameof(IPScannerHostInfo.WebStatusCode), GetWebStatusCode(info, options)), - new(nameof(IPScannerHostInfo.WebServer), IfEnabled(IsWebPageRead(options), info.WebServer), true), - new(nameof(IPScannerHostInfo.WebPoweredBy), IfEnabled(IsWebPageRead(options), info.WebPoweredBy), true), - new(nameof(IPScannerHostInfo.WebRealm), IfEnabled(IsWebPageRead(options), info.WebRealm), true), - new(nameof(IPScannerHostInfo.WebRedirectURL), IfEnabled(IsWebPageRead(options), info.WebRedirectURL), true), - new("WebCertificateSubject", certificate?.Subject, true), - new("WebCertificateIssuer", certificate?.Issuer, true), - new("WebCertificateNotAfter", certificate == null - ? null - : DateTimeHelper.DateTimeToFullDateTimeString(certificate.NotAfter.ToLocalTime())), - new("WebCertificateSelfSigned", certificate?.IsSelfSigned), - // Change since the previous scan of the same input (empty without a previous scan / change) - new(nameof(IPScannerHostInfo.Change), - info.Change == IPScannerHostChange.None ? null : info.Change.ToString()), - new(nameof(IPScannerHostInfo.PreviousMACAddress), info.PreviousMACAddress), - // SNMPv3 error of the host (e.g. "AuthenticationFailed"), empty without - new(nameof(IPScannerHostInfo.SNMPError), - IfEnabled(options.SNMPEnabled, info.HasSNMPError ? info.SNMPError.ToString() : string.Empty), true), - // Windows host information (SMB / NTLM, NetApi) - new("WindowsOS", IfWindows(x => x.OS), true), - new("WindowsEdition", IfWindows(x => x.Edition), true), - new("WindowsVersion", IfWindows(x => x.Version?.ToString())), - new("WindowsRole", IfWindows(x => x.Role == WindowsHostRole.Unknown ? string.Empty : x.Role.ToString())), - new("WindowsComputerName", IfWindows(x => x.ComputerName), true), - new("WindowsDomain", IfWindows(x => x.Domain), true), - // Seconds (time of the host minus the local time) - new("WindowsTimeOffset", - IfWindowsValue(x => x.TimeOffset is { } offset ? Math.Round(offset.TotalSeconds, 3) : null)), - new("WindowsUsers", IfWindows(x => x.Users == null ? string.Empty : string.Join("; ", x.Users)), true), - new("WindowsDescription", IfWindows(x => x.Description), true), - // Win32 error of the NetApi requests (e.g. 5 = access denied, 1326 = wrong username or password) - new("WindowsError", IfWindowsValue(x => x.Error == 0 ? null : x.Error)), - new("SMBDialect", IfWindows(x => x.SMB?.Dialect)), - new("SMBSigningRequired", IfWindowsValue(x => x.SMB?.SigningRequired)), - new("SMBServerGuid", IfWindows(x => x.SMB?.ServerGuid.ToString())) - ]; - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Options of the scan the hosts are from. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, IPScannerResultOptions options, - string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine(string.Join(",", GetFieldNames())); - - foreach (var info in collection) - { - // Skip if critical data is null - if (info?.PingInfo == null) - continue; - - stringBuilder.AppendLine(string.Join(",", GetFields(info, options).Select(field => - { - var value = field.Value is List ports - ? string.Join(";", ports.Select(port => - $"{port.Port}/{port.LookupInfo.Protocol}/{port.LookupInfo.Service}/{port.LookupInfo.Description}/{port.State}")) - // Invariant: a decimal comma would split the column (e.g. WindowsTimeOffset) - : Convert.ToString(field.Value, CultureInfo.InvariantCulture); - - return field.IsQuoted ? CsvHelper.QuoteString(value) : value; - }))); - } - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Gets the names of the exported columns (header of the CSV file, also without hosts) - they don't depend on - /// the values. - /// - private static IEnumerable GetFieldNames() - { - var placeholder = new IPScannerHostInfo(IPAddress.None, false, new PingInfo(), false, [], - new NetBIOSInfo(IPAddress.None)); - - return GetFields(placeholder, new IPScannerResultOptions(false, false, false, false, false, false, false, false, - false, false)).Select(x => x.Name); - } - - /// - /// Creates a XML file from the given collection. - /// - /// Objects as to export. - /// Options of the scan the hosts are from. - /// Path to the export file. - private static void CreateXml(IEnumerable collection, IPScannerResultOptions options, - string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.IPScanner.ToString(), - new XElement(nameof(IPScannerHostInfo) + "s", - from info in collection - where info?.PingInfo != null - select new XElement(nameof(IPScannerHostInfo), - from field in GetFields(info, options) - // One element per port, no element for the list - from element in field.Value is List ports - ? ports.Select(port => new XElement(nameof(PortInfo), - new XElement(nameof(PortInfo.Port), port.Port), - new XElement(nameof(PortInfo.LookupInfo.Protocol), port.LookupInfo.Protocol), - new XElement(nameof(PortInfo.LookupInfo.Service), port.LookupInfo.Service), - new XElement(nameof(PortInfo.LookupInfo.Description), port.LookupInfo.Description), - new XElement(nameof(PortInfo.State), port.State))) - : [new XElement(field.Name, field.Value)] - select element)))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - /// Objects as to export. - /// Options of the scan the hosts are from. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, IPScannerResultOptions options, - string filePath) - { - var jsonData = collection - .Where(info => info?.PingInfo != null) - .Select(info => GetFields(info, options).ToDictionary(x => x.Name, x => x.Value switch - { - List ports => ports.Select(port => new - { - port.Port, - Protocol = port.LookupInfo.Protocol.ToString(), - port.LookupInfo.Service, - port.LookupInfo.Description, - State = port.State.ToString() - }).ToArray(), - // As text, like in the CSV / XML file (not the number of the enum) - Enum or IPAddress => x.Value.ToString(), - _ => x.Value - })) - .ToArray(); - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); - } - - /// - /// Gets the probes a host answered (e.g. "ICMP, TCP"), null if it is unreachable. - /// - /// Host to get the probes for. - /// Probes or null. - private static string GetDetectedBy(IPScannerHostInfo info) - { - return info.DetectedBy == IPScannerDetectionMethod.None ? null : info.DetectedBy.ToString(); - } - - /// - /// Checks if the web pages were read in the scan: only with the port scan (only open ports are requested). - /// - /// Options of the scan the hosts are from. - /// True if the web pages were read. - private static bool IsWebPageRead(IPScannerResultOptions options) - { - return options.PortScanEnabled && options.WebPageEnabled; - } - - /// - /// Gets the HTTP status code of the web page of a host, null if none answered or the web page was not read. - /// - /// Host to get the status code for. - /// Options of the scan the host is from. - /// Status code or null. - private static int? GetWebStatusCode(IPScannerHostInfo info, IPScannerResultOptions options) - { - return IsWebPageRead(options) && info.WebStatusCode > 0 ? info.WebStatusCode : null; - } - - /// - /// Gets the TLS certificate of the web page of a host, null for http, if none answered or the web page was not - /// read. - /// - /// Host to get the certificate for. - /// Options of the scan the host is from. - /// Certificate or null. - private static WebCertificateInfo GetWebCertificate(IPScannerHostInfo info, IPScannerResultOptions options) - { - return IsWebPageRead(options) ? info.WebCertificate : null; - } - - /// - /// Gets the roles of a host for the local computer (e.g. "DefaultGateway, DNSServer"), null if it has none. - /// - /// Host to get the roles for. - /// Roles or null. - private static string GetRole(IPScannerHostInfo info) - { - return info.Role == IPScannerHostRole.None ? null : info.Role.ToString(); - } - - /// - /// Gets the operating system guessed from the TTL (e.g. "Windows"), null if there is no guess or it was disabled. - /// - /// Host to get the guess for. - /// Options of the scan the host is from. - /// Guessed operating system or null. - private static string GetOSGuess(IPScannerHostInfo info, IPScannerResultOptions options) - { - return options.ICMPEnabled && options.OSGuessEnabled && info.OSGuess != IPScannerOSGuess.None - ? info.OSGuess.ToString() - : null; - } - - /// - /// Gets the result of the ping to a host - null while the ping is still running or if it was disabled - /// (placeholder). - /// - /// Host to get the ping result for. - /// Options of the scan the host is from. - /// Result of the ping or null. - private static PingInfo GetPingInfo(IPScannerHostInfo info, IPScannerResultOptions options) - { - return info.IsPingPending || !options.ICMPEnabled ? null : info.PingInfo; - } - - /// - /// Gets the NetBIOS information of a host - null while the NetBIOS request is still running or if it was - /// disabled (placeholder). - /// - /// Host to get the NetBIOS information for. - /// Options of the scan the host is from. - /// NetBIOS information or null. - private static NetBIOSInfo GetNetBIOSInfo(IPScannerHostInfo info, IPScannerResultOptions options) - { - return info.IsNetBIOSPending || !options.NetBIOSEnabled ? null : info.NetBIOSInfo; - } - - /// - /// Gets the port status of a host: open if any port is open, otherwise closed - null while the port scan is - /// still running (no result yet) or if it was disabled. - /// - /// Host to get the port status for. - /// Options of the scan the host is from. - /// Port status or null. - private static PortState? GetPortStatus(IPScannerHostInfo info, IPScannerResultOptions options) - { - if (info.IsPortScanPending || !options.PortScanEnabled) - return null; - - return info.IsAnyPortOpen ? PortState.Open : PortState.Closed; - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using NETworkManager.Models.Network; + +namespace NETworkManager.Models.Export; + +public static partial class ExportManager +{ + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + /// + /// Options of the scan the hosts are from. Values of disabled probes are exported as empty values instead of + /// their placeholders (e.g. port status "Closed" if the port scan was disabled). + /// + public static void Export(string filePath, ExportFileType fileType, + IReadOnlyList collection, IPScannerResultOptions options) + { + // Skip if critical data is null + Export(filePath, fileType, collection.Where(info => info?.PingInfo != null), + GetIPScannerHostInfoExportFields(options), ApplicationName.IPScanner); + } + + /// + /// Exported fields of a (ports of a host, see ). + /// + private static readonly ExportField[] PortInfoExportFields = + [ + new(nameof(PortInfo.Port), x => x.Port), + new(nameof(PortInfo.LookupInfo.Protocol), x => x.LookupInfo.Protocol), + new(nameof(PortInfo.LookupInfo.Service), x => x.LookupInfo.Service), + new(nameof(PortInfo.LookupInfo.Description), x => x.LookupInfo.Description), + new(nameof(PortInfo.State), x => x.State) + ]; + + /// + /// Gets the exported fields of an . The released columns come first, new ones are + /// appended at the end, so the position of a column never changes. Values of a probe that is still running + /// (export during a scan, or a scan canceled before the probe finished) or disabled are placeholders - exported + /// as empty values instead of a result. The ports are an (joined in the CSV + /// file, one element per port in XML, an array in JSON). + /// + /// Options of the scan the hosts are from. + /// Fields in the order of the columns. + private static ExportField[] GetIPScannerHostInfoExportFields(IPScannerResultOptions options) + { + var isWebPageRead = IsWebPageRead(options); + + Func IfEnabled(bool isEnabled, Func value) => + info => isEnabled ? value(info) : null; + + // Ping values only with a reply (time, TTL, bytes) + Func IfPingReply(Func value) => info => + GetPingInfo(info, options) is { } ping && HasPingReply(ping.Status) ? value(ping) : null; + + Func IfNetBIOS(Func value) => info => + GetNetBIOSInfo(info, options) is { } netBIOSInfo ? value(netBIOSInfo) : null; + + Func IfCertificate(Func value) => info => + GetWebCertificate(info, options) is { } certificate ? value(certificate) : null; + + // Windows host information: null (empty values) if disabled, "" if the host had none + Func IfWindows(Func value) => info => + options.WindowsEnabled ? info.Windows == null ? string.Empty : value(info.Windows) ?? string.Empty : null; + + // Number / bool like WebStatusCode / WebCertificateSelfSigned: null without a value + Func IfWindowsValue(Func value) => info => + options.WindowsEnabled && info.Windows != null ? value(info.Windows) : null; + + return + [ + new(nameof(IPScannerHostInfo.IsReachable), x => x.IsReachable), + new(nameof(PingInfo.IPAddress), x => x.PingInfo.IPAddress), + new(nameof(IPScannerHostInfo.Hostname), x => x.Hostname, true), + new("PingStatus", x => GetPingInfo(x, options)?.Status), + new(nameof(PingInfo.Timestamp), x => GetPingInfo(x, options)?.Timestamp), + // ms + new(nameof(PingInfo.Time), IfPingReply(x => x.Time)), + new(nameof(PingInfo.TTL), IfPingReply(x => x.TTL)), + new(nameof(PingInfo.Bytes), IfPingReply(x => x.Bytes)), + new("PortStatus", x => GetPortStatus(x, options)), + new(nameof(IPScannerHostInfo.Ports), x => new ExportList(nameof(PortInfo), + x.Ports != null && options.PortScanEnabled ? x.Ports : [], PortInfoExportFields), true), + new("NetBIOSIsReachable", IfNetBIOS(x => x.IsReachable)), + new("NetBIOSIPAddress", IfNetBIOS(x => x.IPAddress)), + new("NetBIOSComputerName", IfNetBIOS(x => x.ComputerName), true), + new("NetBIOSUserName", IfNetBIOS(x => x.UserName), true), + new("NetBIOSGroupName", IfNetBIOS(x => x.GroupName), true), + new("NetBIOSMACAddress", IfNetBIOS(x => x.MACAddress)), + new("NetBIOSVendor", IfNetBIOS(x => x.Vendor), true), + new(nameof(IPScannerHostInfo.MACAddress), x => x.MACAddress), + new(nameof(IPScannerHostInfo.Vendor), x => x.Vendor, true), + // Added later - after the released columns, so their position doesn't change + new(nameof(IPScannerHostInfo.DNSHostname), x => x.DNSHostname, true), + new(nameof(IPScannerHostInfo.DetectedBy), GetDetectedBy, true), + new(nameof(IPScannerHostInfo.OSGuess), x => GetOSGuess(x, options)), + new(nameof(IPScannerHostInfo.Role), GetRole, true), + new(nameof(IPScannerHostInfo.MDNSHostname), IfEnabled(options.MDNSEnabled, x => x.MDNSHostname), true), + new(nameof(IPScannerHostInfo.WebTitle), IfEnabled(isWebPageRead, x => x.WebTitle), true), + new(nameof(IPScannerHostInfo.WebURL), IfEnabled(isWebPageRead, x => x.WebURL), true), + new(nameof(IPScannerHostInfo.SNMPName), IfEnabled(options.SNMPEnabled, x => x.SNMPName), true), + new(nameof(IPScannerHostInfo.SNMPDescription), IfEnabled(options.SNMPEnabled, x => x.SNMPDescription), + true), + new(nameof(IPScannerHostInfo.SNMPLocation), IfEnabled(options.SNMPEnabled, x => x.SNMPLocation), true), + new(nameof(IPScannerHostInfo.WebStatusCode), x => GetWebStatusCode(x, options)), + new(nameof(IPScannerHostInfo.WebServer), IfEnabled(isWebPageRead, x => x.WebServer), true), + new(nameof(IPScannerHostInfo.WebPoweredBy), IfEnabled(isWebPageRead, x => x.WebPoweredBy), true), + new(nameof(IPScannerHostInfo.WebRealm), IfEnabled(isWebPageRead, x => x.WebRealm), true), + new(nameof(IPScannerHostInfo.WebRedirectURL), IfEnabled(isWebPageRead, x => x.WebRedirectURL), true), + new("WebCertificateSubject", IfCertificate(x => x.Subject), true), + new("WebCertificateIssuer", IfCertificate(x => x.Issuer), true), + new("WebCertificateNotAfter", IfCertificate(x => x.NotAfter.ToLocalTime())), + new("WebCertificateSelfSigned", IfCertificate(x => x.IsSelfSigned)), + // Change since the previous scan of the same input (empty without a previous scan / change) + new(nameof(IPScannerHostInfo.Change), x => x.Change == IPScannerHostChange.None ? null : x.Change), + new(nameof(IPScannerHostInfo.PreviousMACAddress), x => x.PreviousMACAddress), + // SNMPv3 error of the host (e.g. "AuthenticationFailed"), empty without + new(nameof(IPScannerHostInfo.SNMPError), + IfEnabled(options.SNMPEnabled, x => x.HasSNMPError ? x.SNMPError.ToString() : string.Empty), true), + // Windows host information (SMB / NTLM, NetApi) + new("WindowsOS", IfWindows(x => x.OS), true), + new("WindowsEdition", IfWindows(x => x.Edition), true), + new("WindowsVersion", IfWindows(x => x.Version?.ToString())), + new("WindowsRole", IfWindows(x => x.Role == WindowsHostRole.Unknown ? string.Empty : x.Role.ToString())), + new("WindowsComputerName", IfWindows(x => x.ComputerName), true), + new("WindowsDomain", IfWindows(x => x.Domain), true), + // Seconds (time of the host minus the local time) + new("WindowsTimeOffset", + IfWindowsValue(x => x.TimeOffset is { } offset ? Math.Round(offset.TotalSeconds, 3) : null)), + new("WindowsUsers", IfWindows(x => x.Users == null ? string.Empty : string.Join(ListSeparator, x.Users)), + true), + new("WindowsDescription", IfWindows(x => x.Description), true), + // Win32 error of the NetApi requests (e.g. 5 = access denied, 1326 = wrong username or password) + new("WindowsError", IfWindowsValue(x => x.Error == 0 ? null : x.Error)), + new("SMBDialect", IfWindows(x => x.SMB?.Dialect)), + new("SMBSigningRequired", IfWindowsValue(x => x.SMB?.SigningRequired)), + new("SMBServerGuid", IfWindows(x => x.SMB?.ServerGuid.ToString())) + ]; + } + + /// + /// Gets the probes a host answered (e.g. "ICMP, TCP"), null if it is unreachable. + /// + /// Host to get the probes for. + /// Probes or null. + private static string GetDetectedBy(IPScannerHostInfo info) + { + return info.DetectedBy == IPScannerDetectionMethod.None ? null : info.DetectedBy.ToString(); + } + + /// + /// Checks if the web pages were read in the scan: only with the port scan (only open ports are requested). + /// + /// Options of the scan the hosts are from. + /// True if the web pages were read. + private static bool IsWebPageRead(IPScannerResultOptions options) + { + return options.PortScanEnabled && options.WebPageEnabled; + } + + /// + /// Gets the HTTP status code of the web page of a host, null if none answered or the web page was not read. + /// + /// Host to get the status code for. + /// Options of the scan the host is from. + /// Status code or null. + private static int? GetWebStatusCode(IPScannerHostInfo info, IPScannerResultOptions options) + { + return IsWebPageRead(options) && info.WebStatusCode > 0 ? info.WebStatusCode : null; + } + + /// + /// Gets the TLS certificate of the web page of a host, null for http, if none answered or the web page was not + /// read. + /// + /// Host to get the certificate for. + /// Options of the scan the host is from. + /// Certificate or null. + private static WebCertificateInfo GetWebCertificate(IPScannerHostInfo info, IPScannerResultOptions options) + { + return IsWebPageRead(options) ? info.WebCertificate : null; + } + + /// + /// Gets the roles of a host for the local computer (e.g. "DefaultGateway, DNSServer"), null if it has none. + /// + /// Host to get the roles for. + /// Roles or null. + private static string GetRole(IPScannerHostInfo info) + { + return info.Role == IPScannerHostRole.None ? null : info.Role.ToString(); + } + + /// + /// Gets the operating system guessed from the TTL (e.g. "Windows"), null if there is no guess or it was disabled. + /// + /// Host to get the guess for. + /// Options of the scan the host is from. + /// Guessed operating system or null. + private static string GetOSGuess(IPScannerHostInfo info, IPScannerResultOptions options) + { + return options.ICMPEnabled && options.OSGuessEnabled && info.OSGuess != IPScannerOSGuess.None + ? info.OSGuess.ToString() + : null; + } + + /// + /// Gets the result of the ping to a host - null while the ping is still running or if it was disabled + /// (placeholder). + /// + /// Host to get the ping result for. + /// Options of the scan the host is from. + /// Result of the ping or null. + private static PingInfo GetPingInfo(IPScannerHostInfo info, IPScannerResultOptions options) + { + return info.IsPingPending || !options.ICMPEnabled ? null : info.PingInfo; + } + + /// + /// Gets the NetBIOS information of a host - null while the NetBIOS request is still running or if it was + /// disabled (placeholder). + /// + /// Host to get the NetBIOS information for. + /// Options of the scan the host is from. + /// NetBIOS information or null. + private static NetBIOSInfo GetNetBIOSInfo(IPScannerHostInfo info, IPScannerResultOptions options) + { + return info.IsNetBIOSPending || !options.NetBIOSEnabled ? null : info.NetBIOSInfo; + } + + /// + /// Gets the port status of a host: open if any port is open, otherwise closed - null while the port scan is + /// still running (no result yet) or if it was disabled. + /// + /// Host to get the port status for. + /// Options of the scan the host is from. + /// Port status or null. + private static PortState? GetPortStatus(IPScannerHostInfo info, IPScannerResultOptions options) + { + if (info.IsPortScanPending || !options.PortScanEnabled) + return null; + + return info.IsAnyPortOpen ? PortState.Open : PortState.Closed; + } +} \ No newline at end of file diff --git a/Source/NETworkManager.Tests/Network/ExportManagerIPScannerTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs similarity index 66% rename from Source/NETworkManager.Tests/Network/ExportManagerIPScannerTests.cs rename to Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs index e95dbeba69..88db034f4a 100644 --- a/Source/NETworkManager.Tests/Network/ExportManagerIPScannerTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs @@ -6,10 +6,12 @@ using System.Xml.Linq; using NETworkManager.Models.Export; using NETworkManager.Models.Network; +using NETworkManager.Models.Lookup; using Newtonsoft.Json.Linq; using Xunit; +using static NETworkManager.Tests.Export.ExportTestHelper; -namespace NETworkManager.Tests.Network; +namespace NETworkManager.Tests.Export; public class ExportManagerIPScannerTests { @@ -170,4 +172,84 @@ public void Json_SameKeysAsCsv() Assert.Equal(CsvHeader.Split(','), host.Properties().Select(x => x.Name)); } + + private static IPScannerHostInfo CreateHostWithPorts() + { + var ipAddress = IPAddress.Parse("10.0.0.1"); + + return new IPScannerHostInfo(ipAddress, true, + new PingInfo(new DateTime(2026, 11, 8, 10, 15, 30, 123), ipAddress, null, 32, 4, 64, IPStatus.Success), true, + [ + new PortInfo(80, new PortLookupInfo(80, TransportProtocol.Tcp, "http", "World Wide Web, HTTP"), + PortState.Open), + new PortInfo(443, new PortLookupInfo(443, TransportProtocol.Tcp, "https", "TLS"), PortState.Closed) + ], new NetBIOSInfo(ipAddress)); + } + + [Fact] + public void Ping_TimeInMilliseconds() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateHostWithPorts()], AllEnabled)); + + Assert.Equal("2026-11-08 10:15:30.123", files.CsvValue("Timestamp")); + Assert.Equal("4", files.CsvValue("Time")); + Assert.Equal("4", files.XmlValue("Time")); + Assert.Equal(4, (long)files.JsonValue("Time")); + Assert.Equal(64, (int)files.JsonValue("TTL")); + } + + [Fact] + public void Ping_NoReply_TimeTTLBytesEmpty() + { + var ipAddress = IPAddress.Parse("10.0.0.2"); + var host = new IPScannerHostInfo(ipAddress, false, new PingInfo(DateTime.Now, ipAddress, IPStatus.TimedOut), + false, [], new NetBIOSInfo(ipAddress)); + + var files = ExportAll((f, t) => ExportManager.Export(f, t, [host], AllEnabled)); + + foreach (var name in new[] { "Time", "TTL", "Bytes" }) + { + Assert.Equal("", files.CsvValue(name)); + Assert.Equal("", files.XmlValue(name)); + Assert.Equal(JTokenType.Null, files.JsonValue(name).Type); + } + + Assert.Equal("TimedOut", files.CsvValue("PingStatus")); + } + + [Fact] + public void Ports_AllFormats() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateHostWithPorts()], AllEnabled)); + + Assert.Equal(CsvHeader.Split(',').Length, files.CsvRows[0].Count); + Assert.Equal("80/Tcp/http/World Wide Web, HTTP/Open;443/Tcp/https/TLS/Closed", files.CsvValue("Ports")); + + // XML: one element per port (no element for the list) + var ports = files.XmlItems[0].Elements(nameof(PortInfo)).ToList(); + Assert.Equal(2, ports.Count); + Assert.Equal(["Port", "Protocol", "Service", "Description", "State"], + ports[0].Elements().Select(x => x.Name.LocalName)); + Assert.Equal("Tcp", ports[0].Element("Protocol")!.Value); + + // JSON: array of objects + var json = (JArray)files.JsonValue("Ports"); + Assert.Equal(2, json.Count); + Assert.Equal(80, (int)json[0]["Port"]!); + Assert.Equal("Tcp", (string)json[0]["Protocol"]); + Assert.Equal("Open", (string)json[0]["State"]); + } + + [Fact] + public void Ports_PortScanDisabled_Empty() + { + var options = AllEnabled with { PortScanEnabled = false }; + + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateHostWithPorts()], options)); + + Assert.Equal("", files.CsvValue("Ports")); + Assert.Equal("", files.CsvValue("PortStatus")); + Assert.Empty(files.XmlItems[0].Elements(nameof(PortInfo))); + Assert.Empty((JArray)files.JsonValue("Ports")); + } } diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 1bfef0d8ce..21d5496b3e 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -21,6 +21,7 @@ Release date: **xx.xx.2026** - Removed the **ThreadPool additional min. threads** setting (Settings > General) and the application-wide `ThreadPool.SetMinThreads` workaround it configured for the IP Scanner and Port Scanner. It's no longer needed now that both scan engines use non-blocking async concurrency instead of blocking calls. [#3564](https://github.com/BornToBeRoot/NETworkManager/pull/3564) - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. ## What's new? From 7652271eeb4efff6f6f491a389f61e068e47a112 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:25:28 +0100 Subject: [PATCH 04/44] Export: Port Scanner uses the shared writer (E4) Change is empty (JSON null) without a change, like IP Scanner / WiFi. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.PortScannerInfo.cs | 120 +++--------------- .../Export/ExportManagerToolTests.cs | 55 ++++++++ 2 files changed, 74 insertions(+), 101 deletions(-) create mode 100644 Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs diff --git a/Source/NETworkManager.Models/Export/ExportManager.PortScannerInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.PortScannerInfo.cs index 2f34044de8..64c5a1a98f 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.PortScannerInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.PortScannerInfo.cs @@ -1,18 +1,27 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Lookup; using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { + /// + /// Exported fields of a . + /// + private static readonly ExportField[] PortScannerPortInfoExportFields = + [ + new(nameof(PortScannerPortInfo.IPAddress), x => x.IPAddress), + new(nameof(PortScannerPortInfo.Hostname), x => x.Hostname, true), + new(nameof(PortScannerPortInfo.Port), x => x.Port), + new(nameof(PortLookupInfo.Protocol), x => x.LookupInfo.Protocol), + new(nameof(PortLookupInfo.Service), x => x.LookupInfo.Service, true), + new(nameof(PortLookupInfo.Description), x => x.LookupInfo.Description, true), + new(nameof(PortScannerPortInfo.State), x => x.State), + // Change since the previous scan (empty without a previous scan / change) + new(nameof(PortScannerPortInfo.Change), x => x.Change == PortScannerPortChange.None ? null : x.Change) + ]; + /// /// Method to export objects from type to a file. /// @@ -22,97 +31,6 @@ public static partial class ExportManager public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(PortScannerPortInfo.IPAddress)},{nameof(PortScannerPortInfo.Hostname)},{nameof(PortScannerPortInfo.Port)},{nameof(PortLookupInfo.Protocol)},{nameof(PortLookupInfo.Service)},{nameof(PortLookupInfo.Description)},{nameof(PortScannerPortInfo.State)},{nameof(PortScannerPortInfo.Change)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.IPAddress},{CsvHelper.QuoteString(info.Hostname)},{info.Port},{info.LookupInfo.Protocol},{CsvHelper.QuoteString(info.LookupInfo.Service)},{CsvHelper.QuoteString(info.LookupInfo.Description)},{info.State},{GetChange(info)}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Creates a XML file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.PortScanner.ToString(), - new XElement(nameof(PortScannerPortInfo) + "s", - from info in collection - select - new XElement(nameof(PortScannerPortInfo), - new XElement(nameof(PortScannerPortInfo.IPAddress), info.IPAddress), - new XElement(nameof(PortScannerPortInfo.Hostname), info.Hostname), - new XElement(nameof(PortScannerPortInfo.Port), info.Port), - new XElement(nameof(PortLookupInfo.Protocol), info.LookupInfo.Protocol), - new XElement(nameof(PortLookupInfo.Service), info.LookupInfo.Service), - new XElement(nameof(PortLookupInfo.Description), info.LookupInfo.Description), - new XElement(nameof(PortScannerPortInfo.State), info.State), - new XElement(nameof(PortScannerPortInfo.Change), GetChange(info)))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) - { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - IPAddress = collection[i].IPAddress.ToString(), - collection[i].Hostname, - collection[i].Port, - Protocol = collection[i].LookupInfo.Protocol.ToString(), - collection[i].LookupInfo.Service, - collection[i].LookupInfo.Description, - State = collection[i].State.ToString(), - Change = GetChange(collection[i]) - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); - } - - /// - /// Gets the change of a port since the previous scan, empty without a previous scan / change. - /// - private static string GetChange(PortScannerPortInfo info) - { - return info.Change == PortScannerPortChange.None ? string.Empty : info.Change.ToString(); + Export(filePath, fileType, collection, PortScannerPortInfoExportFields, ApplicationName.PortScanner); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs new file mode 100644 index 0000000000..5b0736d393 --- /dev/null +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -0,0 +1,55 @@ +using System; +using System.Net; +using System.Net.NetworkInformation; +using NETworkManager.Models.Export; +using NETworkManager.Models.Lookup; +using NETworkManager.Models.Network; +using Newtonsoft.Json.Linq; +using Xunit; +using static NETworkManager.Tests.Export.ExportTestHelper; + +namespace NETworkManager.Tests.Export; + +/// +/// Exports of the tools: columns (released columns must not move, new ones are appended at the end), the same names in +/// CSV / XML / JSON, one CSV value per column (also with commas and quotes in text) and the shared value formats. +/// +public class ExportManagerToolTests +{ + private static readonly IPAddress IPAddress = IPAddress.Parse("10.0.0.1"); + + private static readonly DateTime Time = new(2026, 11, 8, 10, 15, 30, 123); + + #region Port Scanner + + private static PortScannerPortInfo CreatePort(PortScannerPortChange change = PortScannerPortChange.None) + { + return new PortScannerPortInfo(IPAddress, "host, \"a\"", 443, + new PortLookupInfo(443, TransportProtocol.Tcp, "https", "http protocol over TLS/SSL, secure"), + PortState.Open) { Change = change }; + } + + [Fact] + public void PortScanner_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreatePort(), CreatePort(PortScannerPortChange.Opened)])); + + AssertConsistent(files, "IPAddress,Hostname,Port,Protocol,Service,Description,State,Change"); + Assert.Equal("host, \"a\"", files.CsvValue("Hostname")); + Assert.Equal("Open", files.CsvValue("State")); + } + + [Fact] + public void PortScanner_Change() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreatePort(), CreatePort(PortScannerPortChange.Opened)])); + + // Empty without a change + Assert.Equal("", files.CsvValue("Change")); + Assert.Equal(JTokenType.Null, files.JsonValue("Change").Type); + Assert.Equal("Opened", files.CsvRows[1][7]); + Assert.Equal("Opened", (string)files.JsonItems[1]["Change"]); + } + + #endregion +} From e584a89f48ace94f20f121486eab7cc0a31245f2 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:26:21 +0100 Subject: [PATCH 05/44] Export: Ping Monitor and Traceroute use the shared writer (E5) Times as number (ms), time / TTL / bytes empty without a reply, like the IP Scanner. Ping Monitor hostname quoted in the CSV file. Tests added. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.PingInfo.cs | 109 ++---------- .../Export/ExportManager.TracerouteHopInfo.cs | 167 ++++-------------- .../Export/ExportManagerToolTests.cs | 80 +++++++++ Website/docs/changelog/next-release.md | 3 + 4 files changed, 136 insertions(+), 223 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs index be2027702a..4bb46ab41d 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs @@ -1,107 +1,32 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of a . Bytes, time (ms) and TTL are empty without a reply. /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(PingInfo.Timestamp)},{nameof(PingInfo.IPAddress)},{nameof(PingInfo.Hostname)},{nameof(PingInfo.Bytes)},{nameof(PingInfo.Time)},{nameof(PingInfo.TTL)},{nameof(PingInfo.Status)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{DateTimeHelper.DateTimeToFullDateTimeString(info.Timestamp)},{info.IPAddress},{info.Hostname},{info.Bytes},{Ping.TimeToString(info.Status, info.Time, true)},{info.TTL},{info.Status}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] PingInfoExportFields = + [ + new(nameof(PingInfo.Timestamp), x => x.Timestamp), + new(nameof(PingInfo.IPAddress), x => x.IPAddress), + new(nameof(PingInfo.Hostname), x => x.Hostname, true), + new(nameof(PingInfo.Bytes), x => HasPingReply(x.Status) ? x.Bytes : null), + new(nameof(PingInfo.Time), x => HasPingReply(x.Status) ? x.Time : null), + new(nameof(PingInfo.TTL), x => HasPingReply(x.Status) ? x.TTL : null), + new(nameof(PingInfo.Status), x => x.Status) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.PingMonitor.ToString(), - new XElement(nameof(PingInfo) + "s", - from info in collection - select - new XElement(nameof(PingInfo), - new XElement(nameof(PingInfo.Timestamp), - DateTimeHelper.DateTimeToFullDateTimeString(info.Timestamp)), - new XElement(nameof(PingInfo.IPAddress), info.IPAddress), - new XElement(nameof(PingInfo.Hostname), info.Hostname), - new XElement(nameof(PingInfo.Bytes), info.Bytes), - new XElement(nameof(PingInfo.Time), Ping.TimeToString(info.Status, info.Time, true)), - new XElement(nameof(PingInfo.TTL), info.TTL), - new XElement(nameof(PingInfo.Status), info.Status))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - Timestamp = DateTimeHelper.DateTimeToFullDateTimeString(collection[i].Timestamp), - IPAddress = collection[i].IPAddress.ToString(), - collection[i].Hostname, - collection[i].Bytes, - Time = Ping.TimeToString(collection[i].Status, collection[i].Time, true), - collection[i].TTL, - Status = collection[i].Status.ToString() - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, PingInfoExportFields, ApplicationName.PingMonitor); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs index d02e220bcc..ec89afcacb 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs @@ -1,17 +1,41 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using NETworkManager.Models.IPApi; using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { + /// + /// Exported fields of a . The times (ms) are empty without a reply, the IP + /// geolocation values without a geolocation. + /// + private static readonly ExportField[] TracerouteHopInfoExportFields = + [ + new(nameof(TracerouteHopInfo.Hop), x => x.Hop), + new(nameof(TracerouteHopInfo.Status1), x => x.Status1), + new(nameof(TracerouteHopInfo.Time1), x => HasPingReply(x.Status1) ? x.Time1 : null), + new(nameof(TracerouteHopInfo.Status2), x => x.Status2), + new(nameof(TracerouteHopInfo.Time2), x => HasPingReply(x.Status2) ? x.Time2 : null), + new(nameof(TracerouteHopInfo.Status3), x => x.Status3), + new(nameof(TracerouteHopInfo.Time3), x => HasPingReply(x.Status3) ? x.Time3 : null), + new(nameof(TracerouteHopInfo.IPAddress), x => x.IPAddress), + new(nameof(TracerouteHopInfo.Hostname), x => x.Hostname, true), + new(nameof(IPGeolocationInfo.Continent), IfGeolocation(x => x.Continent), true), + new(nameof(IPGeolocationInfo.Country), IfGeolocation(x => x.Country), true), + new(nameof(IPGeolocationInfo.Region), IfGeolocation(x => x.Region), true), + new(nameof(IPGeolocationInfo.City), IfGeolocation(x => x.City), true), + new(nameof(IPGeolocationInfo.District), IfGeolocation(x => x.District), true), + new(nameof(IPGeolocationInfo.Isp), IfGeolocation(x => x.Isp), true), + new(nameof(IPGeolocationInfo.Org), IfGeolocation(x => x.Org), true), + new(nameof(IPGeolocationInfo.As), IfGeolocation(x => x.As), true), + new(nameof(IPGeolocationInfo.Asname), IfGeolocation(x => x.Asname), true), + new(nameof(IPGeolocationInfo.Hosting), IfGeolocation(x => x.Hosting)), + new(nameof(IPGeolocationInfo.Proxy), IfGeolocation(x => x.Proxy)), + new(nameof(IPGeolocationInfo.Mobile), IfGeolocation(x => x.Mobile)) + ]; + /// /// Method to export objects from type to a file. /// @@ -21,134 +45,15 @@ public static partial class ExportManager public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } + Export(filePath, fileType, collection, TracerouteHopInfoExportFields, ApplicationName.Traceroute); } /// - /// Creates a CSV file from the given collection. + /// Gets a value of the IP geolocation of a hop, null without a geolocation. /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) + /// Value of the IP geolocation. + private static Func IfGeolocation(Func value) { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(TracerouteHopInfo.Hop)},{nameof(TracerouteHopInfo.Status1)},{nameof(TracerouteHopInfo.Time1)},{nameof(TracerouteHopInfo.Status2)},{nameof(TracerouteHopInfo.Time2)},{nameof(TracerouteHopInfo.Status3)},{nameof(TracerouteHopInfo.Time3)},{nameof(TracerouteHopInfo.IPAddress)},{nameof(TracerouteHopInfo.Hostname)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Continent)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Country)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Region)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.City)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.District)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Isp)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Org)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.As)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Asname)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Hosting)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Proxy)},{nameof(TracerouteHopInfo.IPGeolocationResult.Info.Mobile)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Hop},{info.Status1},{Ping.TimeToString(info.Status1, info.Time1, true)},{info.Status2},{Ping.TimeToString(info.Status2, info.Time2, true)},{info.Status3},{Ping.TimeToString(info.Status3, info.Time3, true)},{info.IPAddress}," + - $"{CsvHelper.QuoteString(info.Hostname)},{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.Continent)},{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.Country)}," + - $"{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.Region)},{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.City)},{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.District)}," + - $"{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.Isp)},{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.Org)},{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.As)},{CsvHelper.QuoteString(info.IPGeolocationResult?.Info?.Asname)}," + - $"{info.IPGeolocationResult?.Info?.Hosting},{info.IPGeolocationResult?.Info?.Proxy},{info.IPGeolocationResult?.Info?.Mobile}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Creates a XML file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.Traceroute.ToString(), - new XElement(nameof(TracerouteHopInfo) + "s", - from info in collection - select - new XElement(nameof(TracerouteHopInfo), - new XElement(nameof(TracerouteHopInfo.Hop), info.Hop), - new XElement(nameof(TracerouteHopInfo.Status1), info.Status1), - new XElement(nameof(TracerouteHopInfo.Time1), - Ping.TimeToString(info.Status1, info.Time1, true)), - new XElement(nameof(TracerouteHopInfo.Status2), info.Status2), - new XElement(nameof(TracerouteHopInfo.Time2), - Ping.TimeToString(info.Status2, info.Time2, true)), - new XElement(nameof(TracerouteHopInfo.Status3), info.Status3), - new XElement(nameof(TracerouteHopInfo.Time3), - Ping.TimeToString(info.Status3, info.Time3, true)), - new XElement(nameof(TracerouteHopInfo.IPAddress), info.IPAddress), - new XElement(nameof(TracerouteHopInfo.Hostname), info.Hostname), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Continent), - info.IPGeolocationResult?.Info?.Continent), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Country), - info.IPGeolocationResult?.Info?.Country), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Region), - info.IPGeolocationResult?.Info?.Region), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.City), - info.IPGeolocationResult?.Info?.City), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.District), - info.IPGeolocationResult?.Info?.District), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Isp), - info.IPGeolocationResult?.Info?.Isp), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Org), - info.IPGeolocationResult?.Info?.Org), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.As), - info.IPGeolocationResult?.Info?.As), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Asname), - info.IPGeolocationResult?.Info?.Asname), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Hosting), - info.IPGeolocationResult?.Info?.Hosting), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Proxy), - info.IPGeolocationResult?.Info?.Proxy), - new XElement(nameof(TracerouteHopInfo.IPGeolocationResult.Info.Mobile), - info.IPGeolocationResult?.Info?.Mobile))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) - { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].Hop, - Status1 = collection[i].Status1.ToString(), - Time1 = Ping.TimeToString(collection[i].Status1, collection[i].Time1, true), - Status2 = collection[i].Status2.ToString(), - Time2 = Ping.TimeToString(collection[i].Status2, collection[i].Time2, true), - Status3 = collection[i].Status3.ToString(), - Time3 = Ping.TimeToString(collection[i].Status3, collection[i].Time3, true), - IPAddress = collection[i].IPAddress?.ToString(), - collection[i].Hostname, - Continent = collection[i].IPGeolocationResult?.Info?.Continent, - Country = collection[i].IPGeolocationResult?.Info?.Country, - Region = collection[i].IPGeolocationResult?.Info?.Region, - City = collection[i].IPGeolocationResult?.Info?.City, - District = collection[i].IPGeolocationResult?.Info?.District, - Isp = collection[i].IPGeolocationResult?.Info?.Isp, - Org = collection[i].IPGeolocationResult?.Info?.Org, - As = collection[i].IPGeolocationResult?.Info?.As, - Asname = collection[i].IPGeolocationResult?.Info?.Asname, - Hosting = collection[i].IPGeolocationResult?.Info?.Hosting, - Proxy = collection[i].IPGeolocationResult?.Info?.Proxy, - Mobile = collection[i].IPGeolocationResult?.Info?.Mobile - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + return x => x.IPGeolocationResult?.Info is { } info ? value(info) : null; } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 5b0736d393..2f2d5ebac9 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -2,6 +2,7 @@ using System.Net; using System.Net.NetworkInformation; using NETworkManager.Models.Export; +using NETworkManager.Models.IPApi; using NETworkManager.Models.Lookup; using NETworkManager.Models.Network; using Newtonsoft.Json.Linq; @@ -52,4 +53,83 @@ public void PortScanner_Change() } #endregion + + #region Ping Monitor + + [Fact] + public void PingMonitor_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new PingInfo(Time, IPAddress, "host, a", 32, 4, 128, IPStatus.Success), + new PingInfo(Time, IPAddress, "host, a", IPStatus.TimedOut) + ])); + + AssertConsistent(files, "Timestamp,IPAddress,Hostname,Bytes,Time,TTL,Status"); + Assert.Equal("2026-11-08 10:15:30.123", files.CsvValue("Timestamp")); + Assert.Equal("2026-11-08 10:15:30.123", files.XmlValue("Timestamp")); + Assert.Equal("2026-11-08 10:15:30.123", (string)files.JsonValue("Timestamp")); + Assert.Equal("host, a", files.CsvValue("Hostname")); + + // Time in ms as number + Assert.Equal("4", files.CsvValue("Time")); + Assert.Equal(4, (long)files.JsonValue("Time")); + Assert.Equal(128, (int)files.JsonValue("TTL")); + } + + [Fact] + public void PingMonitor_NoReply_Empty() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new PingInfo(Time, IPAddress, "host", IPStatus.TimedOut)])); + + Assert.Equal("2026-11-08 10:15:30.123,10.0.0.1,\"host\",,,,TimedOut", files.CsvLines[1]); + Assert.Equal(JTokenType.Null, files.JsonValue("Time").Type); + Assert.Equal(JTokenType.Null, files.JsonValue("TTL").Type); + Assert.Equal(JTokenType.Null, files.JsonValue("Bytes").Type); + } + + #endregion + + #region Traceroute + + [Fact] + public void Traceroute_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new TracerouteHopInfo(1, IPStatus.Success, 1, IPStatus.TimedOut, 0, IPStatus.TtlExpired, 3, IPAddress, + "gw, 1", new IPGeolocationResult(CreateGeolocation())), + new TracerouteHopInfo(2, IPStatus.TimedOut, 0, IPStatus.TimedOut, 0, IPStatus.TimedOut, 0, null, null, null) + ])); + + AssertConsistent(files, + "Hop,Status1,Time1,Status2,Time2,Status3,Time3,IPAddress,Hostname,Continent,Country,Region,City,District," + + "Isp,Org,As,Asname,Hosting,Proxy,Mobile"); + + Assert.Equal("1", files.CsvValue("Time1")); + Assert.Equal("", files.CsvValue("Time2")); + Assert.Equal("3", files.CsvValue("Time3")); + Assert.Equal("Example, Inc.", files.CsvValue("Isp")); + Assert.Equal(JTokenType.Boolean, files.JsonValue("Proxy").Type); + + // Hop without reply and geolocation + Assert.Equal(JTokenType.Null, files.JsonItems[1]["Time1"]!.Type); + Assert.Equal(JTokenType.Null, files.JsonItems[1]["Country"]!.Type); + Assert.Equal(JTokenType.Null, files.JsonItems[1]["Proxy"]!.Type); + } + + #endregion + + private static IPGeolocationInfo CreateGeolocation() + { + return new IPGeolocationInfo + { + Status = "success", Continent = "Europe", ContinentCode = "EU", Country = "Germany", CountryCode = "DE", + Region = "BY", RegionName = "Bavaria", City = "Munich", District = "", Zip = "80331", Lat = 48.1374, + Lon = 11.5755, Timezone = "Europe/Berlin", Offset = 3600, Currency = "EUR", Isp = "Example, Inc.", + Org = "Org \"Quoted\"", As = "AS1 Example", Asname = "EXAMPLE", Reverse = "host.example.com", + Mobile = false, Proxy = true, Hosting = false, Query = "1.2.3.4" + }; + } } diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 21d5496b3e..e7d1f556b5 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -22,6 +22,8 @@ Release date: **xx.xx.2026** - Removed the **ThreadPool additional min. threads** setting (Settings > General) and the application-wide `ThreadPool.SetMinThreads` workaround it configured for the IP Scanner and Port Scanner. It's no longer needed now that both scan engines use non-blocking async concurrency instead of blocking calls. [#3564](https://github.com/BornToBeRoot/NETworkManager/pull/3564) - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. +- **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. +- **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. ## What's new? @@ -371,6 +373,7 @@ Release date: **xx.xx.2026** - Fixed the ping not working when the ICMP **Buffer** was set to more than `65500` bytes (Windows limit). The maximum is now `65500`, higher values are lowered to `65500`. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) - Fixed hosts being added twice if the inputs overlap (e.g. `10.0.0.1; 10.0.0.0/24`). If an IP address is also entered as hostname, the hostname is kept; different hostnames of the same IP address (e.g. two names of one server) are all kept. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) - Fixed **Copy** > **Hostname** copying a hostname resolved via DNS (`PTR`) with a trailing dot (e.g. `server.example.com.`). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- Fixed the CSV export breaking the row if the hostname contains a comma. The hostname is quoted now. **Traceroute** From a68a306b9f116e424c37e277522b6c7d082c3511 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:27:30 +0100 Subject: [PATCH 06/44] Export: Network Interface uses the shared writer (E6) MAC address as AA:BB:CC:DD:EE:FF (JSON: no longer {}), status as text, DHCP lease in the common date format (empty without DHCP), lists with "; ", name / description / DNS suffix quoted, new Profile column. Empty lists are empty values in all exports. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.NetworkInterface.cs | 164 +++++------------- .../Export/ExportManager.cs | 5 +- .../Export/ExportManagerToolTests.cs | 74 ++++++++ Website/docs/changelog/next-release.md | 3 + 4 files changed, 122 insertions(+), 124 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs b/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs index 6b28e6b4f9..0bee5741c8 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs @@ -1,146 +1,64 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Text; -using System.Xml.Linq; using NETworkManager.Models.Network; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of a . The released columns come first, new ones are + /// appended at the end, so the position of a column never changes. /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } + private static readonly ExportField[] NetworkInterfaceInfoExportFields = + [ + new(nameof(NetworkInterfaceInfo.Id), x => x.Id), + new(nameof(NetworkInterfaceInfo.Name), x => x.Name, true), + new(nameof(NetworkInterfaceInfo.Description), x => x.Description, true), + new(nameof(NetworkInterfaceInfo.Type), x => x.Type), + new(nameof(NetworkInterfaceInfo.PhysicalAddress), x => x.PhysicalAddress), + new(nameof(NetworkInterfaceInfo.Status), x => x.Status), + new(nameof(NetworkInterfaceInfo.IsOperational), x => x.IsOperational), + // Bit/s + new(nameof(NetworkInterfaceInfo.Speed), x => x.Speed), + new(nameof(NetworkInterfaceInfo.IPv4ProtocolAvailable), x => x.IPv4ProtocolAvailable), + // IP address with prefix length (e.g. 192.168.1.10/24) + new(nameof(NetworkInterfaceInfo.IPv4Address), + x => x.IPv4Address?.Select(ip => $"{ip.Item1}/{Subnetmask.ConvertSubnetmaskToCidr(ip.Item2)}")), + new(nameof(NetworkInterfaceInfo.IPv4Gateway), x => x.IPv4Gateway), + new(nameof(NetworkInterfaceInfo.DhcpEnabled), x => x.DhcpEnabled), + new(nameof(NetworkInterfaceInfo.DhcpServer), x => x.DhcpServer), + // Empty without DHCP + new(nameof(NetworkInterfaceInfo.DhcpLeaseObtained), x => GetDhcpLease(x.DhcpLeaseObtained)), + new(nameof(NetworkInterfaceInfo.DhcpLeaseExpires), x => GetDhcpLease(x.DhcpLeaseExpires)), + new(nameof(NetworkInterfaceInfo.IPv6ProtocolAvailable), x => x.IPv6ProtocolAvailable), + new(nameof(NetworkInterfaceInfo.IPv6Address), x => x.IPv6Address), + new(nameof(NetworkInterfaceInfo.IPv6AddressLinkLocal), x => x.IPv6AddressLinkLocal), + new(nameof(NetworkInterfaceInfo.IPv6Gateway), x => x.IPv6Gateway), + new(nameof(NetworkInterfaceInfo.DNSAutoconfigurationEnabled), x => x.DNSAutoconfigurationEnabled), + new(nameof(NetworkInterfaceInfo.DNSSuffix), x => x.DNSSuffix, true), + new(nameof(NetworkInterfaceInfo.DNSServer), x => x.DNSServer), + // Added later - after the released columns, so their position doesn't change + new(nameof(NetworkInterfaceInfo.Profile), x => x.Profile) + ]; /// - /// Creates a CSV file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(NetworkInterfaceInfo.Id)},{nameof(NetworkInterfaceInfo.Name)},{nameof(NetworkInterfaceInfo.Description)},{nameof(NetworkInterfaceInfo.Type)},{nameof(NetworkInterfaceInfo.PhysicalAddress)},{nameof(NetworkInterfaceInfo.Status)},{nameof(NetworkInterfaceInfo.IsOperational)},{nameof(NetworkInterfaceInfo.Speed)},{nameof(NetworkInterfaceInfo.IPv4ProtocolAvailable)},{nameof(NetworkInterfaceInfo.IPv4Address)},{nameof(NetworkInterfaceInfo.IPv4Gateway)},{nameof(NetworkInterfaceInfo.DhcpEnabled)},{nameof(NetworkInterfaceInfo.DhcpServer)},{nameof(NetworkInterfaceInfo.DhcpLeaseObtained)},{nameof(NetworkInterfaceInfo.DhcpLeaseExpires)},{nameof(NetworkInterfaceInfo.IPv6ProtocolAvailable)},{nameof(NetworkInterfaceInfo.IPv6Address)},{nameof(NetworkInterfaceInfo.IPv6AddressLinkLocal)},{nameof(NetworkInterfaceInfo.IPv6Gateway)},{nameof(NetworkInterfaceInfo.DNSAutoconfigurationEnabled)},{nameof(NetworkInterfaceInfo.DNSSuffix)},{nameof(NetworkInterfaceInfo.DNSServer)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Id},{info.Name},{info.Description},{info.Type},{info.PhysicalAddress},{info.Status},{info.IsOperational},{info.Speed},{info.IPv4ProtocolAvailable},{IPv4Address.ConvertIPAddressWithSubnetmaskListToString(info.IPv4Address, ";")},{IPv4Address.ConvertIPAddressListToString(info.IPv4Gateway, ";")},{info.DhcpEnabled},{IPv4Address.ConvertIPAddressListToString(info.DhcpServer, ";")},{info.DhcpLeaseObtained},{info.DhcpLeaseExpires},{info.IPv6ProtocolAvailable},{IPv4Address.ConvertIPAddressListToString(info.IPv6Address, ";")},{IPv4Address.ConvertIPAddressListToString(info.IPv6AddressLinkLocal, ";")},{IPv4Address.ConvertIPAddressListToString(info.IPv6Gateway, ";")},{info.DNSAutoconfigurationEnabled},{info.DNSSuffix},{IPv4Address.ConvertIPAddressListToString(info.DNSServer, ";")}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Creates a XML file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.NetworkInterface.ToString(), - new XElement(nameof(NetworkInterfaceInfo) + "s", - from info in collection - select - new XElement(nameof(NetworkInterfaceInfo), - new XElement(nameof(NetworkInterfaceInfo.Id), info.Id), - new XElement(nameof(NetworkInterfaceInfo.Name), info.Name), - new XElement(nameof(NetworkInterfaceInfo.Description), info.Description), - new XElement(nameof(NetworkInterfaceInfo.Type), info.Type), - new XElement(nameof(NetworkInterfaceInfo.PhysicalAddress), info.PhysicalAddress), - new XElement(nameof(NetworkInterfaceInfo.Status), info.Status), - new XElement(nameof(NetworkInterfaceInfo.IsOperational), info.IsOperational), - new XElement(nameof(NetworkInterfaceInfo.Speed), info.Speed), - new XElement(nameof(NetworkInterfaceInfo.IPv4ProtocolAvailable), - info.IPv4ProtocolAvailable), - new XElement(nameof(NetworkInterfaceInfo.IPv4Address), - IPv4Address.ConvertIPAddressWithSubnetmaskListToString(info.IPv4Address, ";")), - new XElement(nameof(NetworkInterfaceInfo.IPv4Gateway), - IPv4Address.ConvertIPAddressListToString(info.IPv4Gateway, ";")), - new XElement(nameof(NetworkInterfaceInfo.DhcpEnabled), info.DhcpEnabled), - new XElement(nameof(NetworkInterfaceInfo.DhcpServer), - IPv4Address.ConvertIPAddressListToString(info.DhcpServer, ";")), - new XElement(nameof(NetworkInterfaceInfo.DhcpLeaseObtained), info.DhcpLeaseObtained), - new XElement(nameof(NetworkInterfaceInfo.DhcpLeaseExpires), info.DhcpLeaseExpires), - new XElement(nameof(NetworkInterfaceInfo.IPv6ProtocolAvailable), - info.IPv6ProtocolAvailable), - new XElement(nameof(NetworkInterfaceInfo.IPv6Address), - IPv4Address.ConvertIPAddressListToString(info.IPv6Address, ";")), - new XElement(nameof(NetworkInterfaceInfo.IPv6AddressLinkLocal), - IPv4Address.ConvertIPAddressListToString(info.IPv6AddressLinkLocal, ";")), - new XElement(nameof(NetworkInterfaceInfo.IPv6Gateway), - IPv4Address.ConvertIPAddressListToString(info.IPv6Gateway, ";")), - new XElement(nameof(NetworkInterfaceInfo.DNSAutoconfigurationEnabled), - info.DNSAutoconfigurationEnabled), - new XElement(nameof(NetworkInterfaceInfo.DNSSuffix), info.DNSSuffix), - new XElement(nameof(NetworkInterfaceInfo.DNSServer), - IPv4Address.ConvertIPAddressListToString(info.DNSServer, ";")))))); - - document.Save(filePath); + Export(filePath, fileType, collection, NetworkInterfaceInfoExportFields, ApplicationName.NetworkInterface); } /// - /// Creates a JSON file from the given collection. + /// Gets the time of a DHCP lease, null if not set (no DHCP). /// - /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + private static DateTime? GetDhcpLease(DateTime dateTime) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].Id, - collection[i].Name, - collection[i].Description, - collection[i].Type, - collection[i].PhysicalAddress, - collection[i].Status, - collection[i].IsOperational, - collection[i].Speed, - collection[i].IPv4ProtocolAvailable, - IPv4Address = IPv4Address.ConvertIPAddressWithSubnetmaskListToString(collection[i].IPv4Address, ";"), - IPv4Gateway = IPv4Address.ConvertIPAddressListToString(collection[i].IPv4Gateway, ";"), - collection[i].DhcpEnabled, - DhcpServer = IPv4Address.ConvertIPAddressListToString(collection[i].DhcpServer, ";"), - collection[i].DhcpLeaseObtained, - collection[i].DhcpLeaseExpires, - collection[i].IPv6ProtocolAvailable, - IPv6Address = IPv4Address.ConvertIPAddressListToString(collection[i].IPv6Address, ";"), - IPv6AddressLinkLocal = - IPv4Address.ConvertIPAddressListToString(collection[i].IPv6AddressLinkLocal, ";"), - IPv6Gateway = IPv4Address.ConvertIPAddressListToString(collection[i].IPv6Gateway, ";"), - collection[i].DNSAutoconfigurationEnabled, - collection[i].DNSSuffix, - DNSServer = IPv4Address.ConvertIPAddressListToString(collection[i].DNSServer, ";") - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + return dateTime == DateTime.MinValue ? null : dateTime; } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index 700469f1e1..b4f25726a3 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -279,7 +279,10 @@ private static string ToText(object value) DateTime dateTime => dateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture), TimeSpan timeSpan => timeSpan.ToString("c", CultureInfo.InvariantCulture), PhysicalAddress physicalAddress => ToText(physicalAddress), - IEnumerable list => string.Join(ListSeparator, list.Cast().Select(ToText)), + // Empty list: empty value + IEnumerable list => list.Cast().Select(ToText).ToList() is { Count: > 0 } items + ? string.Join(ListSeparator, items) + : null, IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), _ => value.ToString() }; diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 2f2d5ebac9..253029aa87 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -121,6 +121,80 @@ public void Traceroute_Consistent() #endregion + #region Network Interface + + private static NetworkInterfaceInfo CreateNetworkInterface() + { + return new NetworkInterfaceInfo + { + Id = "{GUID}", Name = "Ethernet, 2", Description = "Intel(R) Ethernet \"I219\"", Type = "Ethernet", + PhysicalAddress = PhysicalAddress.Parse("00-11-22-AA-BB-CC"), Status = OperationalStatus.Up, + IsOperational = true, Speed = 1000000000, IPv4ProtocolAvailable = true, + IPv4Address = [Tuple.Create(IPAddress, IPAddress.Parse("255.255.255.0"))], + IPv4Gateway = [IPAddress.Parse("10.0.0.254")], DhcpEnabled = true, + DhcpServer = [IPAddress.Parse("10.0.0.254")], DhcpLeaseObtained = Time, DhcpLeaseExpires = Time.AddDays(1), + IPv6ProtocolAvailable = true, IPv6Address = [IPAddress.Parse("fd00::1")], + IPv6AddressLinkLocal = [IPAddress.Parse("fe80::1")], IPv6Gateway = [], DNSAutoconfigurationEnabled = true, + DNSSuffix = "corp.example.com", DNSServer = [IPAddress.Parse("10.0.0.53"), IPAddress.Parse("10.0.0.54")], + Profile = NetworkProfile.Private + }; + } + + [Fact] + public void NetworkInterface_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateNetworkInterface()])); + + AssertConsistent(files, + "Id,Name,Description,Type,PhysicalAddress,Status,IsOperational,Speed,IPv4ProtocolAvailable,IPv4Address," + + "IPv4Gateway,DhcpEnabled,DhcpServer,DhcpLeaseObtained,DhcpLeaseExpires,IPv6ProtocolAvailable,IPv6Address," + + "IPv6AddressLinkLocal,IPv6Gateway,DNSAutoconfigurationEnabled,DNSSuffix,DNSServer,Profile"); + Assert.Equal("Ethernet, 2", files.CsvValue("Name")); + Assert.Equal("Private", files.CsvValue("Profile")); + } + + [Fact] + public void NetworkInterface_Values() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateNetworkInterface()])); + + // MAC address like in the other tools, status as text (also in JSON) + Assert.Equal("00:11:22:AA:BB:CC", files.CsvValue("PhysicalAddress")); + Assert.Equal("00:11:22:AA:BB:CC", (string)files.JsonValue("PhysicalAddress")); + Assert.Equal("Up", (string)files.JsonValue("Status")); + Assert.Equal(1000000000, (long)files.JsonValue("Speed")); + + // Lists separated by "; ", empty list empty + Assert.Equal("10.0.0.1/24", files.CsvValue("IPv4Address")); + Assert.Equal("10.0.0.53; 10.0.0.54", files.CsvValue("DNSServer")); + Assert.Equal("10.0.0.53; 10.0.0.54", files.XmlValue("DNSServer")); + Assert.Equal("10.0.0.53; 10.0.0.54", (string)files.JsonValue("DNSServer")); + Assert.Equal(JTokenType.Null, files.JsonValue("IPv6Gateway").Type); + + // Date and time like in the other tools + Assert.Equal("2026-11-08 10:15:30.123", files.CsvValue("DhcpLeaseObtained")); + Assert.Equal("2026-11-08 10:15:30.123", files.XmlValue("DhcpLeaseObtained")); + Assert.Equal("2026-11-09 10:15:30.123", (string)files.JsonValue("DhcpLeaseExpires")); + } + + [Fact] + public void NetworkInterface_WithoutDhcpAndMACAddress_Empty() + { + var networkInterface = CreateNetworkInterface(); + networkInterface.PhysicalAddress = PhysicalAddress.None; + networkInterface.DhcpEnabled = false; + networkInterface.DhcpLeaseObtained = new DateTime(); + networkInterface.DhcpLeaseExpires = new DateTime(); + + var files = ExportAll((f, t) => ExportManager.Export(f, t, [networkInterface])); + + Assert.Equal("", files.CsvValue("PhysicalAddress")); + Assert.Equal("", files.CsvValue("DhcpLeaseObtained")); + Assert.Equal(JTokenType.Null, files.JsonValue("DhcpLeaseExpires").Type); + } + + #endregion + private static IPGeolocationInfo CreateGeolocation() { return new IPGeolocationInfo diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index e7d1f556b5..45c300d165 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -24,6 +24,7 @@ Release date: **xx.xx.2026** - **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. - **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. +- **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. ## What's new? @@ -73,6 +74,7 @@ Release date: **xx.xx.2026** **Network Interface** - Members of the **Network Configuration Operators** group can now change the network configuration (IP address, DNS servers, release/renew) without being an administrator. NETworkManager has to run elevated (**Restart as Administrator**, confirm with your own credentials). The hint is now also shown as tooltip on **Apply** in the profile context menu. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) +- The export contains the network profile (`Profile`, e.g. `Private`) as last column / element. **WiFi** @@ -278,6 +280,7 @@ Release date: **xx.xx.2026** **Network Interface** - Fixed errors when changing the network configuration (e.g. missing permissions) not being shown — the change was reported as successful although it failed. The error message of Windows is now shown. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) +- Fixed the CSV export breaking the row if the name, the description or the DNS suffix contains a comma (they are quoted now), and the JSON export containing the MAC address as `{}` and the status as a number (e.g. `1` instead of `Up`). **WiFi** From d81c1848a4de929b9e893111d16932a56e2fb50c Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:28:10 +0100 Subject: [PATCH 07/44] Export: DNS Lookup and SNTP Lookup use the shared writer (E7) DNS Lookup text quoted in the CSV file (TXT records with commas). SNTP offset / round trip delay as numbers (s / ms) with a decimal point. Co-Authored-By: Claude Opus 5.5 --- .../ExportManager.DNSLookupRecordInfo.cs | 110 +++-------------- .../ExportManager.SNTPLookupResultInfo.cs | 115 +++--------------- .../Export/ExportManagerToolTests.cs | 43 +++++++ Website/docs/changelog/next-release.md | 3 + 4 files changed, 83 insertions(+), 188 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.DNSLookupRecordInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.DNSLookupRecordInfo.cs index 7e56e5bc40..a80b93d8c6 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.DNSLookupRecordInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.DNSLookupRecordInfo.cs @@ -1,16 +1,25 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { + /// + /// Exported fields of a . + /// + private static readonly ExportField[] DNSLookupRecordInfoExportFields = + [ + new(nameof(DNSLookupRecordInfo.DomainName), x => x.DomainName, true), + new(nameof(DNSLookupRecordInfo.TTL), x => x.TTL), + new(nameof(DNSLookupRecordInfo.RecordClass), x => x.RecordClass), + new(nameof(DNSLookupRecordInfo.RecordType), x => x.RecordType), + new(nameof(DNSLookupRecordInfo.Result), x => x.Result, true), + new(nameof(DNSLookupRecordInfo.NameServerIPAddress), x => x.NameServerIPAddress), + new(nameof(DNSLookupRecordInfo.NameServerHostName), x => x.NameServerHostName, true), + new(nameof(DNSLookupRecordInfo.NameServerPort), x => x.NameServerPort) + ]; + /// /// Method to export objects from type to a file. /// @@ -20,89 +29,6 @@ public static partial class ExportManager public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(DNSLookupRecordInfo.DomainName)},{nameof(DNSLookupRecordInfo.TTL)},{nameof(DNSLookupRecordInfo.RecordClass)},{nameof(DNSLookupRecordInfo.RecordType)},{nameof(DNSLookupRecordInfo.Result)},{nameof(DNSLookupRecordInfo.NameServerIPAddress)},{nameof(DNSLookupRecordInfo.NameServerHostName)},{nameof(DNSLookupRecordInfo.NameServerPort)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.DomainName},{info.TTL},{info.RecordClass},{info.RecordType},{info.Result},{info.NameServerIPAddress},{info.NameServerHostName},{info.NameServerPort}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Creates a XML file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.DNSLookup.ToString(), - new XElement(nameof(DNSLookupRecordInfo) + "s", - from info in collection - select - new XElement(nameof(DNSLookupRecordInfo), - new XElement(nameof(DNSLookupRecordInfo.DomainName), info.DomainName), - new XElement(nameof(DNSLookupRecordInfo.TTL), info.TTL), - new XElement(nameof(DNSLookupRecordInfo.RecordClass), info.RecordClass), - new XElement(nameof(DNSLookupRecordInfo.RecordType), info.RecordType), - new XElement(nameof(DNSLookupRecordInfo.Result), info.Result), - new XElement(nameof(DNSLookupRecordInfo.NameServerIPAddress), info.NameServerIPAddress), - new XElement(nameof(DNSLookupRecordInfo.NameServerHostName), info.NameServerHostName), - new XElement(nameof(DNSLookupRecordInfo.NameServerPort), info.NameServerPort))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) - { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].DomainName, - collection[i].TTL, - collection[i].RecordClass, - collection[i].RecordType, - collection[i].Result, - collection[i].NameServerIPAddress, - collection[i].NameServerHostName, - collection[i].NameServerPort - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, DNSLookupRecordInfoExportFields, ApplicationName.DNSLookup); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.SNTPLookupResultInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.SNTPLookupResultInfo.cs index d2b9a16064..5a50124033 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.SNTPLookupResultInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.SNTPLookupResultInfo.cs @@ -1,111 +1,34 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, - IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. + /// Exported fields of a . /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(SNTPLookupInfo.Server)},{nameof(SNTPLookupInfo.IPEndPoint)},{nameof(SNTPLookupInfo.DateTime.NetworkTime)},{nameof(SNTPLookupInfo.DateTime.LocalStartTime)},{nameof(SNTPLookupInfo.DateTime.LocalEndTime)},{nameof(SNTPLookupInfo.DateTime.Offset)},{nameof(SNTPLookupInfo.DateTime.RoundTripDelay)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Server},{info.IPEndPoint},{DateTimeHelper.DateTimeToFullDateTimeString(info.DateTime.NetworkTime)},{DateTimeHelper.DateTimeToFullDateTimeString(info.DateTime.LocalStartTime)},{DateTimeHelper.DateTimeToFullDateTimeString(info.DateTime.LocalEndTime)},{info.DateTime.Offset} s,{info.DateTime.RoundTripDelay} ms"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] SNTPLookupInfoExportFields = + [ + new(nameof(SNTPLookupInfo.Server), x => x.Server, true), + new(nameof(SNTPLookupInfo.IPEndPoint), x => x.IPEndPoint), + new(nameof(SNTPLookupInfo.DateTime.NetworkTime), x => x.DateTime.NetworkTime), + new(nameof(SNTPLookupInfo.DateTime.LocalStartTime), x => x.DateTime.LocalStartTime), + new(nameof(SNTPLookupInfo.DateTime.LocalEndTime), x => x.DateTime.LocalEndTime), + // Seconds + new(nameof(SNTPLookupInfo.DateTime.Offset), x => x.DateTime.Offset), + // ms + new(nameof(SNTPLookupInfo.DateTime.RoundTripDelay), x => x.DateTime.RoundTripDelay) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.SNTPLookup.ToString(), - new XElement(nameof(SNTPLookupInfo) + "s", - from info in collection - select - new XElement(nameof(SNTPLookupInfo), - new XElement(nameof(SNTPLookupInfo.Server), info.Server), - new XElement(nameof(SNTPLookupInfo.IPEndPoint), info.IPEndPoint), - new XElement(nameof(SNTPLookupInfo.DateTime.NetworkTime), - DateTimeHelper.DateTimeToFullDateTimeString(info.DateTime.NetworkTime)), - new XElement(nameof(SNTPLookupInfo.DateTime.LocalStartTime), - DateTimeHelper.DateTimeToFullDateTimeString(info.DateTime.LocalStartTime)), - new XElement(nameof(SNTPLookupInfo.DateTime.LocalEndTime), - DateTimeHelper.DateTimeToFullDateTimeString(info.DateTime.LocalEndTime)), - new XElement(nameof(SNTPLookupInfo.DateTime.Offset), $"{info.DateTime.Offset} s"), - new XElement(nameof(SNTPLookupInfo.DateTime.RoundTripDelay), - $"{info.DateTime.RoundTripDelay} ms"))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].Server, - collection[i].IPEndPoint, - NetworkTime = DateTimeHelper.DateTimeToFullDateTimeString(collection[i].DateTime.NetworkTime), - LocalStartTime = DateTimeHelper.DateTimeToFullDateTimeString(collection[i].DateTime.LocalStartTime), - LocalEndTime = DateTimeHelper.DateTimeToFullDateTimeString(collection[i].DateTime.LocalEndTime), - Offset = $"{collection[i].DateTime.Offset} s", - RoundTripDelay = $"{collection[i].DateTime.RoundTripDelay} ms" - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, SNTPLookupInfoExportFields, ApplicationName.SNTPLookup); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 253029aa87..a43ad04472 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -195,6 +195,49 @@ public void NetworkInterface_WithoutDhcpAndMACAddress_Empty() #endregion + #region DNS Lookup + + [Fact] + public void DNSLookup_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new DNSLookupRecordInfo("example.com", 300, "IN", "TXT", "v=spf1 a, mx \"x\"", "1.1.1.1", "one.one", 53)])); + + AssertConsistent(files, + "DomainName,TTL,RecordClass,RecordType,Result,NameServerIPAddress,NameServerHostName,NameServerPort"); + Assert.Equal("v=spf1 a, mx \"x\"", files.CsvValue("Result")); + Assert.Equal(300, (int)files.JsonValue("TTL")); + } + + #endregion + + #region SNTP Lookup + + [Fact] + public void SNTPLookup_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new SNTPLookupInfo("pool.ntp.org", "1.2.3.4:123", + new SNTPDateTime + { + LocalStartTime = Time, NetworkTime = Time.AddMilliseconds(5), LocalEndTime = Time.AddMilliseconds(10), + RoundTripDelay = 10.5, Offset = -0.25 + }) + ])); + + AssertConsistent(files, "Server,IPEndPoint,NetworkTime,LocalStartTime,LocalEndTime,Offset,RoundTripDelay"); + Assert.Equal("2026-11-08 10:15:30.128", files.CsvValue("NetworkTime")); + + // Numbers without unit (s / ms), decimal point + Assert.Equal("-0.25", files.CsvValue("Offset")); + Assert.Equal("10.5", files.XmlValue("RoundTripDelay")); + Assert.Equal(-0.25, (double)files.JsonValue("Offset")); + Assert.Equal(JTokenType.Float, files.JsonValue("RoundTripDelay").Type); + } + + #endregion + private static IPGeolocationInfo CreateGeolocation() { return new IPGeolocationInfo diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 45c300d165..a9881a7dec 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -25,6 +25,7 @@ Release date: **xx.xx.2026** - **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. - **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. +- **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. ## What's new? @@ -391,6 +392,7 @@ Release date: **xx.xx.2026** - Fixed **Add DNS suffix (primary) to hostname** silently appending no suffix at all on machines without a Windows primary DNS suffix configured (e.g. not domain-joined), even though a usable suffix was available via the active network adapter's connection-specific DNS suffix (shown under **DNS Suffix Search List** in `ipconfig /all`). It now falls back to that adapter's suffix in this case. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the DNS server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - Fixed a technical error (*An invalid IP address was specified*) being shown for a hostname looked up with `PTR`. A message is shown and the hostname is skipped, the other hosts are looked up. [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) +- Fixed the CSV export breaking the row if a result (e.g. a `TXT` record) contains a comma or a quote. Domain name, result and name server hostname are quoted now. **Web Console** @@ -404,6 +406,7 @@ Release date: **xx.xx.2026** **SNTP Lookup** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the SNTP server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the offset and round trip delay, the values are exported with a decimal point now. **Hosts File Editor** From 0bdfd7c6682a96d08d1cf9fb5507e089166bcf22 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:28:48 +0100 Subject: [PATCH 08/44] Export: Connections, Listeners and Neighbor Table use the shared writer (E8) Neighbor Table MAC address as AA:BB:CC:DD:EE:FF like shown in the grid. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.ConnectionInfo.cs | 119 +++--------------- .../Export/ExportManager.ListenerInfo.cs | 94 ++------------ .../Export/ExportManager.NeighborInfo.cs | 98 +++------------ .../Export/ExportManagerToolTests.cs | 47 +++++++ Website/docs/changelog/next-release.md | 1 + 5 files changed, 96 insertions(+), 263 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.ConnectionInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.ConnectionInfo.cs index 9458949fb2..11713482ab 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.ConnectionInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.ConnectionInfo.cs @@ -1,114 +1,35 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of a . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(ConnectionInfo.Protocol)},{nameof(ConnectionInfo.LocalIPAddress)},{nameof(ConnectionInfo.LocalPort)},{nameof(ConnectionInfo.RemoteIPAddress)},{nameof(ConnectionInfo.RemotePort)},{nameof(ConnectionInfo.RemoteHostname)},{nameof(ConnectionInfo.TcpState)},{nameof(ConnectionInfo.ProcessId)},{nameof(ConnectionInfo.ProcessName)},{nameof(ConnectionInfo.ProcessPath)}" - ); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Protocol},{info.LocalIPAddress},{info.LocalPort},{info.RemoteIPAddress},{info.RemotePort},{CsvHelper.QuoteString(info.RemoteHostname)},{info.TcpState},{info.ProcessId},{CsvHelper.QuoteString(info.ProcessName)},{CsvHelper.QuoteString(info.ProcessPath)}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] ConnectionInfoExportFields = + [ + new(nameof(ConnectionInfo.Protocol), x => x.Protocol), + new(nameof(ConnectionInfo.LocalIPAddress), x => x.LocalIPAddress), + new(nameof(ConnectionInfo.LocalPort), x => x.LocalPort), + new(nameof(ConnectionInfo.RemoteIPAddress), x => x.RemoteIPAddress), + new(nameof(ConnectionInfo.RemotePort), x => x.RemotePort), + new(nameof(ConnectionInfo.RemoteHostname), x => x.RemoteHostname, true), + new(nameof(ConnectionInfo.TcpState), x => x.TcpState), + new(nameof(ConnectionInfo.ProcessId), x => x.ProcessId), + new(nameof(ConnectionInfo.ProcessName), x => x.ProcessName, true), + new(nameof(ConnectionInfo.ProcessPath), x => x.ProcessPath, true) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.Connections.ToString(), - new XElement(nameof(ConnectionInfo) + "s", - from info in collection - select - new XElement(nameof(ConnectionInfo), - new XElement(nameof(ConnectionInfo.Protocol), info.Protocol), - new XElement(nameof(ConnectionInfo.LocalIPAddress), info.LocalIPAddress), - new XElement(nameof(ConnectionInfo.LocalPort), info.LocalPort), - new XElement(nameof(ConnectionInfo.RemoteIPAddress), info.RemoteIPAddress), - new XElement(nameof(ConnectionInfo.RemotePort), info.RemotePort), - new XElement(nameof(ConnectionInfo.RemoteHostname), info.RemoteHostname), - new XElement(nameof(ConnectionInfo.TcpState), info.TcpState), - new XElement(nameof(ConnectionInfo.ProcessId), info.ProcessId), - new XElement(nameof(ConnectionInfo.ProcessName), info.ProcessName), - new XElement(nameof(ConnectionInfo.ProcessPath), info.ProcessPath) - )))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - Protocol = collection[i].Protocol.ToString(), - LocalIPAddress = collection[i].LocalIPAddress.ToString(), - collection[i].LocalPort, - RemoteIPAddress = collection[i].RemoteIPAddress.ToString(), - collection[i].RemotePort, - collection[i].RemoteHostname, - TcpState = collection[i].TcpState.ToString(), - collection[i].ProcessId, - collection[i].ProcessName, - collection[i].ProcessPath - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, ConnectionInfoExportFields, ApplicationName.Connections); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.ListenerInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.ListenerInfo.cs index 3ddf23c2f9..b718d22788 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.ListenerInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.ListenerInfo.cs @@ -1,96 +1,28 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of a . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(ListenerInfo.Protocol)},{nameof(ListenerInfo.IPAddress)},{nameof(ListenerInfo.Port)}"); - - foreach (var info in collection) - stringBuilder.AppendLine($"{info.Protocol},{info.IPAddress},{info.Port}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] ListenerInfoExportFields = + [ + new(nameof(ListenerInfo.Protocol), x => x.Protocol), + new(nameof(ListenerInfo.IPAddress), x => x.IPAddress), + new(nameof(ListenerInfo.Port), x => x.Port) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.Listeners.ToString(), - new XElement(nameof(ListenerInfo) + "s", - from info in collection - select - new XElement(nameof(ListenerInfo), - new XElement(nameof(ListenerInfo.Protocol), info.Protocol), - new XElement(nameof(ListenerInfo.IPAddress), info.IPAddress), - new XElement(nameof(ListenerInfo.Port), info.Port))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - Protocol = collection[i].Protocol.ToString(), - IPAddress = collection[i].IPAddress.ToString(), - collection[i].Port - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, ListenerInfoExportFields, ApplicationName.Listeners); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.NeighborInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.NeighborInfo.cs index af6e501d11..6b867df651 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.NeighborInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.NeighborInfo.cs @@ -1,17 +1,24 @@ -using System; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; using NETworkManager.Models.Network; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { + /// + /// Exported fields of a . + /// + private static readonly ExportField[] NeighborInfoExportFields = + [ + new(nameof(NeighborInfo.IPAddress), x => x.IPAddress), + new(nameof(NeighborInfo.MACAddress), x => x.MACAddress), + new(nameof(NeighborInfo.InterfaceAlias), x => x.InterfaceAlias, true), + new(nameof(NeighborInfo.InterfaceIndex), x => x.InterfaceIndex), + new(nameof(NeighborInfo.State), x => x.State), + new(nameof(NeighborInfo.AddressFamily), x => x.AddressFamily), + new(nameof(NeighborInfo.IsMulticast), x => x.IsMulticast) + ]; + /// /// Method to export objects from type to a file. /// @@ -20,81 +27,6 @@ public static partial class ExportManager /// Objects as to export. public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(NeighborInfo.IPAddress)},{nameof(NeighborInfo.MACAddress)},{nameof(NeighborInfo.InterfaceAlias)},{nameof(NeighborInfo.InterfaceIndex)},{nameof(NeighborInfo.State)},{nameof(NeighborInfo.AddressFamily)},{nameof(NeighborInfo.IsMulticast)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.IPAddress},{info.MACAddress},{CsvHelper.QuoteString(info.InterfaceAlias)},{info.InterfaceIndex},{info.State},{info.AddressFamily},{info.IsMulticast}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Creates an XML file from the given collection. - /// - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.NeighborTable.ToString(), - new XElement(nameof(NeighborInfo) + "s", - from info in collection - select - new XElement(nameof(NeighborInfo), - new XElement(nameof(NeighborInfo.IPAddress), info.IPAddress), - new XElement(nameof(NeighborInfo.MACAddress), info.MACAddress), - new XElement(nameof(NeighborInfo.InterfaceAlias), info.InterfaceAlias), - new XElement(nameof(NeighborInfo.InterfaceIndex), info.InterfaceIndex), - new XElement(nameof(NeighborInfo.State), info.State), - new XElement(nameof(NeighborInfo.AddressFamily), info.AddressFamily), - new XElement(nameof(NeighborInfo.IsMulticast), info.IsMulticast))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - private static void CreateJson(IReadOnlyList collection, string filePath) - { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - IPAddress = collection[i].IPAddress.ToString(), - MACAddress = collection[i].MACAddress.ToString(), - collection[i].InterfaceAlias, - collection[i].InterfaceIndex, - State = collection[i].State.ToString(), - AddressFamily = collection[i].AddressFamily.ToString(), - collection[i].IsMulticast - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, NeighborInfoExportFields, ApplicationName.NeighborTable); } } diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index a43ad04472..2d4ad270e8 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -1,6 +1,7 @@ using System; using System.Net; using System.Net.NetworkInformation; +using System.Net.Sockets; using NETworkManager.Models.Export; using NETworkManager.Models.IPApi; using NETworkManager.Models.Lookup; @@ -238,6 +239,52 @@ public void SNTPLookup_Consistent() #endregion + #region Connections, Listeners, Neighbor Table + + [Fact] + public void Connections_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new ConnectionInfo(TransportProtocol.Tcp, IPAddress, 50000, IPAddress.Parse("1.2.3.4"), 443, + "a, b.example.com", TcpState.Established, 1234, "chrome", @"C:\Program Files\chrome, x.exe") + ])); + + AssertConsistent(files, + "Protocol,LocalIPAddress,LocalPort,RemoteIPAddress,RemotePort,RemoteHostname,TcpState,ProcessId," + + "ProcessName,ProcessPath"); + Assert.Equal("Established", (string)files.JsonValue("TcpState")); + Assert.Equal(@"C:\Program Files\chrome, x.exe", files.CsvValue("ProcessPath")); + } + + [Fact] + public void Listeners_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new ListenerInfo(TransportProtocol.Udp, IPAddress.Parse("::"), 53)])); + + AssertConsistent(files, "Protocol,IPAddress,Port"); + Assert.Equal("Udp,::,53", files.CsvLines[1]); + } + + [Fact] + public void NeighborTable_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new NeighborInfo(IPAddress, PhysicalAddress.Parse("00-11-22-AA-BB-CC"), false, 12, "Ethernet, 2", + NeighborState.Reachable, AddressFamily.InterNetwork) + ])); + + AssertConsistent(files, "IPAddress,MACAddress,InterfaceAlias,InterfaceIndex,State,AddressFamily,IsMulticast"); + Assert.Equal("00:11:22:AA:BB:CC", files.CsvValue("MACAddress")); + Assert.Equal("00:11:22:AA:BB:CC", (string)files.JsonValue("MACAddress")); + Assert.Equal("Reachable", (string)files.JsonValue("State")); + Assert.Equal("Ethernet, 2", files.CsvValue("InterfaceAlias")); + } + + #endregion + private static IPGeolocationInfo CreateGeolocation() { return new IPGeolocationInfo diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index a9881a7dec..42b837e16a 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -26,6 +26,7 @@ Release date: **xx.xx.2026** - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. - **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. - **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. +- **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. ## What's new? From d7b512cf210426451205dcc69749947a5e47e589 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:29:47 +0100 Subject: [PATCH 09/44] Export: Discovery Protocol uses the shared writer (E9) Text quoted in the CSV file. Management, ChassisId, LocalConnection and LocalInterface (shown, not exported) appended. Co-Authored-By: Claude Opus 5.5 --- ...ortManager.DiscoveryProtocolPackageInfo.cs | 122 ++++-------------- .../Export/ExportManagerToolTests.cs | 25 ++++ Website/docs/changelog/next-release.md | 8 ++ 3 files changed, 59 insertions(+), 96 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs index 9e58a7f136..1f2fd697b4 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs @@ -1,16 +1,32 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { + /// + /// Exported fields of a . The released columns come first, new ones + /// are appended at the end, so the position of a column never changes. + /// + private static readonly ExportField[] DiscoveryProtocolPackageInfoExportFields = + [ + new(nameof(DiscoveryProtocolPackageInfo.Device), x => x.Device, true), + new(nameof(DiscoveryProtocolPackageInfo.DeviceDescription), x => x.DeviceDescription, true), + new(nameof(DiscoveryProtocolPackageInfo.Port), x => x.Port, true), + new(nameof(DiscoveryProtocolPackageInfo.PortDescription), x => x.PortDescription, true), + new(nameof(DiscoveryProtocolPackageInfo.Model), x => x.Model, true), + new(nameof(DiscoveryProtocolPackageInfo.VLAN), x => x.VLAN), + new(nameof(DiscoveryProtocolPackageInfo.IPAddress), x => x.IPAddress, true), + new(nameof(DiscoveryProtocolPackageInfo.Protocol), x => x.Protocol), + new(nameof(DiscoveryProtocolPackageInfo.TimeToLive), x => x.TimeToLive), + // Added later - after the released columns, so their position doesn't change + new(nameof(DiscoveryProtocolPackageInfo.Management), x => x.Management, true), + new(nameof(DiscoveryProtocolPackageInfo.ChassisId), x => x.ChassisId, true), + new(nameof(DiscoveryProtocolPackageInfo.LocalConnection), x => x.LocalConnection, true), + new(nameof(DiscoveryProtocolPackageInfo.LocalInterface), x => x.LocalInterface, true) + ]; + /// /// Method to export objects from type to a file. /// @@ -20,93 +36,7 @@ public static partial class ExportManager public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - - stringBuilder.AppendLine( - $"{nameof(DiscoveryProtocolPackageInfo.Device)},{nameof(DiscoveryProtocolPackageInfo.DeviceDescription)},{nameof(DiscoveryProtocolPackageInfo.Port)},{nameof(DiscoveryProtocolPackageInfo.PortDescription)},{nameof(DiscoveryProtocolPackageInfo.Model)},{nameof(DiscoveryProtocolPackageInfo.VLAN)},{nameof(DiscoveryProtocolPackageInfo.IPAddress)},{nameof(DiscoveryProtocolPackageInfo.Protocol)},{nameof(DiscoveryProtocolPackageInfo.TimeToLive)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Device},{info.DeviceDescription},{info.Port},{info.PortDescription},{info.Model},{info.VLAN},{info.IPAddress},{info.Protocol},{info.TimeToLive}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } - - /// - /// Creates a XML file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.DiscoveryProtocol.ToString(), - new XElement(nameof(DiscoveryProtocolPackageInfo) + "s", - from info in collection - select - new XElement(nameof(DiscoveryProtocolPackageInfo), - new XElement(nameof(DiscoveryProtocolPackageInfo.Device), info.Device), - new XElement(nameof(DiscoveryProtocolPackageInfo.DeviceDescription), - info.DeviceDescription), - new XElement(nameof(DiscoveryProtocolPackageInfo.Port), info.Port), - new XElement(nameof(DiscoveryProtocolPackageInfo.PortDescription), info.PortDescription), - new XElement(nameof(DiscoveryProtocolPackageInfo.Model), info.Model), - new XElement(nameof(DiscoveryProtocolPackageInfo.VLAN), info.VLAN), - new XElement(nameof(DiscoveryProtocolPackageInfo.IPAddress), info.IPAddress), - new XElement(nameof(DiscoveryProtocolPackageInfo.Protocol), info.Protocol), - new XElement(nameof(DiscoveryProtocolPackageInfo.TimeToLive), info.TimeToLive))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) - { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].Device, - collection[i].DeviceDescription, - collection[i].Port, - collection[i].PortDescription, - collection[i].Model, - collection[i].VLAN, - collection[i].IPAddress, - collection[i].Protocol, - collection[i].TimeToLive - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, DiscoveryProtocolPackageInfoExportFields, + ApplicationName.DiscoveryProtocol); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 2d4ad270e8..d26d86a85f 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -285,6 +285,31 @@ public void NeighborTable_Consistent() #endregion + #region Discovery Protocol + + [Fact] + public void DiscoveryProtocol_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new DiscoveryProtocolPackageInfo + { + Device = "sw1", DeviceDescription = "Cisco IOS, Version 15", Port = "Gi0/1", PortDescription = "Uplink", + Model = "C2960", VLAN = "10", IPAddress = "10.0.0.2", Protocol = "CDP", TimeToLive = "180", + Management = "10.0.0.2", ChassisId = "00:11:22:33:44:55", LocalConnection = "Ethernet", + LocalInterface = "Intel(R) Ethernet" + } + ])); + + AssertConsistent(files, + "Device,DeviceDescription,Port,PortDescription,Model,VLAN,IPAddress,Protocol,TimeToLive,Management," + + "ChassisId,LocalConnection,LocalInterface"); + Assert.Equal("Cisco IOS, Version 15", files.CsvValue("DeviceDescription")); + Assert.Equal("Intel(R) Ethernet", (string)files.JsonValue("LocalInterface")); + } + + #endregion + private static IPGeolocationInfo CreateGeolocation() { return new IPGeolocationInfo diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 42b837e16a..07a047ff53 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -221,6 +221,10 @@ Release date: **xx.xx.2026** - `Enter` in the search box filters the rules right away instead of after the delay while typing. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; the line below the list only shows errors (e.g. rules loaded with errors, a failed action). A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until the rules are loaded (also with **Show all rules**). [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +**Discovery Protocol** + +- The export contains the values shown that were missing: `Management`, `ChassisId`, `LocalConnection` and `LocalInterface` (appended as the last columns / elements). + **Whois** - Added an **Export...** button below the result, like in the other tools. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) @@ -427,6 +431,10 @@ Release date: **xx.xx.2026** - Fixed program paths with environment variables (e.g. `%SystemRoot%\System32\svchost.exe`) being rejected as non-existent in the add / edit / copy rule dialog. [#3630](https://github.com/BornToBeRoot/NETworkManager/pull/3630) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +**Discovery Protocol** + +- Fixed the CSV export breaking the row if a value (e.g. the device description) contains a comma or a quote. Text values are quoted now. + **RDAP** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the bootstrap files in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) From 406651ffe86cc8d51a8b9b56355bca39dd484e77 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:30:37 +0100 Subject: [PATCH 10/44] Export: IP Geolocation, Hosts File Editor and Firewall use the shared writer (E10) IP Geolocation: latitude / longitude with a decimal point, text quoted. Hosts File Editor: hostname / comment quoted. Firewall: output unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.FirewallRule.cs | 155 +++-------------- .../Export/ExportManager.HostsFileEntry.cs | 95 ++--------- .../Export/ExportManager.IPGeolocationInfo.cs | 159 ++++-------------- .../Export/ExportManagerToolTests.cs | 49 ++++++ Website/docs/changelog/next-release.md | 2 + 5 files changed, 124 insertions(+), 336 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs b/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs index a38710469e..f3f71df465 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs @@ -1,17 +1,33 @@ -using System; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; using NETworkManager.Models.Firewall; -using NETworkManager.Utilities; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { + /// + /// Exported fields of a . Ports, addresses, network profiles, interface type and + /// program as shown (e.g. 80; 443, empty if not restricted). + /// + private static readonly ExportField[] FirewallRuleExportFields = + [ + new(nameof(FirewallRule.Name), x => x.Name, true), + new(nameof(FirewallRule.IsEnabled), x => x.IsEnabled), + new(nameof(FirewallRule.IsManaged), x => x.IsManaged), + new(nameof(FirewallRule.Source), x => x.Source), + new(nameof(FirewallRule.Direction), x => x.Direction), + new(nameof(FirewallRule.Action), x => x.Action), + new(nameof(FirewallRule.Protocol), x => x.Protocol), + new(nameof(FirewallRule.LocalPorts), x => x.LocalPortsDisplay, true), + new(nameof(FirewallRule.RemotePorts), x => x.RemotePortsDisplay, true), + new(nameof(FirewallRule.LocalAddresses), x => x.LocalAddressesDisplay, true), + new(nameof(FirewallRule.RemoteAddresses), x => x.RemoteAddressesDisplay, true), + new(nameof(FirewallRule.NetworkProfiles), x => x.NetworkProfilesDisplay, true), + new(nameof(FirewallRule.InterfaceType), x => x.InterfaceTypeDisplay, true), + new(nameof(FirewallRule.Program), x => x.ProgramDisplay, true), + new(nameof(FirewallRule.Description), x => x.Description, true) + ]; + /// /// Method to export objects from type to a file. /// @@ -20,127 +36,6 @@ public static partial class ExportManager /// Objects as to export. public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - private static void CreateCsv(IEnumerable collection, string filePath) - { - var sb = new StringBuilder(); - - sb.AppendLine( - $"{nameof(FirewallRule.Name)}," + - $"{nameof(FirewallRule.IsEnabled)}," + - $"{nameof(FirewallRule.IsManaged)}," + - $"{nameof(FirewallRule.Source)}," + - $"{nameof(FirewallRule.Direction)}," + - $"{nameof(FirewallRule.Action)}," + - $"{nameof(FirewallRule.Protocol)}," + - $"{nameof(FirewallRule.LocalPorts)}," + - $"{nameof(FirewallRule.RemotePorts)}," + - $"{nameof(FirewallRule.LocalAddresses)}," + - $"{nameof(FirewallRule.RemoteAddresses)}," + - $"{nameof(FirewallRule.NetworkProfiles)}," + - $"{nameof(FirewallRule.InterfaceType)}," + - $"{nameof(FirewallRule.Program)}," + - $"{nameof(FirewallRule.Description)}"); - - foreach (var rule in collection) - sb.AppendLine( - $"{CsvHelper.QuoteString(rule.Name)}," + - $"{rule.IsEnabled}," + - $"{rule.IsManaged}," + - $"{rule.Source}," + - $"{rule.Direction}," + - $"{rule.Action}," + - $"{rule.Protocol}," + - $"{CsvHelper.QuoteString(rule.LocalPortsDisplay)}," + - $"{CsvHelper.QuoteString(rule.RemotePortsDisplay)}," + - $"{CsvHelper.QuoteString(rule.LocalAddressesDisplay)}," + - $"{CsvHelper.QuoteString(rule.RemoteAddressesDisplay)}," + - $"{CsvHelper.QuoteString(rule.NetworkProfilesDisplay)}," + - $"{CsvHelper.QuoteString(rule.InterfaceTypeDisplay)}," + - $"{CsvHelper.QuoteString(rule.ProgramDisplay)}," + - $"{CsvHelper.QuoteString(rule.Description)}"); - - File.WriteAllText(filePath, sb.ToString()); - } - - /// - /// Creates an XML file from the given collection. - /// - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(nameof(ApplicationName.Firewall), - new XElement(nameof(FirewallRule) + "s", - from rule in collection - select new XElement(nameof(FirewallRule), - new XElement(nameof(FirewallRule.Name), rule.Name), - new XElement(nameof(FirewallRule.IsEnabled), rule.IsEnabled), - new XElement(nameof(FirewallRule.IsManaged), rule.IsManaged), - new XElement(nameof(FirewallRule.Source), rule.Source), - new XElement(nameof(FirewallRule.Direction), rule.Direction), - new XElement(nameof(FirewallRule.Action), rule.Action), - new XElement(nameof(FirewallRule.Protocol), rule.Protocol), - new XElement(nameof(FirewallRule.LocalPorts), rule.LocalPortsDisplay), - new XElement(nameof(FirewallRule.RemotePorts), rule.RemotePortsDisplay), - new XElement(nameof(FirewallRule.LocalAddresses), rule.LocalAddressesDisplay), - new XElement(nameof(FirewallRule.RemoteAddresses), rule.RemoteAddressesDisplay), - new XElement(nameof(FirewallRule.NetworkProfiles), rule.NetworkProfilesDisplay), - new XElement(nameof(FirewallRule.InterfaceType), rule.InterfaceTypeDisplay), - new XElement(nameof(FirewallRule.Program), rule.ProgramDisplay), - new XElement(nameof(FirewallRule.Description), rule.Description))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// - private static void CreateJson(IReadOnlyList collection, string filePath) - { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - { - var rule = collection[i]; - jsonData[i] = new - { - rule.Name, - rule.IsEnabled, - rule.IsManaged, - Source = rule.Source.ToString(), - Direction = rule.Direction.ToString(), - Action = rule.Action.ToString(), - Protocol = rule.Protocol.ToString(), - LocalPorts = rule.LocalPortsDisplay, - RemotePorts = rule.RemotePortsDisplay, - LocalAddresses = rule.LocalAddressesDisplay, - RemoteAddresses = rule.RemoteAddressesDisplay, - NetworkProfiles = rule.NetworkProfilesDisplay, - InterfaceType = rule.InterfaceTypeDisplay, - Program = rule.ProgramDisplay, - rule.Description - }; - } - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, FirewallRuleExportFields, ApplicationName.Firewall); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.HostsFileEntry.cs b/Source/NETworkManager.Models/Export/ExportManager.HostsFileEntry.cs index 2eb7ae3e58..a04cf98663 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.HostsFileEntry.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.HostsFileEntry.cs @@ -1,98 +1,29 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.HostsFileEditor; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of a . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(HostsFileEntry.IsEnabled)},{nameof(HostsFileEntry.IPAddress)},{nameof(HostsFileEntry.Hostname)},{nameof(HostsFileEntry.Comment)}"); - - foreach (var info in collection) - stringBuilder.AppendLine($"{info.IsEnabled},{info.IPAddress},{info.Hostname},{info.Comment}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] HostsFileEntryExportFields = + [ + new(nameof(HostsFileEntry.IsEnabled), x => x.IsEnabled), + new(nameof(HostsFileEntry.IPAddress), x => x.IPAddress), + new(nameof(HostsFileEntry.Hostname), x => x.Hostname, true), + new(nameof(HostsFileEntry.Comment), x => x.Comment, true) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.HostsFileEditor.ToString(), - new XElement(nameof(HostsFileEntry) + "s", - from info in collection - select - new XElement(nameof(HostsFileEntry), - new XElement(nameof(HostsFileEntry.IsEnabled), info.IsEnabled), - new XElement(nameof(HostsFileEntry.IPAddress), info.IPAddress), - new XElement(nameof(HostsFileEntry.Hostname), info.Hostname), - new XElement(nameof(HostsFileEntry.Comment), info.Comment))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].IsEnabled, - collection[i].IPAddress, - collection[i].Hostname, - collection[i].Comment - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, HostsFileEntryExportFields, ApplicationName.HostsFileEditor); } } diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs index b54a3cb185..c126463577 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs @@ -1,139 +1,50 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.IPApi; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of an . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(IPGeolocationInfo.Status)},{nameof(IPGeolocationInfo.Continent)},{nameof(IPGeolocationInfo.ContinentCode)},{nameof(IPGeolocationInfo.Country)},{nameof(IPGeolocationInfo.CountryCode)},{nameof(IPGeolocationInfo.Region)},{nameof(IPGeolocationInfo.RegionName)},{nameof(IPGeolocationInfo.City)},{nameof(IPGeolocationInfo.District)},{nameof(IPGeolocationInfo.Zip)},{nameof(IPGeolocationInfo.Lat)},{nameof(IPGeolocationInfo.Lon)},{nameof(IPGeolocationInfo.Timezone)},{nameof(IPGeolocationInfo.Offset)},{nameof(IPGeolocationInfo.Currency)},{nameof(IPGeolocationInfo.Isp)},{nameof(IPGeolocationInfo.Org)},{nameof(IPGeolocationInfo.As)},{nameof(IPGeolocationInfo.Asname)},{nameof(IPGeolocationInfo.Reverse)},{nameof(IPGeolocationInfo.Mobile)},{nameof(IPGeolocationInfo.Proxy)},{nameof(IPGeolocationInfo.Hosting)},{nameof(IPGeolocationInfo.Query)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Status},{info.Continent},{info.ContinentCode},{info.Country},{info.CountryCode},{info.Region},{info.RegionName},{info.City},{info.District},{info.Zip},{info.Lat},{info.Lon},{info.Timezone},{info.Offset},{info.Currency},{info.Isp},{info.Org},{info.As},{info.Asname},{info.Reverse},{info.Mobile},{info.Proxy},{info.Hosting},{info.Query}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] IPGeolocationInfoExportFields = + [ + new(nameof(IPGeolocationInfo.Status), x => x.Status), + new(nameof(IPGeolocationInfo.Continent), x => x.Continent, true), + new(nameof(IPGeolocationInfo.ContinentCode), x => x.ContinentCode), + new(nameof(IPGeolocationInfo.Country), x => x.Country, true), + new(nameof(IPGeolocationInfo.CountryCode), x => x.CountryCode), + new(nameof(IPGeolocationInfo.Region), x => x.Region), + new(nameof(IPGeolocationInfo.RegionName), x => x.RegionName, true), + new(nameof(IPGeolocationInfo.City), x => x.City, true), + new(nameof(IPGeolocationInfo.District), x => x.District, true), + new(nameof(IPGeolocationInfo.Zip), x => x.Zip), + new(nameof(IPGeolocationInfo.Lat), x => x.Lat), + new(nameof(IPGeolocationInfo.Lon), x => x.Lon), + new(nameof(IPGeolocationInfo.Timezone), x => x.Timezone), + // Seconds (offset of the time zone to UTC) + new(nameof(IPGeolocationInfo.Offset), x => x.Offset), + new(nameof(IPGeolocationInfo.Currency), x => x.Currency), + new(nameof(IPGeolocationInfo.Isp), x => x.Isp, true), + new(nameof(IPGeolocationInfo.Org), x => x.Org, true), + new(nameof(IPGeolocationInfo.As), x => x.As, true), + new(nameof(IPGeolocationInfo.Asname), x => x.Asname, true), + new(nameof(IPGeolocationInfo.Reverse), x => x.Reverse, true), + new(nameof(IPGeolocationInfo.Mobile), x => x.Mobile), + new(nameof(IPGeolocationInfo.Proxy), x => x.Proxy), + new(nameof(IPGeolocationInfo.Hosting), x => x.Hosting), + new(nameof(IPGeolocationInfo.Query), x => x.Query) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.IPGeolocation.ToString(), - new XElement(nameof(IPGeolocationInfo) + "s", - from info in collection - select - new XElement(nameof(IPGeolocationInfo), - new XElement(nameof(IPGeolocationInfo.Status), info.Status), - new XElement(nameof(IPGeolocationInfo.Continent), info.Continent), - new XElement(nameof(IPGeolocationInfo.ContinentCode), info.ContinentCode), - new XElement(nameof(IPGeolocationInfo.Country), info.Country), - new XElement(nameof(IPGeolocationInfo.CountryCode), info.CountryCode), - new XElement(nameof(IPGeolocationInfo.Region), info.Region), - new XElement(nameof(IPGeolocationInfo.RegionName), info.RegionName), - new XElement(nameof(IPGeolocationInfo.City), info.City), - new XElement(nameof(IPGeolocationInfo.District), info.District), - new XElement(nameof(IPGeolocationInfo.Zip), info.Zip), - new XElement(nameof(IPGeolocationInfo.Lat), info.Lat), - new XElement(nameof(IPGeolocationInfo.Lon), info.Lon), - new XElement(nameof(IPGeolocationInfo.Timezone), info.Timezone), - new XElement(nameof(IPGeolocationInfo.Offset), info.Offset), - new XElement(nameof(IPGeolocationInfo.Currency), info.Currency), - new XElement(nameof(IPGeolocationInfo.Isp), info.Isp), - new XElement(nameof(IPGeolocationInfo.Org), info.Org), - new XElement(nameof(IPGeolocationInfo.As), info.As), - new XElement(nameof(IPGeolocationInfo.Asname), info.Asname), - new XElement(nameof(IPGeolocationInfo.Reverse), info.Reverse), - new XElement(nameof(IPGeolocationInfo.Mobile), info.Mobile), - new XElement(nameof(IPGeolocationInfo.Proxy), info.Proxy), - new XElement(nameof(IPGeolocationInfo.Hosting), info.Hosting), - new XElement(nameof(IPGeolocationInfo.Query), info.Query))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].Status, - collection[i].Continent, - collection[i].ContinentCode, - collection[i].Country, - collection[i].CountryCode, - collection[i].Region, - collection[i].RegionName, - collection[i].City, - collection[i].District, - collection[i].Zip, - collection[i].Lat, - collection[i].Lon, - collection[i].Timezone, - collection[i].Offset, - collection[i].Currency, - collection[i].Isp, - collection[i].Org, - collection[i].As, - collection[i].Asname, - collection[i].Reverse, - collection[i].Mobile, - collection[i].Proxy, - collection[i].Hosting, - collection[i].Query - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, IPGeolocationInfoExportFields, ApplicationName.IPGeolocation); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index d26d86a85f..8a505b984c 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -3,6 +3,8 @@ using System.Net.NetworkInformation; using System.Net.Sockets; using NETworkManager.Models.Export; +using NETworkManager.Models.Firewall; +using NETworkManager.Models.HostsFileEditor; using NETworkManager.Models.IPApi; using NETworkManager.Models.Lookup; using NETworkManager.Models.Network; @@ -310,6 +312,53 @@ public void DiscoveryProtocol_Consistent() #endregion + #region Hosts File Editor, Firewall, IP Geolocation + + [Fact] + public void HostsFileEditor_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new HostsFileEntry(true, "10.0.0.1", "a.local b.local", "comment, with \"quotes\"")])); + + AssertConsistent(files, "IsEnabled,IPAddress,Hostname,Comment"); + Assert.Equal("comment, with \"quotes\"", files.CsvValue("Comment")); + Assert.Equal("True", files.CsvValue("IsEnabled")); + Assert.Equal("true", files.XmlValue("IsEnabled")); + Assert.Equal(JTokenType.Boolean, files.JsonValue("IsEnabled").Type); + } + + [Fact] + public void Firewall_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new FirewallRule { Name = "Rule, 1", Description = "Description \"x\"" }])); + + AssertConsistent(files, + "Name,IsEnabled,IsManaged,Source,Direction,Action,Protocol,LocalPorts,RemotePorts,LocalAddresses," + + "RemoteAddresses,NetworkProfiles,InterfaceType,Program,Description"); + Assert.Equal("Rule, 1", files.CsvValue("Name")); + Assert.Equal("Inbound", (string)files.JsonValue("Direction")); + } + + [Fact] + public void IPGeolocation_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateGeolocation()])); + + AssertConsistent(files, + "Status,Continent,ContinentCode,Country,CountryCode,Region,RegionName,City,District,Zip,Lat,Lon,Timezone," + + "Offset,Currency,Isp,Org,As,Asname,Reverse,Mobile,Proxy,Hosting,Query"); + + // Decimal point in every language + Assert.Equal("48.1374", files.CsvValue("Lat")); + Assert.Equal("11.5755", files.XmlValue("Lon")); + Assert.Equal(48.1374, (double)files.JsonValue("Lat")); + Assert.Equal("Example, Inc.", files.CsvValue("Isp")); + Assert.Equal("Org \"Quoted\"", files.CsvValue("Org")); + } + + #endregion + private static IPGeolocationInfo CreateGeolocation() { return new IPGeolocationInfo diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 07a047ff53..29766b9dec 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -416,6 +416,7 @@ Release date: **xx.xx.2026** **Hosts File Editor** - Fixed the retry of a locked hosts file waiting 5 seconds between the attempts (the message said 2) and once more after the last attempt. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- Fixed the CSV export breaking the row if the comment contains a comma. Hostname and comment are quoted now. **Firewall** @@ -442,6 +443,7 @@ Release date: **xx.xx.2026** **IP Geolocation** - Fixed the query history of **IP Geolocation** being written to the history of **Whois** instead of its own. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) +- Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the latitude / longitude, or a comma in a text (e.g. the ISP `Example, Inc.`). Decimals are exported with a decimal point, text is quoted now. **Subnet Calculator** From bbd45e40674060583eed80b379e718e46a04ee8b Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:31:18 +0100 Subject: [PATCH 11/44] Export: Subnet Calculator, Bit Calculator and SNMP use the shared writer (E11) Bit Calculator values with a decimal point, SNMP data quoted. All exports now use ExportField and the shared writer. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.BitCaluclatorInfo.cs | 122 ++++-------------- .../Export/ExportManager.IPNetworkInfo.cs | 110 +++------------- .../Export/ExportManager.SNMPReceivedInfo.cs | 91 ++----------- .../Export/ExportManagerToolTests.cs | 44 +++++++ Website/docs/changelog/next-release.md | 5 + 5 files changed, 101 insertions(+), 271 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.BitCaluclatorInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.BitCaluclatorInfo.cs index a5c01c2e38..08254f3ea7 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.BitCaluclatorInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.BitCaluclatorInfo.cs @@ -1,115 +1,37 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of a . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(BitCaluclatorInfo.Bits)},{nameof(BitCaluclatorInfo.Bytes)},{nameof(BitCaluclatorInfo.Kilobits)},{nameof(BitCaluclatorInfo.Kilobytes)},{nameof(BitCaluclatorInfo.Megabits)},{nameof(BitCaluclatorInfo.Megabytes)},{nameof(BitCaluclatorInfo.Gigabits)},{nameof(BitCaluclatorInfo.Gigabytes)},{nameof(BitCaluclatorInfo.Terabits)},{nameof(BitCaluclatorInfo.Terabytes)},{nameof(BitCaluclatorInfo.Petabits)},{nameof(BitCaluclatorInfo.Petabytes)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Bits},{info.Bytes},{info.Kilobits},{info.Kilobytes},{info.Megabits},{info.Megabytes},{info.Gigabits},{info.Gigabytes},{info.Terabits},{info.Terabytes},{info.Petabits},{info.Petabytes}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] BitCaluclatorInfoExportFields = + [ + new(nameof(BitCaluclatorInfo.Bits), x => x.Bits), + new(nameof(BitCaluclatorInfo.Bytes), x => x.Bytes), + new(nameof(BitCaluclatorInfo.Kilobits), x => x.Kilobits), + new(nameof(BitCaluclatorInfo.Kilobytes), x => x.Kilobytes), + new(nameof(BitCaluclatorInfo.Megabits), x => x.Megabits), + new(nameof(BitCaluclatorInfo.Megabytes), x => x.Megabytes), + new(nameof(BitCaluclatorInfo.Gigabits), x => x.Gigabits), + new(nameof(BitCaluclatorInfo.Gigabytes), x => x.Gigabytes), + new(nameof(BitCaluclatorInfo.Terabits), x => x.Terabits), + new(nameof(BitCaluclatorInfo.Terabytes), x => x.Terabytes), + new(nameof(BitCaluclatorInfo.Petabits), x => x.Petabits), + new(nameof(BitCaluclatorInfo.Petabytes), x => x.Petabytes) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.BitCalculator.ToString(), - new XElement(nameof(BitCaluclatorInfo) + "s", - from info in collection - select - new XElement(nameof(BitCaluclatorInfo), - new XElement(nameof(BitCaluclatorInfo.Bits), info.Bits), - new XElement(nameof(BitCaluclatorInfo.Bytes), info.Bytes), - new XElement(nameof(BitCaluclatorInfo.Kilobits), info.Kilobits), - new XElement(nameof(BitCaluclatorInfo.Kilobytes), info.Kilobytes), - new XElement(nameof(BitCaluclatorInfo.Megabits), info.Megabits), - new XElement(nameof(BitCaluclatorInfo.Megabytes), info.Megabytes), - new XElement(nameof(BitCaluclatorInfo.Gigabits), info.Gigabits), - new XElement(nameof(BitCaluclatorInfo.Gigabytes), info.Gigabytes), - new XElement(nameof(BitCaluclatorInfo.Terabits), info.Terabits), - new XElement(nameof(BitCaluclatorInfo.Terabytes), info.Terabytes), - new XElement(nameof(BitCaluclatorInfo.Petabits), info.Petabits), - new XElement(nameof(BitCaluclatorInfo.Petabytes), info.Petabytes))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].Bits, - collection[i].Bytes, - collection[i].Kilobits, - collection[i].Kilobytes, - collection[i].Megabits, - collection[i].Megabytes, - collection[i].Gigabits, - collection[i].Gigabytes, - collection[i].Terabits, - collection[i].Terabytes, - collection[i].Petabits, - collection[i].Petabytes - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, BitCaluclatorInfoExportFields, ApplicationName.BitCalculator); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPNetworkInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPNetworkInfo.cs index 7af1f7de6b..e54cf20a6d 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.IPNetworkInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.IPNetworkInfo.cs @@ -1,107 +1,33 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. + /// Exported fields of an . /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. - /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine( - $"{nameof(IPNetworkInfo.Network)},{nameof(IPNetworkInfo.Broadcast)},{nameof(IPNetworkInfo.Total)},{nameof(IPNetworkInfo.Netmask)},{nameof(IPNetworkInfo.Cidr)},{nameof(IPNetworkInfo.FirstUsable)},{nameof(IPNetworkInfo.LastUsable)},{nameof(IPNetworkInfo.Usable)}"); - - foreach (var info in collection) - stringBuilder.AppendLine( - $"{info.Network},{info.Broadcast},{info.Total},{info.Netmask},{info.Cidr},{info.FirstUsable},{info.LastUsable},{info.Usable}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] IPNetworkInfoExportFields = + [ + new(nameof(IPNetworkInfo.Network), x => x.Network), + new(nameof(IPNetworkInfo.Broadcast), x => x.Broadcast), + new(nameof(IPNetworkInfo.Total), x => x.Total), + new(nameof(IPNetworkInfo.Netmask), x => x.Netmask), + new(nameof(IPNetworkInfo.Cidr), x => x.Cidr), + new(nameof(IPNetworkInfo.FirstUsable), x => x.FirstUsable), + new(nameof(IPNetworkInfo.LastUsable), x => x.LastUsable), + new(nameof(IPNetworkInfo.Usable), x => x.Usable) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.SubnetCalculator.ToString(), - new XElement(nameof(IPNetworkInfo) + "s", - from info in collection - select - new XElement(nameof(IPNetworkInfo), - new XElement(nameof(IPNetworkInfo.Network), info.Network), - new XElement(nameof(IPNetworkInfo.Broadcast), info.Broadcast), - new XElement(nameof(IPNetworkInfo.Total), info.Total), - new XElement(nameof(IPNetworkInfo.Netmask), info.Netmask), - new XElement(nameof(IPNetworkInfo.Cidr), info.Cidr), - new XElement(nameof(IPNetworkInfo.FirstUsable), info.FirstUsable), - new XElement(nameof(IPNetworkInfo.LastUsable), info.LastUsable), - new XElement(nameof(IPNetworkInfo.Usable), info.Usable))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - Network = collection[i].Network.ToString(), - Broadcast = collection[i].Broadcast.ToString(), - collection[i].Total, - Netmask = collection[i].Netmask.ToString(), - collection[i].Cidr, - FirstUsable = collection[i].FirstUsable.ToString(), - LastUsable = collection[i].LastUsable.ToString(), - collection[i].Usable - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, IPNetworkInfoExportFields, ApplicationName.SubnetCalculator); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Models/Export/ExportManager.SNMPReceivedInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.SNMPReceivedInfo.cs index 7e3aaa7704..6e9a7b4461 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.SNMPReceivedInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.SNMPReceivedInfo.cs @@ -1,94 +1,27 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Xml.Linq; +using System.Collections.Generic; using NETworkManager.Models.Network; -using Newtonsoft.Json; namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - public static void Export(string filePath, ExportFileType fileType, - IReadOnlyList collection) - { - switch (fileType) - { - case ExportFileType.Csv: - CreateCsv(collection, filePath); - break; - case ExportFileType.Xml: - CreateXml(collection, filePath); - break; - case ExportFileType.Json: - CreateJson(collection, filePath); - break; - case ExportFileType.Txt: - default: - throw new ArgumentOutOfRangeException(nameof(fileType), fileType, null); - } - } - - /// - /// Creates a CSV file from the given collection. + /// Exported fields of a . /// - /// Objects as to export. - /// Path to the export file. - private static void CreateCsv(IEnumerable collection, string filePath) - { - var stringBuilder = new StringBuilder(); - - stringBuilder.AppendLine($"{nameof(SNMPInfo.OID)},{nameof(SNMPInfo.Data)}"); - - foreach (var info in collection) - stringBuilder.AppendLine($"{info.OID},{info.Data}"); - - File.WriteAllText(filePath, stringBuilder.ToString()); - } + private static readonly ExportField[] SNMPInfoExportFields = + [ + new(nameof(SNMPInfo.OID), x => x.OID), + new(nameof(SNMPInfo.Data), x => x.Data, true) + ]; /// - /// Creates a XML file from the given collection. + /// Method to export objects from type to a file. /// - /// Objects as to export. /// Path to the export file. - private static void CreateXml(IEnumerable collection, string filePath) - { - var document = new XDocument(DefaultXDeclaration, - new XElement(ApplicationName.SNMP.ToString(), - new XElement(nameof(SNMPInfo) + "s", - from info in collection - select - new XElement(nameof(SNMPInfo), - new XElement(nameof(SNMPInfo.OID), info.OID), - new XElement(nameof(SNMPInfo.Data), info.Data))))); - - document.Save(filePath); - } - - /// - /// Creates a JSON file from the given collection. - /// + /// Allowed are CSV, XML or JSON. /// Objects as to export. - /// Path to the export file. - private static void CreateJson(IReadOnlyList collection, string filePath) + public static void Export(string filePath, ExportFileType fileType, IReadOnlyList collection) { - var jsonData = new object[collection.Count]; - - for (var i = 0; i < collection.Count; i++) - jsonData[i] = new - { - collection[i].OID, - collection[i].Data - }; - - File.WriteAllText(filePath, JsonConvert.SerializeObject(jsonData, Formatting.Indented)); + Export(filePath, fileType, collection, SNMPInfoExportFields, ApplicationName.SNMP); } -} \ No newline at end of file +} diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 8a505b984c..b96ca6d2aa 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -359,6 +359,50 @@ public void IPGeolocation_Consistent() #endregion + #region Subnet Calculator, Bit Calculator, SNMP + + [Fact] + public void SubnetCalculator_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new IPNetworkInfo(IPNetwork2.Parse("10.0.0.0/24")), new IPNetworkInfo(IPNetwork2.Parse("2001:db8::/32"))])); + + AssertConsistent(files, "Network,Broadcast,Total,Netmask,Cidr,FirstUsable,LastUsable,Usable"); + Assert.Equal("10.0.0.0,10.0.0.255,256,255.255.255.0,24,10.0.0.1,10.0.0.254,254", files.CsvLines[1]); + Assert.Equal(256, (int)files.JsonValue("Total")); + + // Large numbers (IPv6) as JSON number + Assert.Equal(JTokenType.Integer, files.JsonItems[1]["Total"]!.Type); + } + + [Fact] + public void BitCalculator_DecimalPoint() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new BitCaluclatorInfo(1.5, 0.1875, 0.0015, 0.00018, 1, 2, 3, 4, 5, 6, 7, 8)])); + + AssertConsistent(files, + "Bits,Bytes,Kilobits,Kilobytes,Megabits,Megabytes,Gigabits,Gigabytes,Terabits,Terabytes,Petabits,Petabytes"); + Assert.Equal("1.5,0.1875,0.0015,0.00018,1,2,3,4,5,6,7,8", files.CsvLines[1]); + Assert.Equal("0.1875", files.XmlValue("Bytes")); + Assert.Equal(1.5, (double)files.JsonValue("Bits")); + } + + [Fact] + public void SNMP_Consistent() + { + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [ + new SNMPInfo(new Lextm.SharpSnmpLib.ObjectIdentifier("1.3.6.1.2.1.1.1.0"), + new Lextm.SharpSnmpLib.OctetString("Linux sw1, 5.10 \"x\"")) + ])); + + AssertConsistent(files, "OID,Data"); + Assert.Equal("Linux sw1, 5.10 \"x\"", files.CsvValue("Data")); + } + + #endregion + private static IPGeolocationInfo CreateGeolocation() { return new IPGeolocationInfo diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 29766b9dec..45bd997799 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -407,6 +407,7 @@ Release date: **xx.xx.2026** - Fixed `Enter` in the search box of the OID profiles dialog closing the dialog with **OK**. It only filters the OID profiles now. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the OID profiles (dialog, settings). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +- Fixed the CSV export breaking the row if the data contains a comma or a quote. The data is quoted now. **SNTP Lookup** @@ -450,6 +451,10 @@ Release date: **xx.xx.2026** - Fixed **Subnetting** getting stuck when the new subnet mask is smaller than the subnet mask of the subnet (e.g. `10.0.0.0/24` with `/16`) or too large for the address family (e.g. `/40` for IPv4). An error is shown instead. [#3646](https://github.com/BornToBeRoot/NETworkManager/pull/3646) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the subnetting result. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) +**Bit Calculator** + +- Fixed the CSV export breaking the row with a decimal comma (e.g. German), the values are exported with a decimal point now. + **Lookup** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the OUI and port lookup. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) From 28502dd6306fc8b5de9c68b1e847dac1336a351b Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:33:11 +0100 Subject: [PATCH 12/44] Ping: remove unused disableSpecialChar parameter of TimeToString Only the exports used it, they export the time as number now. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager.Models/Network/Ping.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/Source/NETworkManager.Models/Network/Ping.cs b/Source/NETworkManager.Models/Network/Ping.cs index fc64412f19..b6844513d8 100644 --- a/Source/NETworkManager.Models/Network/Ping.cs +++ b/Source/NETworkManager.Models/Network/Ping.cs @@ -188,22 +188,19 @@ public void SendAsync(IPAddress ipAddress, CancellationToken cancellationToken) }, cancellationToken); } - // Param: disableSpecialChar --> ExportManager --> "<" this char cannot be displayed in xml /// - /// Converts the ping time to a string representation. + /// Converts the ping time to a string representation (e.g. <1 ms, 4 ms), -/- without a + /// reply. /// /// The IP status of the ping reply. /// The round-trip time in milliseconds. - /// If true, disables special characters like '<' in the output (e.g., for XML export). /// The formatted time string. - public static string TimeToString(IPStatus status, long time, bool disableSpecialChar = false) + public static string TimeToString(IPStatus status, long time) { if (status != IPStatus.Success && status != IPStatus.TtlExpired) return "-/-"; - _ = long.TryParse(time.ToString(), out var t); - - return disableSpecialChar ? $"{t} ms" : t == 0 ? "<1 ms" : $"{t} ms"; + return time == 0 ? "<1 ms" : $"{time} ms"; } #endregion From d75f2da9645d2c6ff2bbe75634b973da10c9745b Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:33:43 +0100 Subject: [PATCH 13/44] Docs: export format (E12) New FAQ page with the format shared by all exports (columns, empty values, numbers / units, dates, MAC addresses, lists, CSV quoting). Co-Authored-By: Claude Opus 5.5 --- Website/docs/changelog/next-release.md | 2 +- Website/docs/faq/export-format.md | 35 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 Website/docs/faq/export-format.md diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 45bd997799..305f5dfad0 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -494,6 +494,6 @@ Release date: **xx.xx.2026** - Added a unit test project (xUnit) with tests for the run command parser and the history lists. [#3644](https://github.com/BornToBeRoot/NETworkManager/pull/3644) - Reworked the GitHub issue templates as forms (bug report, feature request, question) that ask for the relevant information (e.g. affected feature, version, installation, Windows version, log), with links to the documentation, discussions, translations and security advisories. Simplified the pull request template and removed the Copilot summary section. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Faster CI: AppVeyor no longer builds a branch a second time when a PR is open, skips changes that only affect the documentation / website, builds ARM64 only for releases and now runs the unit tests. The website is only built for PRs that change it and builds about 3x faster (Docusaurus Faster). Dependabot also updates the GitHub Actions, and CodeQL also scans the workflows. Website changes are only merged automatically if the website builds. Dependabot major updates are no longer merged automatically. Removed the stale bot. [#3675](https://github.com/BornToBeRoot/NETworkManager/pull/3675) -- The exports (CSV, XML, JSON) of all tools define their columns once and are written by one shared writer, so the three formats can't drift apart and every tool formats the same kind of value the same way (not translated). Added unit tests for the exports. +- The exports (CSV, XML, JSON) of all tools define their columns once and are written by one shared writer, so the three formats can't drift apart and every tool formats the same kind of value the same way (not translated), see [Export format](../faq/export-format.md). Added unit tests for the exports. - Language files updated via [#transifex](https://github.com/BornToBeRoot/NETworkManager/pulls?q=author%3Aapp%2Ftransifex-integration) - Dependencies updated via [#dependabot](https://github.com/BornToBeRoot/NETworkManager/pulls?q=author%3Aapp%2Fdependabot) diff --git a/Website/docs/faq/export-format.md b/Website/docs/faq/export-format.md new file mode 100644 index 0000000000..5c77f11217 --- /dev/null +++ b/Website/docs/faq/export-format.md @@ -0,0 +1,35 @@ +--- +description: "Format of the CSV, XML and JSON exports of NETworkManager: columns, empty values, numbers, units, dates, MAC addresses and lists." +keywords: [NETworkManager, export, CSV, XML, JSON, export format, columns, script] +--- + +# Export format + +## How are the results exported? + +Most tools can export their results with **Export...** (selected or all results) to a CSV, XML or JSON file. All tools use the same format, so a script can read the exports of every tool the same way. The values are never translated: they are the same in every language. + +| File | Structure | +| ---- | ----------------------------------------------------------------------------------------------------------------------------- | +| CSV | First line with the column names, one line per result. Values are separated by `,` | +| XML | `...` (e.g. ``), one element per column | +| JSON | Array with one object per result, one key per column | + +The CSV columns, the XML elements and the JSON keys have the same names and order. Columns are never moved or renamed: new columns are appended at the end, so a script that reads the columns by position keeps working. + +## How are the values formatted? + +| Value | Format | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Empty value | Empty in CSV, empty element in XML, `null` in JSON (e.g. the ping time without a reply) | +| Number | Decimal point in every language (e.g. `10.5`), without a unit. JSON: number | +| Time / duration | Number in a fixed unit: ping time in milliseconds (e.g. `4`), SNTP **Offset** in seconds and **RoundTripDelay** in milliseconds, **Speed** of a network interface in bit/s | +| Yes / No | `True` / `False` (CSV), `true` / `false` (XML, JSON) | +| Date and time | Local time as `yyyy-MM-dd HH:mm:ss.fff` (e.g. `2026-11-08 10:15:30.123`) | +| Status, type, state | English name (e.g. `Success`, `TimedOut`, `Open`, `Tcp`), several values separated by `, ` (e.g. `ICMP, TCP`) | +| MAC address | `AA:BB:CC:DD:EE:FF` | +| List (e.g. IP addresses) | One value, separated by `; ` (e.g. `10.0.0.53; 10.0.0.54`) | + +In the CSV file, text that may contain a comma (e.g. hostname, description, comment) is always enclosed in quotes (`"`), any other value only if it contains a comma, a quote or a line break. A quote in a value is doubled (`""`), as defined in [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180), e.g. for `Import-Csv` in PowerShell. + +The ports of a host in the **IP Scanner** export are one value in the CSV file (`Port/Protocol/Service/Description/State`, ports separated by `;`), one `PortInfo` element per port in the XML file and an array of objects in the JSON file. From 14550d1e1f0c2f007cd63f18ff4ea98ae779219b Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:39:30 +0100 Subject: [PATCH 14/44] Export: columns in a logical order instead of append-only (R0) Columns may be reordered so related values are next to each other (like shown in the tool); scripts read them by name. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager.Models/Export/ExportManager.cs | 5 +++-- .../Export/ExportManagerIPScannerTests.cs | 3 +-- Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs | 2 +- Source/NETworkManager.Tests/Export/ExportTestHelper.cs | 2 +- Website/docs/faq/export-format.md | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index b4f25726a3..6e8e9cd0e8 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -21,8 +21,9 @@ namespace NETworkManager.Models.Export; /// PingInfoExportFields), the CSV, XML and JSON files are written from this list by /// . The values have the same format in every tool and are never translated: /// -/// Names: CSV column = XML element = JSON key, in the same order. Released columns never move, new ones -/// are appended at the end. +/// Names: CSV column = XML element = JSON key, in the same order. The columns are in a logical order +/// (like shown in the tool, related values next to each other), a new column is added where it belongs - read +/// them by name, not by position. /// Empty value (null): empty in CSV, empty element in XML, null in JSON. /// Numbers with a decimal point (invariant culture), without a unit (e.g. ping time in ms, offset in /// s - the unit is documented). Bools as True / False (CSV), true / false (XML). diff --git a/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs index 88db034f4a..e2fee5ed5f 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs @@ -16,8 +16,7 @@ namespace NETworkManager.Tests.Export; public class ExportManagerIPScannerTests { /// - /// Columns of the CSV export - scripts read them by position: released columns must not move, new ones are - /// appended at the end. + /// Columns of the CSV export (names and order), grouped by topic. /// private const string CsvHeader = "IsReachable,IPAddress,Hostname,PingStatus,Timestamp,Time,TTL,Bytes,PortStatus,Ports,NetBIOSIsReachable," + diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index b96ca6d2aa..2031c9cf0d 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -15,7 +15,7 @@ namespace NETworkManager.Tests.Export; /// -/// Exports of the tools: columns (released columns must not move, new ones are appended at the end), the same names in +/// Exports of the tools: columns (names and order), the same names in /// CSV / XML / JSON, one CSV value per column (also with commas and quotes in text) and the shared value formats. /// public class ExportManagerToolTests diff --git a/Source/NETworkManager.Tests/Export/ExportTestHelper.cs b/Source/NETworkManager.Tests/Export/ExportTestHelper.cs index 7b3a28c1b9..9a4e5d05b6 100644 --- a/Source/NETworkManager.Tests/Export/ExportTestHelper.cs +++ b/Source/NETworkManager.Tests/Export/ExportTestHelper.cs @@ -85,7 +85,7 @@ private static string Export(Action export, ExportFileTy /// CSV header, the XML elements and the JSON keys, and one CSV value per column in every row. /// /// Exported files. - /// Expected CSV header (released columns must not move). + /// Expected CSV header (names and order of the columns). public static void AssertConsistent(ExportFiles files, string expectedHeader) { var header = expectedHeader.Split(','); diff --git a/Website/docs/faq/export-format.md b/Website/docs/faq/export-format.md index 5c77f11217..5348eb924d 100644 --- a/Website/docs/faq/export-format.md +++ b/Website/docs/faq/export-format.md @@ -15,7 +15,7 @@ Most tools can export their results with **Export...** (selected or all results) | XML | `...` (e.g. ``), one element per column | | JSON | Array with one object per result, one key per column | -The CSV columns, the XML elements and the JSON keys have the same names and order. Columns are never moved or renamed: new columns are appended at the end, so a script that reads the columns by position keeps working. +The CSV columns, the XML elements and the JSON keys have the same names and order. The columns are in a logical order: like they are shown in the tool, related values next to each other (e.g. the ping or the web page values of the **IP Scanner**). A new column is added where it belongs, so a script should read the columns by name (CSV header, XML element, JSON key) instead of by position. ## How are the values formatted? From d1ffb3d4b7c29ed949c83ef172bcd67f707e593c Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:39:59 +0100 Subject: [PATCH 15/44] Export: Network Interface columns in the order of the details (R1) Profile after Speed instead of at the end, IPv6 link-local before the IPv6 address. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.NetworkInterface.cs | 13 ++++++------- .../Export/ExportManagerToolTests.cs | 6 +++--- Website/docs/changelog/next-release.md | 4 ++-- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs b/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs index 0bee5741c8..542c118629 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using NETworkManager.Models.Network; @@ -8,8 +8,8 @@ namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Exported fields of a . The released columns come first, new ones are - /// appended at the end, so the position of a column never changes. + /// Exported fields of a in the order of the details: interface, IPv4 (incl. + /// DHCP), IPv6, DNS. /// private static readonly ExportField[] NetworkInterfaceInfoExportFields = [ @@ -22,6 +22,7 @@ public static partial class ExportManager new(nameof(NetworkInterfaceInfo.IsOperational), x => x.IsOperational), // Bit/s new(nameof(NetworkInterfaceInfo.Speed), x => x.Speed), + new(nameof(NetworkInterfaceInfo.Profile), x => x.Profile), new(nameof(NetworkInterfaceInfo.IPv4ProtocolAvailable), x => x.IPv4ProtocolAvailable), // IP address with prefix length (e.g. 192.168.1.10/24) new(nameof(NetworkInterfaceInfo.IPv4Address), @@ -33,14 +34,12 @@ public static partial class ExportManager new(nameof(NetworkInterfaceInfo.DhcpLeaseObtained), x => GetDhcpLease(x.DhcpLeaseObtained)), new(nameof(NetworkInterfaceInfo.DhcpLeaseExpires), x => GetDhcpLease(x.DhcpLeaseExpires)), new(nameof(NetworkInterfaceInfo.IPv6ProtocolAvailable), x => x.IPv6ProtocolAvailable), - new(nameof(NetworkInterfaceInfo.IPv6Address), x => x.IPv6Address), new(nameof(NetworkInterfaceInfo.IPv6AddressLinkLocal), x => x.IPv6AddressLinkLocal), + new(nameof(NetworkInterfaceInfo.IPv6Address), x => x.IPv6Address), new(nameof(NetworkInterfaceInfo.IPv6Gateway), x => x.IPv6Gateway), new(nameof(NetworkInterfaceInfo.DNSAutoconfigurationEnabled), x => x.DNSAutoconfigurationEnabled), new(nameof(NetworkInterfaceInfo.DNSSuffix), x => x.DNSSuffix, true), - new(nameof(NetworkInterfaceInfo.DNSServer), x => x.DNSServer), - // Added later - after the released columns, so their position doesn't change - new(nameof(NetworkInterfaceInfo.Profile), x => x.Profile) + new(nameof(NetworkInterfaceInfo.DNSServer), x => x.DNSServer) ]; /// diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 2031c9cf0d..089b278cda 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -149,9 +149,9 @@ public void NetworkInterface_Consistent() var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateNetworkInterface()])); AssertConsistent(files, - "Id,Name,Description,Type,PhysicalAddress,Status,IsOperational,Speed,IPv4ProtocolAvailable,IPv4Address," + - "IPv4Gateway,DhcpEnabled,DhcpServer,DhcpLeaseObtained,DhcpLeaseExpires,IPv6ProtocolAvailable,IPv6Address," + - "IPv6AddressLinkLocal,IPv6Gateway,DNSAutoconfigurationEnabled,DNSSuffix,DNSServer,Profile"); + "Id,Name,Description,Type,PhysicalAddress,Status,IsOperational,Speed,Profile,IPv4ProtocolAvailable," + + "IPv4Address,IPv4Gateway,DhcpEnabled,DhcpServer,DhcpLeaseObtained,DhcpLeaseExpires,IPv6ProtocolAvailable," + + "IPv6AddressLinkLocal,IPv6Address,IPv6Gateway,DNSAutoconfigurationEnabled,DNSSuffix,DNSServer"); Assert.Equal("Ethernet, 2", files.CsvValue("Name")); Assert.Equal("Private", files.CsvValue("Profile")); } diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 305f5dfad0..7cbcf4ef62 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -24,7 +24,7 @@ Release date: **xx.xx.2026** - **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. - **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. -- **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. +- **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. - **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. - **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. @@ -76,7 +76,7 @@ Release date: **xx.xx.2026** **Network Interface** - Members of the **Network Configuration Operators** group can now change the network configuration (IP address, DNS servers, release/renew) without being an administrator. NETworkManager has to run elevated (**Restart as Administrator**, confirm with your own credentials). The hint is now also shown as tooltip on **Apply** in the profile context menu. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) -- The export contains the network profile (`Profile`, e.g. `Private`) as last column / element. +- The export contains the network profile (`Profile`, e.g. `Private`) after the speed, like in the details. **WiFi** From 387a0c8c567301ee54b78e73a71e817737ad1bd6 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:40:27 +0100 Subject: [PATCH 16/44] Export: WiFi columns in the order of the grid (R2) Network, security, channel, signal, access point, other values, change. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.WiFiNetworkInfo.cs | 31 +++++++++---------- Website/docs/changelog/next-release.md | 3 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs index 3d43f04109..e6479bc651 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NETworkManager.Models.Network; namespace NETworkManager.Models.Export; @@ -6,36 +6,35 @@ namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Exported fields of a . The released columns come first, new ones are appended at - /// the end, so the position of a column never changes. + /// Exported fields of a in the order of the grid: network, security, channel, + /// signal, access point, other values of the network and the change since the previous scan. /// private static readonly ExportField[] WiFiNetworkInfoExportFields = [ - new(nameof(WiFiNetworkInfo.Bssid), x => x.Bssid), new(nameof(WiFiNetworkInfo.AvailableNetwork.Ssid), x => x.AvailableNetwork.Ssid, true), + new(nameof(WiFiNetworkInfo.IsConnected), x => x.IsConnected), + // Human-readable authentication type (e.g. "WPA2 Personal (PSK)") + new("Security", x => x.NetworkAuthenticationType, true), new(nameof(WiFiNetworkInfo.AvailableNetwork.ChannelCenterFrequencyInKilohertz), x => x.AvailableNetwork.ChannelCenterFrequencyInKilohertz), + new(nameof(WiFiNetworkInfo.Channel), x => x.Channel), + // MHz, estimated if the width could not be read from the beacon + new("ChannelWidth", x => x.ChannelBandwidth), + new("ChannelWidthEstimated", x => x.IsChannelBandwidthEstimated), new(nameof(WiFiNetworkInfo.AvailableNetwork.SignalBars), x => x.AvailableNetwork.SignalBars), - new(nameof(WiFiNetworkInfo.AvailableNetwork.IsWiFiDirect), x => x.AvailableNetwork.IsWiFiDirect), new(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkRssiInDecibelMilliwatts), x => x.AvailableNetwork.NetworkRssiInDecibelMilliwatts), - new(nameof(WiFiNetworkInfo.AvailableNetwork.PhyKind), x => x.AvailableNetwork.PhyKind), - new(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkKind), x => x.AvailableNetwork.NetworkKind), new(nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkAuthenticationType), x => x.AvailableNetwork.SecuritySettings.NetworkAuthenticationType), new(nameof(WiFiNetworkInfo.AvailableNetwork.SecuritySettings.NetworkEncryptionType), x => x.AvailableNetwork.SecuritySettings.NetworkEncryptionType), + new(nameof(WiFiNetworkInfo.Bssid), x => x.Bssid), + new(nameof(WiFiNetworkInfo.Vendor), x => x.Vendor, true), + new(nameof(WiFiNetworkInfo.AvailableNetwork.PhyKind), x => x.AvailableNetwork.PhyKind), + new(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkKind), x => x.AvailableNetwork.NetworkKind), + new(nameof(WiFiNetworkInfo.AvailableNetwork.IsWiFiDirect), x => x.AvailableNetwork.IsWiFiDirect), new(nameof(WiFiNetworkInfo.AvailableNetwork.BeaconInterval), x => x.AvailableNetwork.BeaconInterval), new(nameof(WiFiNetworkInfo.AvailableNetwork.Uptime), x => x.AvailableNetwork.Uptime), - // Values shown in the grid - new(nameof(WiFiNetworkInfo.IsConnected), x => x.IsConnected), - // Human-readable authentication type (e.g. "WPA2 Personal (PSK)") - new("Security", x => x.NetworkAuthenticationType, true), - new(nameof(WiFiNetworkInfo.Channel), x => x.Channel), - // MHz, estimated if the width could not be read from the beacon - new("ChannelWidth", x => x.ChannelBandwidth), - new("ChannelWidthEstimated", x => x.IsChannelBandwidthEstimated), - new(nameof(WiFiNetworkInfo.Vendor), x => x.Vendor, true), // Change since the previous scan of the same adapter (empty without a previous scan / change) new(nameof(WiFiNetworkInfo.Change), x => x.Change == WiFiNetworkChange.None ? null : x.Change) ]; diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 7cbcf4ef62..a4a1e31fe8 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -27,6 +27,7 @@ Release date: **xx.xx.2026** - **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. - **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. - **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. +- **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. ## What's new? @@ -87,7 +88,7 @@ Release date: **xx.xx.2026** - The BSSID is shown, copied and exported in the same format as the MAC addresses of the other tools (`AA:BB:CC:DD:EE:FF` instead of `aa:bb:cc:dd:ee:ff`). [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Reloading the adapters keeps the networks visible while they are scanned again (the refresh icon spins), instead of replacing them by the loading indicator. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - An unknown security or PHY kind is shown as `-/-` (like an unknown vendor) instead of the untranslated text `Unknown`. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) -- The export contains the values shown in the grid that were missing: `IsConnected`, `Security`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated` and `Vendor` (appended as the last columns / elements). [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) +- The export contains the values shown in the grid that were missing: `IsConnected`, `Security`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated` and `Vendor`. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - **Export...** > all exports the networks shown in the grid (filtered by band and search) in the order shown, the selected networks are exported in the order shown too. The file is written in the background. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Scanning the networks (also **Automatically update every**) no longer freezes the window briefly: the connected network is read from the WiFi API instead of `netsh` via PowerShell, and the vendor lookups run in the background. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - The selected network stays selected (and in view) when the networks are scanned again, e.g. with **Automatically update every**. The list is replaced at once instead of network by network. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) From b824bd075ef4f1f2b14b9bde7e00e445914ff0b2 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:41:12 +0100 Subject: [PATCH 17/44] Export: IP Scanner columns grouped by topic (R3) Host, ping, port scan, NetBIOS, web page, SNMP, Windows, change since the previous scan - instead of new columns appended at the end. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.IPScannerHostInfo.cs | 53 ++++++++++--------- .../Export/ExportManagerIPScannerTests.cs | 16 +++--- Website/docs/changelog/next-release.md | 3 +- 3 files changed, 40 insertions(+), 32 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs index f24e63c353..ec088405ff 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using NETworkManager.Models.Network; @@ -38,8 +38,8 @@ public static void Export(string filePath, ExportFileType fileType, ]; /// - /// Gets the exported fields of an . The released columns come first, new ones are - /// appended at the end, so the position of a column never changes. Values of a probe that is still running + /// Gets the exported fields of an , grouped by topic (host, ping, ports, NetBIOS, + /// web page, SNMP, Windows, change since the previous scan). Values of a probe that is still running /// (export during a scan, or a scan canceled before the probe finished) or disabled are placeholders - exported /// as empty values instead of a result. The ports are an (joined in the CSV /// file, one element per port in XML, an array in JSON). @@ -73,18 +73,28 @@ Func IfWindowsValue(Func val return [ + // Host (the hostname is the DNS name, or the mDNS / NetBIOS name as fallback) new(nameof(IPScannerHostInfo.IsReachable), x => x.IsReachable), + new(nameof(IPScannerHostInfo.DetectedBy), GetDetectedBy, true), new(nameof(PingInfo.IPAddress), x => x.PingInfo.IPAddress), new(nameof(IPScannerHostInfo.Hostname), x => x.Hostname, true), + new(nameof(IPScannerHostInfo.DNSHostname), x => x.DNSHostname, true), + new(nameof(IPScannerHostInfo.MDNSHostname), IfEnabled(options.MDNSEnabled, x => x.MDNSHostname), true), + new(nameof(IPScannerHostInfo.MACAddress), x => x.MACAddress), + new(nameof(IPScannerHostInfo.Vendor), x => x.Vendor, true), + new(nameof(IPScannerHostInfo.Role), GetRole, true), + new(nameof(IPScannerHostInfo.OSGuess), x => GetOSGuess(x, options)), + // Ping (time in ms, time / TTL / bytes only with a reply) new("PingStatus", x => GetPingInfo(x, options)?.Status), new(nameof(PingInfo.Timestamp), x => GetPingInfo(x, options)?.Timestamp), - // ms new(nameof(PingInfo.Time), IfPingReply(x => x.Time)), new(nameof(PingInfo.TTL), IfPingReply(x => x.TTL)), new(nameof(PingInfo.Bytes), IfPingReply(x => x.Bytes)), + // Port scan new("PortStatus", x => GetPortStatus(x, options)), new(nameof(IPScannerHostInfo.Ports), x => new ExportList(nameof(PortInfo), x.Ports != null && options.PortScanEnabled ? x.Ports : [], PortInfoExportFields), true), + // NetBIOS new("NetBIOSIsReachable", IfNetBIOS(x => x.IsReachable)), new("NetBIOSIPAddress", IfNetBIOS(x => x.IPAddress)), new("NetBIOSComputerName", IfNetBIOS(x => x.ComputerName), true), @@ -92,21 +102,10 @@ Func IfWindowsValue(Func val new("NetBIOSGroupName", IfNetBIOS(x => x.GroupName), true), new("NetBIOSMACAddress", IfNetBIOS(x => x.MACAddress)), new("NetBIOSVendor", IfNetBIOS(x => x.Vendor), true), - new(nameof(IPScannerHostInfo.MACAddress), x => x.MACAddress), - new(nameof(IPScannerHostInfo.Vendor), x => x.Vendor, true), - // Added later - after the released columns, so their position doesn't change - new(nameof(IPScannerHostInfo.DNSHostname), x => x.DNSHostname, true), - new(nameof(IPScannerHostInfo.DetectedBy), GetDetectedBy, true), - new(nameof(IPScannerHostInfo.OSGuess), x => GetOSGuess(x, options)), - new(nameof(IPScannerHostInfo.Role), GetRole, true), - new(nameof(IPScannerHostInfo.MDNSHostname), IfEnabled(options.MDNSEnabled, x => x.MDNSHostname), true), - new(nameof(IPScannerHostInfo.WebTitle), IfEnabled(isWebPageRead, x => x.WebTitle), true), + // Web page (only read with the port scan) new(nameof(IPScannerHostInfo.WebURL), IfEnabled(isWebPageRead, x => x.WebURL), true), - new(nameof(IPScannerHostInfo.SNMPName), IfEnabled(options.SNMPEnabled, x => x.SNMPName), true), - new(nameof(IPScannerHostInfo.SNMPDescription), IfEnabled(options.SNMPEnabled, x => x.SNMPDescription), - true), - new(nameof(IPScannerHostInfo.SNMPLocation), IfEnabled(options.SNMPEnabled, x => x.SNMPLocation), true), new(nameof(IPScannerHostInfo.WebStatusCode), x => GetWebStatusCode(x, options)), + new(nameof(IPScannerHostInfo.WebTitle), IfEnabled(isWebPageRead, x => x.WebTitle), true), new(nameof(IPScannerHostInfo.WebServer), IfEnabled(isWebPageRead, x => x.WebServer), true), new(nameof(IPScannerHostInfo.WebPoweredBy), IfEnabled(isWebPageRead, x => x.WebPoweredBy), true), new(nameof(IPScannerHostInfo.WebRealm), IfEnabled(isWebPageRead, x => x.WebRealm), true), @@ -115,30 +114,34 @@ Func IfWindowsValue(Func val new("WebCertificateIssuer", IfCertificate(x => x.Issuer), true), new("WebCertificateNotAfter", IfCertificate(x => x.NotAfter.ToLocalTime())), new("WebCertificateSelfSigned", IfCertificate(x => x.IsSelfSigned)), - // Change since the previous scan of the same input (empty without a previous scan / change) - new(nameof(IPScannerHostInfo.Change), x => x.Change == IPScannerHostChange.None ? null : x.Change), - new(nameof(IPScannerHostInfo.PreviousMACAddress), x => x.PreviousMACAddress), - // SNMPv3 error of the host (e.g. "AuthenticationFailed"), empty without + // SNMP system information (SNMPError: SNMPv3 error of the host, e.g. "AuthenticationFailed") + new(nameof(IPScannerHostInfo.SNMPName), IfEnabled(options.SNMPEnabled, x => x.SNMPName), true), + new(nameof(IPScannerHostInfo.SNMPDescription), IfEnabled(options.SNMPEnabled, x => x.SNMPDescription), + true), + new(nameof(IPScannerHostInfo.SNMPLocation), IfEnabled(options.SNMPEnabled, x => x.SNMPLocation), true), new(nameof(IPScannerHostInfo.SNMPError), IfEnabled(options.SNMPEnabled, x => x.HasSNMPError ? x.SNMPError.ToString() : string.Empty), true), - // Windows host information (SMB / NTLM, NetApi) + // Windows host information (SMB / NTLM, NetApi). WindowsTimeOffset: seconds (time of the host minus the local + // time), WindowsError: Win32 error of the NetApi requests (e.g. 5 = access denied, 1326 = wrong username or + // password) new("WindowsOS", IfWindows(x => x.OS), true), new("WindowsEdition", IfWindows(x => x.Edition), true), new("WindowsVersion", IfWindows(x => x.Version?.ToString())), new("WindowsRole", IfWindows(x => x.Role == WindowsHostRole.Unknown ? string.Empty : x.Role.ToString())), new("WindowsComputerName", IfWindows(x => x.ComputerName), true), new("WindowsDomain", IfWindows(x => x.Domain), true), - // Seconds (time of the host minus the local time) new("WindowsTimeOffset", IfWindowsValue(x => x.TimeOffset is { } offset ? Math.Round(offset.TotalSeconds, 3) : null)), new("WindowsUsers", IfWindows(x => x.Users == null ? string.Empty : string.Join(ListSeparator, x.Users)), true), new("WindowsDescription", IfWindows(x => x.Description), true), - // Win32 error of the NetApi requests (e.g. 5 = access denied, 1326 = wrong username or password) new("WindowsError", IfWindowsValue(x => x.Error == 0 ? null : x.Error)), new("SMBDialect", IfWindows(x => x.SMB?.Dialect)), new("SMBSigningRequired", IfWindowsValue(x => x.SMB?.SigningRequired)), - new("SMBServerGuid", IfWindows(x => x.SMB?.ServerGuid.ToString())) + new("SMBServerGuid", IfWindows(x => x.SMB?.ServerGuid.ToString())), + // Change since the previous scan of the same input (empty without a previous scan / change) + new(nameof(IPScannerHostInfo.Change), x => x.Change == IPScannerHostChange.None ? null : x.Change), + new(nameof(IPScannerHostInfo.PreviousMACAddress), x => x.PreviousMACAddress) ]; } diff --git a/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs index e2fee5ed5f..b0b83d79f7 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs @@ -19,13 +19,17 @@ public class ExportManagerIPScannerTests /// Columns of the CSV export (names and order), grouped by topic. /// private const string CsvHeader = - "IsReachable,IPAddress,Hostname,PingStatus,Timestamp,Time,TTL,Bytes,PortStatus,Ports,NetBIOSIsReachable," + - "NetBIOSIPAddress,NetBIOSComputerName,NetBIOSUserName,NetBIOSGroupName,NetBIOSMACAddress,NetBIOSVendor," + - "MACAddress,Vendor,DNSHostname,DetectedBy,OSGuess,Role,MDNSHostname,WebTitle,WebURL,SNMPName,SNMPDescription," + - "SNMPLocation,WebStatusCode,WebServer,WebPoweredBy,WebRealm,WebRedirectURL,WebCertificateSubject," + - "WebCertificateIssuer,WebCertificateNotAfter,WebCertificateSelfSigned,Change,PreviousMACAddress,SNMPError," + + "IsReachable,DetectedBy,IPAddress,Hostname,DNSHostname,MDNSHostname,MACAddress,Vendor,Role,OSGuess," + + "PingStatus,Timestamp,Time,TTL,Bytes," + + "PortStatus,Ports," + + "NetBIOSIsReachable,NetBIOSIPAddress,NetBIOSComputerName,NetBIOSUserName,NetBIOSGroupName,NetBIOSMACAddress," + + "NetBIOSVendor," + + "WebURL,WebStatusCode,WebTitle,WebServer,WebPoweredBy,WebRealm,WebRedirectURL,WebCertificateSubject," + + "WebCertificateIssuer,WebCertificateNotAfter,WebCertificateSelfSigned," + + "SNMPName,SNMPDescription,SNMPLocation,SNMPError," + "WindowsOS,WindowsEdition,WindowsVersion,WindowsRole,WindowsComputerName,WindowsDomain,WindowsTimeOffset," + - "WindowsUsers,WindowsDescription,WindowsError,SMBDialect,SMBSigningRequired,SMBServerGuid"; + "WindowsUsers,WindowsDescription,WindowsError,SMBDialect,SMBSigningRequired,SMBServerGuid," + + "Change,PreviousMACAddress"; private static readonly IPScannerResultOptions AllEnabled = new(true, true, true, true, true, true, true, true, true, true); diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index a4a1e31fe8..d5da6f6efe 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -28,6 +28,7 @@ Release date: **xx.xx.2026** - **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. - **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. - **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. +- **IP Scanner**: the columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. ## What's new? @@ -115,7 +116,7 @@ Release date: **xx.xx.2026** - **Copy** > **IP address** / **Hostname** / **MAC address** is also available if multiple results are selected (one value per line, in the order shown). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Added a **Time** column with the round trip time of the ping. Sorted by time, hosts without a ping reply are at the end. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - A host is shown as soon as it answers (ping reply, open or refused port or NetBIOS answer) instead of after all probes and lookups are finished (up to the port scan / NetBIOS timeout, plus the DNS lookup). Values of probes that are still running are shown as `...`, the other results, the DNS hostname and the MAC address / vendor are filled in when they arrive. The DNS hostname and the MAC address are resolved right after the first answer. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- The CSV and XML export contain the DNS hostname (`DNSHostname`) in addition to the hostname (DNS, or NetBIOS as fallback), like the JSON export. It is added after the columns (CSV) / elements (XML) of the last release, so their position doesn't change. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) +- The CSV and XML export contain the DNS hostname (`DNSHostname`) in addition to the hostname (DNS, or NetBIOS as fallback), like the JSON export. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Hosts are started one after another (every 10 ms, shorter with short timeouts and many threads) instead of all at the same moment. This avoids bursts of more than a thousand connection requests within a few milliseconds and makes the progress smoother. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) - Closed ports are reported immediately. Windows repeated the connection request after the host refused it and reported a closed port only after about 2 seconds. The connection request is sent once. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) - New **Attempts** setting for the port scan (default `1`): another connection request is sent if there was no answer, e.g. on an unreliable network (Wi-Fi, VPN) or for hosts on the internet. Open and closed ports are not repeated. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) From fa861547a3063f277cf396cd23a456b5edf972c4 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:41:38 +0100 Subject: [PATCH 18/44] Export: Discovery Protocol columns in the order shown (R4) Management and ChassisId after IPAddress instead of at the end. Co-Authored-By: Claude Opus 5.5 --- .../ExportManager.DiscoveryProtocolPackageInfo.cs | 10 ++++------ .../Export/ExportManagerToolTests.cs | 4 ++-- Website/docs/changelog/next-release.md | 3 ++- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs index 1f2fd697b4..3946074658 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NETworkManager.Models.Network; namespace NETworkManager.Models.Export; @@ -6,8 +6,7 @@ namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Exported fields of a . The released columns come first, new ones - /// are appended at the end, so the position of a column never changes. + /// Exported fields of a in the order shown. /// private static readonly ExportField[] DiscoveryProtocolPackageInfoExportFields = [ @@ -18,11 +17,10 @@ public static partial class ExportManager new(nameof(DiscoveryProtocolPackageInfo.Model), x => x.Model, true), new(nameof(DiscoveryProtocolPackageInfo.VLAN), x => x.VLAN), new(nameof(DiscoveryProtocolPackageInfo.IPAddress), x => x.IPAddress, true), - new(nameof(DiscoveryProtocolPackageInfo.Protocol), x => x.Protocol), - new(nameof(DiscoveryProtocolPackageInfo.TimeToLive), x => x.TimeToLive), - // Added later - after the released columns, so their position doesn't change new(nameof(DiscoveryProtocolPackageInfo.Management), x => x.Management, true), new(nameof(DiscoveryProtocolPackageInfo.ChassisId), x => x.ChassisId, true), + new(nameof(DiscoveryProtocolPackageInfo.Protocol), x => x.Protocol), + new(nameof(DiscoveryProtocolPackageInfo.TimeToLive), x => x.TimeToLive), new(nameof(DiscoveryProtocolPackageInfo.LocalConnection), x => x.LocalConnection, true), new(nameof(DiscoveryProtocolPackageInfo.LocalInterface), x => x.LocalInterface, true) ]; diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 089b278cda..980a2057c7 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -304,8 +304,8 @@ public void DiscoveryProtocol_Consistent() ])); AssertConsistent(files, - "Device,DeviceDescription,Port,PortDescription,Model,VLAN,IPAddress,Protocol,TimeToLive,Management," + - "ChassisId,LocalConnection,LocalInterface"); + "Device,DeviceDescription,Port,PortDescription,Model,VLAN,IPAddress,Management,ChassisId,Protocol," + + "TimeToLive,LocalConnection,LocalInterface"); Assert.Equal("Cisco IOS, Version 15", files.CsvValue("DeviceDescription")); Assert.Equal("Intel(R) Ethernet", (string)files.JsonValue("LocalInterface")); } diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index d5da6f6efe..622befd5e9 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -29,6 +29,7 @@ Release date: **xx.xx.2026** - **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. - **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. - **IP Scanner**: the columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. +- **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. ## What's new? @@ -225,7 +226,7 @@ Release date: **xx.xx.2026** **Discovery Protocol** -- The export contains the values shown that were missing: `Management`, `ChassisId`, `LocalConnection` and `LocalInterface` (appended as the last columns / elements). +- The export contains the values shown that were missing: `Management`, `ChassisId`, `LocalConnection` and `LocalInterface`. The columns are in the order shown (`Management` and `ChassisId` after `IPAddress`). **Whois** From a132c96cb4677826a3d5176955703413c06fa0d3 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:42:00 +0100 Subject: [PATCH 19/44] Export: Firewall columns in the order of the grid (R5) IsEnabled first (like the Hosts File Editor), address before port, program after the remote port. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.FirewallRule.cs | 12 ++++++------ .../Export/ExportManagerToolTests.cs | 4 ++-- Website/docs/changelog/next-release.md | 1 + 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs b/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs index f3f71df465..daf8abe184 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs @@ -6,25 +6,25 @@ namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Exported fields of a . Ports, addresses, network profiles, interface type and + /// Exported fields of a in the order of the grid. Ports, addresses, network profiles, interface type and /// program as shown (e.g. 80; 443, empty if not restricted). /// private static readonly ExportField[] FirewallRuleExportFields = [ - new(nameof(FirewallRule.Name), x => x.Name, true), new(nameof(FirewallRule.IsEnabled), x => x.IsEnabled), + new(nameof(FirewallRule.Name), x => x.Name, true), new(nameof(FirewallRule.IsManaged), x => x.IsManaged), new(nameof(FirewallRule.Source), x => x.Source), new(nameof(FirewallRule.Direction), x => x.Direction), new(nameof(FirewallRule.Action), x => x.Action), new(nameof(FirewallRule.Protocol), x => x.Protocol), - new(nameof(FirewallRule.LocalPorts), x => x.LocalPortsDisplay, true), - new(nameof(FirewallRule.RemotePorts), x => x.RemotePortsDisplay, true), new(nameof(FirewallRule.LocalAddresses), x => x.LocalAddressesDisplay, true), + new(nameof(FirewallRule.LocalPorts), x => x.LocalPortsDisplay, true), new(nameof(FirewallRule.RemoteAddresses), x => x.RemoteAddressesDisplay, true), - new(nameof(FirewallRule.NetworkProfiles), x => x.NetworkProfilesDisplay, true), - new(nameof(FirewallRule.InterfaceType), x => x.InterfaceTypeDisplay, true), + new(nameof(FirewallRule.RemotePorts), x => x.RemotePortsDisplay, true), new(nameof(FirewallRule.Program), x => x.ProgramDisplay, true), + new(nameof(FirewallRule.InterfaceType), x => x.InterfaceTypeDisplay, true), + new(nameof(FirewallRule.NetworkProfiles), x => x.NetworkProfilesDisplay, true), new(nameof(FirewallRule.Description), x => x.Description, true) ]; diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 980a2057c7..4e86884d96 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -334,8 +334,8 @@ public void Firewall_Consistent() [new FirewallRule { Name = "Rule, 1", Description = "Description \"x\"" }])); AssertConsistent(files, - "Name,IsEnabled,IsManaged,Source,Direction,Action,Protocol,LocalPorts,RemotePorts,LocalAddresses," + - "RemoteAddresses,NetworkProfiles,InterfaceType,Program,Description"); + "IsEnabled,Name,IsManaged,Source,Direction,Action,Protocol,LocalAddresses,LocalPorts,RemoteAddresses," + + "RemotePorts,Program,InterfaceType,NetworkProfiles,Description"); Assert.Equal("Rule, 1", files.CsvValue("Name")); Assert.Equal("Inbound", (string)files.JsonValue("Direction")); } diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 622befd5e9..9dd0dbcf64 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -30,6 +30,7 @@ Release date: **xx.xx.2026** - **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. - **IP Scanner**: the columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. - **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. +- **Firewall**: the columns of the export are in the order of the grid: `IsEnabled` first, the local and remote address before the port (`LocalAddresses`, `LocalPorts`, `RemoteAddresses`, `RemotePorts`), then `Program`, `InterfaceType`, `NetworkProfiles` and `Description`. ## What's new? From 3b08201d6e16554acaf92ba8b35d97ba99545da9 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:42:34 +0100 Subject: [PATCH 20/44] Export: same geolocation columns in IP Geolocation and Traceroute (R6) IP Geolocation in the order shown (Query / Reverse before the network, Hosting / Proxy / Mobile like Traceroute). Traceroute exports the region name shown in the grid in addition to the region code. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.IPGeolocationInfo.cs | 14 ++++++++------ .../Export/ExportManager.TracerouteHopInfo.cs | 5 +++-- .../Export/ExportManagerToolTests.cs | 7 ++++--- Website/docs/changelog/next-release.md | 2 ++ 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs index c126463577..5e6e949338 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NETworkManager.Models.IPApi; namespace NETworkManager.Models.Export; @@ -6,7 +6,8 @@ namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Exported fields of an . + /// Exported fields of an in the order shown: location, time zone and currency, + /// IP address, network (same order as the geolocation of a ). /// private static readonly ExportField[] IPGeolocationInfoExportFields = [ @@ -26,15 +27,16 @@ public static partial class ExportManager // Seconds (offset of the time zone to UTC) new(nameof(IPGeolocationInfo.Offset), x => x.Offset), new(nameof(IPGeolocationInfo.Currency), x => x.Currency), + // IP address and its DNS name + new(nameof(IPGeolocationInfo.Query), x => x.Query), + new(nameof(IPGeolocationInfo.Reverse), x => x.Reverse, true), new(nameof(IPGeolocationInfo.Isp), x => x.Isp, true), new(nameof(IPGeolocationInfo.Org), x => x.Org, true), new(nameof(IPGeolocationInfo.As), x => x.As, true), new(nameof(IPGeolocationInfo.Asname), x => x.Asname, true), - new(nameof(IPGeolocationInfo.Reverse), x => x.Reverse, true), - new(nameof(IPGeolocationInfo.Mobile), x => x.Mobile), - new(nameof(IPGeolocationInfo.Proxy), x => x.Proxy), new(nameof(IPGeolocationInfo.Hosting), x => x.Hosting), - new(nameof(IPGeolocationInfo.Query), x => x.Query) + new(nameof(IPGeolocationInfo.Proxy), x => x.Proxy), + new(nameof(IPGeolocationInfo.Mobile), x => x.Mobile) ]; /// diff --git a/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs index ec89afcacb..dc229e6970 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using NETworkManager.Models.IPApi; using NETworkManager.Models.Network; @@ -24,7 +24,8 @@ public static partial class ExportManager new(nameof(TracerouteHopInfo.Hostname), x => x.Hostname, true), new(nameof(IPGeolocationInfo.Continent), IfGeolocation(x => x.Continent), true), new(nameof(IPGeolocationInfo.Country), IfGeolocation(x => x.Country), true), - new(nameof(IPGeolocationInfo.Region), IfGeolocation(x => x.Region), true), + new(nameof(IPGeolocationInfo.Region), IfGeolocation(x => x.Region)), + new(nameof(IPGeolocationInfo.RegionName), IfGeolocation(x => x.RegionName), true), new(nameof(IPGeolocationInfo.City), IfGeolocation(x => x.City), true), new(nameof(IPGeolocationInfo.District), IfGeolocation(x => x.District), true), new(nameof(IPGeolocationInfo.Isp), IfGeolocation(x => x.Isp), true), diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index 4e86884d96..d8cb6e2350 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -107,13 +107,14 @@ public void Traceroute_Consistent() ])); AssertConsistent(files, - "Hop,Status1,Time1,Status2,Time2,Status3,Time3,IPAddress,Hostname,Continent,Country,Region,City,District," + - "Isp,Org,As,Asname,Hosting,Proxy,Mobile"); + "Hop,Status1,Time1,Status2,Time2,Status3,Time3,IPAddress,Hostname,Continent,Country,Region,RegionName," + + "City,District,Isp,Org,As,Asname,Hosting,Proxy,Mobile"); Assert.Equal("1", files.CsvValue("Time1")); Assert.Equal("", files.CsvValue("Time2")); Assert.Equal("3", files.CsvValue("Time3")); Assert.Equal("Example, Inc.", files.CsvValue("Isp")); + Assert.Equal("Bavaria", files.CsvValue("RegionName")); Assert.Equal(JTokenType.Boolean, files.JsonValue("Proxy").Type); // Hop without reply and geolocation @@ -347,7 +348,7 @@ public void IPGeolocation_Consistent() AssertConsistent(files, "Status,Continent,ContinentCode,Country,CountryCode,Region,RegionName,City,District,Zip,Lat,Lon,Timezone," + - "Offset,Currency,Isp,Org,As,Asname,Reverse,Mobile,Proxy,Hosting,Query"); + "Offset,Currency,Query,Reverse,Isp,Org,As,Asname,Hosting,Proxy,Mobile"); // Decimal point in every language Assert.Equal("48.1374", files.CsvValue("Lat")); diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 9dd0dbcf64..2842cdd49e 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -31,6 +31,7 @@ Release date: **xx.xx.2026** - **IP Scanner**: the columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. - **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. - **Firewall**: the columns of the export are in the order of the grid: `IsEnabled` first, the local and remote address before the port (`LocalAddresses`, `LocalPorts`, `RemoteAddresses`, `RemotePorts`), then `Program`, `InterfaceType`, `NetworkProfiles` and `Description`. +- **IP Geolocation**: the columns of the export are in the order shown: `Query` (IP address) and `Reverse` after `Currency`, then the network (`Isp`, `Org`, `As`, `Asname`, `Hosting`, `Proxy`, `Mobile`), like the geolocation in the **Traceroute** export. ## What's new? @@ -190,6 +191,7 @@ Release date: **xx.xx.2026** **Traceroute** - Added **RDAP...** to the context menu to query the registration data of the IP address, hostname or AS number of a hop in the [**RDAP**](../application/rdap.md) tool. [#3642](https://github.com/BornToBeRoot/NETworkManager/pull/3642) +- The export contains the region name shown in the grid (`RegionName`, e.g. `Bavaria`) after the region code (`Region`, e.g. `BY`), like the **IP Geolocation** export. **DNS Lookup** From e0788911005d0be57ee445337348262938b8d139 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:42:55 +0100 Subject: [PATCH 21/44] Export: Ping Monitor columns like the IP Scanner ping (R7) Status, time, TTL, bytes instead of bytes, time, TTL, status. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.PingInfo.cs | 9 +++++---- .../Export/ExportManagerToolTests.cs | 4 ++-- Website/docs/changelog/next-release.md | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs index 4bb46ab41d..9a7a55ca35 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using NETworkManager.Models.Network; namespace NETworkManager.Models.Export; @@ -6,17 +6,18 @@ namespace NETworkManager.Models.Export; public static partial class ExportManager { /// - /// Exported fields of a . Bytes, time (ms) and TTL are empty without a reply. + /// Exported fields of a (status, time, TTL, bytes like the ping of the IP Scanner). Time + /// (ms), TTL and bytes are empty without a reply. /// private static readonly ExportField[] PingInfoExportFields = [ new(nameof(PingInfo.Timestamp), x => x.Timestamp), new(nameof(PingInfo.IPAddress), x => x.IPAddress), new(nameof(PingInfo.Hostname), x => x.Hostname, true), - new(nameof(PingInfo.Bytes), x => HasPingReply(x.Status) ? x.Bytes : null), + new(nameof(PingInfo.Status), x => x.Status), new(nameof(PingInfo.Time), x => HasPingReply(x.Status) ? x.Time : null), new(nameof(PingInfo.TTL), x => HasPingReply(x.Status) ? x.TTL : null), - new(nameof(PingInfo.Status), x => x.Status) + new(nameof(PingInfo.Bytes), x => HasPingReply(x.Status) ? x.Bytes : null) ]; /// diff --git a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs index d8cb6e2350..8b949a27a3 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerToolTests.cs @@ -68,7 +68,7 @@ public void PingMonitor_Consistent() new PingInfo(Time, IPAddress, "host, a", IPStatus.TimedOut) ])); - AssertConsistent(files, "Timestamp,IPAddress,Hostname,Bytes,Time,TTL,Status"); + AssertConsistent(files, "Timestamp,IPAddress,Hostname,Status,Time,TTL,Bytes"); Assert.Equal("2026-11-08 10:15:30.123", files.CsvValue("Timestamp")); Assert.Equal("2026-11-08 10:15:30.123", files.XmlValue("Timestamp")); Assert.Equal("2026-11-08 10:15:30.123", (string)files.JsonValue("Timestamp")); @@ -86,7 +86,7 @@ public void PingMonitor_NoReply_Empty() var files = ExportAll((f, t) => ExportManager.Export(f, t, [new PingInfo(Time, IPAddress, "host", IPStatus.TimedOut)])); - Assert.Equal("2026-11-08 10:15:30.123,10.0.0.1,\"host\",,,,TimedOut", files.CsvLines[1]); + Assert.Equal("2026-11-08 10:15:30.123,10.0.0.1,\"host\",TimedOut,,,", files.CsvLines[1]); Assert.Equal(JTokenType.Null, files.JsonValue("Time").Type); Assert.Equal(JTokenType.Null, files.JsonValue("TTL").Type); Assert.Equal(JTokenType.Null, files.JsonValue("Bytes").Type); diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 2842cdd49e..a1606f70e6 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -22,7 +22,7 @@ Release date: **xx.xx.2026** - Removed the **ThreadPool additional min. threads** setting (Settings > General) and the application-wide `ThreadPool.SetMinThreads` workaround it configured for the IP Scanner and Port Scanner. It's no longer needed now that both scan engines use non-blocking async concurrency instead of blocking calls. [#3564](https://github.com/BornToBeRoot/NETworkManager/pull/3564) - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. -- **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. +- **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns are `Timestamp`, `IPAddress`, `Hostname`, `Status`, `Time`, `TTL`, `Bytes` (status first, like the ping of the **IP Scanner**). - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. - **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. - **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. From 6f944c8e36ccd319983b746a65a1e58c4b533760 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:43:47 +0100 Subject: [PATCH 22/44] Changelog: breaking note for the exports General note that exports changed and scripts should be checked (read columns by name), tool entries merged and in application order. Co-Authored-By: Claude Opus 5.5 --- Website/docs/changelog/next-release.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index a1606f70e6..232e442f8d 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -20,18 +20,18 @@ Release date: **xx.xx.2026** ## Breaking Changes - Removed the **ThreadPool additional min. threads** setting (Settings > General) and the application-wide `ThreadPool.SetMinThreads` workaround it configured for the IP Scanner and Port Scanner. It's no longer needed now that both scan engines use non-blocking async concurrency instead of blocking calls. [#3564](https://github.com/BornToBeRoot/NETworkManager/pull/3564) +- **Exports (CSV, XML, JSON)**: the exports of all tools now use the same format, see [Export format](../faq/export-format.md). Columns may have been reordered (like shown in the tool) or added, and values are formatted the same way in every tool (e.g. numbers without unit and with a decimal point, dates as `yyyy-MM-dd HH:mm:ss.fff`, MAC addresses as `AA:BB:CC:DD:EE:FF`, empty values instead of placeholders like `-/-`). If you process exports with scripts or other tools, check them after the update and read the columns by name instead of by position. The changes of each tool are listed below. +- **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. +- **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. +- **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. - **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns are `Timestamp`, `IPAddress`, `Hostname`, `Status`, `Time`, `TTL`, `Bytes` (status first, like the ping of the **IP Scanner**). - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. -- **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. - **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. -- **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. -- **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. -- **IP Scanner**: the columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. -- **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. - **Firewall**: the columns of the export are in the order of the grid: `IsEnabled` first, the local and remote address before the port (`LocalAddresses`, `LocalPorts`, `RemoteAddresses`, `RemotePorts`), then `Program`, `InterfaceType`, `NetworkProfiles` and `Description`. +- **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. - **IP Geolocation**: the columns of the export are in the order shown: `Query` (IP address) and `Reverse` after `Currency`, then the network (`Isp`, `Org`, `As`, `Asname`, `Hosting`, `Proxy`, `Mobile`), like the geolocation in the **Traceroute** export. +- **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. ## What's new? From 9b6b2f41ca9a575df63b5dae10f2be59bb217221 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:47:18 +0100 Subject: [PATCH 23/44] Changelog: link the export entries to #3696 Co-Authored-By: Claude Opus 5.5 --- Website/docs/changelog/next-release.md | 50 +++++++++++++------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 232e442f8d..034d3466a8 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -20,18 +20,18 @@ Release date: **xx.xx.2026** ## Breaking Changes - Removed the **ThreadPool additional min. threads** setting (Settings > General) and the application-wide `ThreadPool.SetMinThreads` workaround it configured for the IP Scanner and Port Scanner. It's no longer needed now that both scan engines use non-blocking async concurrency instead of blocking calls. [#3564](https://github.com/BornToBeRoot/NETworkManager/pull/3564) -- **Exports (CSV, XML, JSON)**: the exports of all tools now use the same format, see [Export format](../faq/export-format.md). Columns may have been reordered (like shown in the tool) or added, and values are formatted the same way in every tool (e.g. numbers without unit and with a decimal point, dates as `yyyy-MM-dd HH:mm:ss.fff`, MAC addresses as `AA:BB:CC:DD:EE:FF`, empty values instead of placeholders like `-/-`). If you process exports with scripts or other tools, check them after the update and read the columns by name instead of by position. The changes of each tool are listed below. -- **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. -- **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. -- **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. +- **Exports (CSV, XML, JSON)**: the exports of all tools now use the same format, see [Export format](../faq/export-format.md). Columns may have been reordered (like shown in the tool) or added, and values are formatted the same way in every tool (e.g. numbers without unit and with a decimal point, dates as `yyyy-MM-dd HH:mm:ss.fff`, MAC addresses as `AA:BB:CC:DD:EE:FF`, empty values instead of placeholders like `-/-`). If you process exports with scripts or other tools, check them after the update and read the columns by name instead of by position. The changes of each tool are listed below. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns are `Timestamp`, `IPAddress`, `Hostname`, `Status`, `Time`, `TTL`, `Bytes` (status first, like the ping of the **IP Scanner**). -- **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. -- **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. -- **Firewall**: the columns of the export are in the order of the grid: `IsEnabled` first, the local and remote address before the port (`LocalAddresses`, `LocalPorts`, `RemoteAddresses`, `RemotePorts`), then `Program`, `InterfaceType`, `NetworkProfiles` and `Description`. -- **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. -- **IP Geolocation**: the columns of the export are in the order shown: `Query` (IP address) and `Reverse` after `Currency`, then the network (`Isp`, `Org`, `As`, `Asname`, `Hosting`, `Proxy`, `Mobile`), like the geolocation in the **Traceroute** export. -- **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. +- **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns are `Timestamp`, `IPAddress`, `Hostname`, `Status`, `Time`, `TTL`, `Bytes` (status first, like the ping of the **IP Scanner**). [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **Firewall**: the columns of the export are in the order of the grid: `IsEnabled` first, the local and remote address before the port (`LocalAddresses`, `LocalPorts`, `RemoteAddresses`, `RemotePorts`), then `Program`, `InterfaceType`, `NetworkProfiles` and `Description`. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **IP Geolocation**: the columns of the export are in the order shown: `Query` (IP address) and `Reverse` after `Currency`, then the network (`Isp`, `Org`, `As`, `Asname`, `Hosting`, `Proxy`, `Mobile`), like the geolocation in the **Traceroute** export. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **Neighbor Table**: the export contains the MAC address as `AA:BB:CC:DD:EE:FF` (like it is shown) instead of `AABBCCDDEEFF`, like in all exports. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) ## What's new? @@ -81,7 +81,7 @@ Release date: **xx.xx.2026** **Network Interface** - Members of the **Network Configuration Operators** group can now change the network configuration (IP address, DNS servers, release/renew) without being an administrator. NETworkManager has to run elevated (**Restart as Administrator**, confirm with your own credentials). The hint is now also shown as tooltip on **Apply** in the profile context menu. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) -- The export contains the network profile (`Profile`, e.g. `Private`) after the speed, like in the details. +- The export contains the network profile (`Profile`, e.g. `Private`) after the speed, like in the details. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **WiFi** @@ -191,7 +191,7 @@ Release date: **xx.xx.2026** **Traceroute** - Added **RDAP...** to the context menu to query the registration data of the IP address, hostname or AS number of a hop in the [**RDAP**](../application/rdap.md) tool. [#3642](https://github.com/BornToBeRoot/NETworkManager/pull/3642) -- The export contains the region name shown in the grid (`RegionName`, e.g. `Bavaria`) after the region code (`Region`, e.g. `BY`), like the **IP Geolocation** export. +- The export contains the region name shown in the grid (`RegionName`, e.g. `Bavaria`) after the region code (`Region`, e.g. `BY`), like the **IP Geolocation** export. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **DNS Lookup** @@ -229,7 +229,7 @@ Release date: **xx.xx.2026** **Discovery Protocol** -- The export contains the values shown that were missing: `Management`, `ChassisId`, `LocalConnection` and `LocalInterface`. The columns are in the order shown (`Management` and `ChassisId` after `IPAddress`). +- The export contains the values shown that were missing: `Management`, `ChassisId`, `LocalConnection` and `LocalInterface`. The columns are in the order shown (`Management` and `ChassisId` after `IPAddress`). [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Whois** @@ -292,7 +292,7 @@ Release date: **xx.xx.2026** **Network Interface** - Fixed errors when changing the network configuration (e.g. missing permissions) not being shown — the change was reported as successful although it failed. The error message of Windows is now shown. [#3606](https://github.com/BornToBeRoot/NETworkManager/issues/3606) -- Fixed the CSV export breaking the row if the name, the description or the DNS suffix contains a comma (they are quoted now), and the JSON export containing the MAC address as `{}` and the status as a number (e.g. `1` instead of `Up`). +- Fixed the CSV export breaking the row if the name, the description or the DNS suffix contains a comma (they are quoted now), and the JSON export containing the MAC address as `{}` and the status as a number (e.g. `1` instead of `Up`). [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **WiFi** @@ -319,7 +319,7 @@ Release date: **xx.xx.2026** - Fixed the icon of the adapter selection (connected / disconnected) keeping the state of when the adapters were loaded. It is updated after each scan, e.g. after connecting or disconnecting. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Fixed `F5` scanning and **Automatically update every** refreshing the networks behind an open dialog (e.g. **Connect...** or **Export...**). The auto refresh waits until the dialog is closed. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Fixed the CSV export breaking the row of a network whose SSID contains a comma or a quote. SSID, security and vendor are quoted. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) -- Fixed the export formatting values differently per format: the JSON export contains `IsWiFiDirect`, `IsConnected`, `ChannelWidthEstimated` as `true` / `false` and `SignalBars`, `NetworkRssiInDecibelMilliwatts` as numbers instead of text, the XML export `BeaconInterval` and `Uptime` like the CSV export (e.g. `00:00:00.1024000`) instead of `PT0.1024S`, and the CSV export decimals with a point in every language. +- Fixed the export formatting values differently per format: the JSON export contains `IsWiFiDirect`, `IsConnected`, `ChannelWidthEstimated` as `true` / `false` and `SignalBars`, `NetworkRssiInDecibelMilliwatts` as numbers instead of text, the XML export `BeaconInterval` and `Uptime` like the CSV export (e.g. `00:00:00.1024000`) instead of `PT0.1024S`, and the CSV export decimals with a point in every language. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - Fixed a network being marked as **Connected** that the selected adapter isn't connected to, if the computer has several WiFi adapters and the selected one was disconnected. An error while reading the connected network no longer ends the scan. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) - Fixed the connection status message (e.g. "Connecting to ...") being hidden too early, while still connecting, if a previous message (e.g. after connecting or disconnecting) was shown shortly before. Each message is now shown for 15 seconds. [#3638](https://github.com/BornToBeRoot/NETworkManager/pull/3638) - Fixed the adapter list and the auto refresh keeping a removed adapter (e.g. an unplugged USB adapter) after **Refresh** found no adapter or failed: "No WiFi adapters found" is shown now. [#3695](https://github.com/BornToBeRoot/NETworkManager/pull/3695) @@ -388,7 +388,7 @@ Release date: **xx.xx.2026** - Fixed the ping not working when the ICMP **Buffer** was set to more than `65500` bytes (Windows limit). The maximum is now `65500`, higher values are lowered to `65500`. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) - Fixed hosts being added twice if the inputs overlap (e.g. `10.0.0.1; 10.0.0.0/24`). If an IP address is also entered as hostname, the hostname is kept; different hostnames of the same IP address (e.g. two names of one server) are all kept. [#3653](https://github.com/BornToBeRoot/NETworkManager/pull/3653) - Fixed **Copy** > **Hostname** copying a hostname resolved via DNS (`PTR`) with a trailing dot (e.g. `server.example.com.`). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) -- Fixed the CSV export breaking the row if the hostname contains a comma. The hostname is quoted now. +- Fixed the CSV export breaking the row if the hostname contains a comma. The hostname is quoted now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Traceroute** @@ -403,7 +403,7 @@ Release date: **xx.xx.2026** - Fixed **Add DNS suffix (primary) to hostname** silently appending no suffix at all on machines without a Windows primary DNS suffix configured (e.g. not domain-joined), even though a usable suffix was available via the active network adapter's connection-specific DNS suffix (shown under **DNS Suffix Search List** in `ipconfig /all`). It now falls back to that adapter's suffix in this case. [#3591](https://github.com/BornToBeRoot/NETworkManager/pull/3591) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the DNS server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - Fixed a technical error (*An invalid IP address was specified*) being shown for a hostname looked up with `PTR`. A message is shown and the hostname is skipped, the other hosts are looked up. [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) -- Fixed the CSV export breaking the row if a result (e.g. a `TXT` record) contains a comma or a quote. Domain name, result and name server hostname are quoted now. +- Fixed the CSV export breaking the row if a result (e.g. a `TXT` record) contains a comma or a quote. Domain name, result and name server hostname are quoted now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Web Console** @@ -413,17 +413,17 @@ Release date: **xx.xx.2026** - Fixed `Enter` in the search box of the OID profiles dialog closing the dialog with **OK**. It only filters the OID profiles now. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the OID profiles (dialog, settings). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) -- Fixed the CSV export breaking the row if the data contains a comma or a quote. The data is quoted now. +- Fixed the CSV export breaking the row if the data contains a comma or a quote. The data is quoted now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **SNTP Lookup** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the SNTP server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) -- Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the offset and round trip delay, the values are exported with a decimal point now. +- Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the offset and round trip delay, the values are exported with a decimal point now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Hosts File Editor** - Fixed the retry of a locked hosts file waiting 5 seconds between the attempts (the message said 2) and once more after the last attempt. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) -- Fixed the CSV export breaking the row if the comment contains a comma. Hostname and comment are quoted now. +- Fixed the CSV export breaking the row if the comment contains a comma. Hostname and comment are quoted now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Firewall** @@ -441,7 +441,7 @@ Release date: **xx.xx.2026** **Discovery Protocol** -- Fixed the CSV export breaking the row if a value (e.g. the device description) contains a comma or a quote. Text values are quoted now. +- Fixed the CSV export breaking the row if a value (e.g. the device description) contains a comma or a quote. Text values are quoted now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **RDAP** @@ -450,7 +450,7 @@ Release date: **xx.xx.2026** **IP Geolocation** - Fixed the query history of **IP Geolocation** being written to the history of **Whois** instead of its own. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) -- Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the latitude / longitude, or a comma in a text (e.g. the ISP `Example, Inc.`). Decimals are exported with a decimal point, text is quoted now. +- Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the latitude / longitude, or a comma in a text (e.g. the ISP `Example, Inc.`). Decimals are exported with a decimal point, text is quoted now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Subnet Calculator** @@ -459,7 +459,7 @@ Release date: **xx.xx.2026** **Bit Calculator** -- Fixed the CSV export breaking the row with a decimal comma (e.g. German), the values are exported with a decimal point now. +- Fixed the CSV export breaking the row with a decimal comma (e.g. German), the values are exported with a decimal point now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Lookup** @@ -500,6 +500,6 @@ Release date: **xx.xx.2026** - Added a unit test project (xUnit) with tests for the run command parser and the history lists. [#3644](https://github.com/BornToBeRoot/NETworkManager/pull/3644) - Reworked the GitHub issue templates as forms (bug report, feature request, question) that ask for the relevant information (e.g. affected feature, version, installation, Windows version, log), with links to the documentation, discussions, translations and security advisories. Simplified the pull request template and removed the Copilot summary section. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Faster CI: AppVeyor no longer builds a branch a second time when a PR is open, skips changes that only affect the documentation / website, builds ARM64 only for releases and now runs the unit tests. The website is only built for PRs that change it and builds about 3x faster (Docusaurus Faster). Dependabot also updates the GitHub Actions, and CodeQL also scans the workflows. Website changes are only merged automatically if the website builds. Dependabot major updates are no longer merged automatically. Removed the stale bot. [#3675](https://github.com/BornToBeRoot/NETworkManager/pull/3675) -- The exports (CSV, XML, JSON) of all tools define their columns once and are written by one shared writer, so the three formats can't drift apart and every tool formats the same kind of value the same way (not translated), see [Export format](../faq/export-format.md). Added unit tests for the exports. +- The exports (CSV, XML, JSON) of all tools define their columns once and are written by one shared writer, so the three formats can't drift apart and every tool formats the same kind of value the same way (not translated), see [Export format](../faq/export-format.md). Added unit tests for the exports. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - Language files updated via [#transifex](https://github.com/BornToBeRoot/NETworkManager/pulls?q=author%3Aapp%2Ftransifex-integration) - Dependencies updated via [#dependabot](https://github.com/BornToBeRoot/NETworkManager/pulls?q=author%3Aapp%2Fdependabot) From 9dda4fa79eb7f3d4d69599a0f25fcaaa4e732863 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:48:45 +0100 Subject: [PATCH 24/44] Grid order: shared CollectionViewExtensions (G1) GetItemsInViewOrder / GetSelectedItemsInViewOrder (filtered, sorted, grouped) replace the own helpers of WiFi, IP Scanner and Port Scanner. Tests run on Windows only (WPF), the test project uses WPF now. Co-Authored-By: Claude Opus 5.5 --- .../NETworkManager.Tests.csproj | 3 + .../CollectionViewExtensionsTests.cs | 98 +++++++++++++++++++ .../CollectionViewExtensions.cs | 61 ++++++++++++ .../ViewModels/IPScannerViewModel.cs | 20 +--- .../ViewModels/PortScannerViewModel.cs | 30 +----- .../ViewModels/WiFiViewModel.cs | 16 +-- 6 files changed, 173 insertions(+), 55 deletions(-) create mode 100644 Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs create mode 100644 Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs diff --git a/Source/NETworkManager.Tests/NETworkManager.Tests.csproj b/Source/NETworkManager.Tests/NETworkManager.Tests.csproj index 897095982a..71ba11a3b8 100644 --- a/Source/NETworkManager.Tests/NETworkManager.Tests.csproj +++ b/Source/NETworkManager.Tests/NETworkManager.Tests.csproj @@ -10,6 +10,8 @@ 10.0.22621.0 false true + + true @@ -19,5 +21,6 @@ + diff --git a/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs b/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs new file mode 100644 index 0000000000..9557d0e810 --- /dev/null +++ b/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Windows.Data; +using NETworkManager.Utilities.WPF; +using Xunit; + +namespace NETworkManager.Tests.Utilities; + +/// +/// Tests of (rows of a grid in the order shown, e.g. for the export). The +/// views need WPF: the tests only run on Windows. The WPF code is in separate methods, so the test methods can be +/// loaded without WPF. +/// +public class CollectionViewExtensionsTests +{ + private sealed record Item(string Group, int Value); + + private static readonly Item[] Items = + [ + new("b", 3), new("a", 2), new("b", 1), new("a", 4), new("c", 5) + ]; + + private static void SkipUnlessWindows() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "Needs WPF (Windows)"); + } + + [Fact] + public void GetItemsInViewOrder_Unsorted_SourceOrder() + { + SkipUnlessWindows(); + + Assert.Equal([3, 2, 1, 4, 5], GetItems(sort: false, filter: false, group: false)); + } + + [Fact] + public void GetItemsInViewOrder_SortedAndFiltered() + { + SkipUnlessWindows(); + + // Sorted by value, values > 4 filtered + Assert.Equal([1, 2, 3, 4], GetItems(sort: true, filter: true, group: false)); + } + + [Fact] + public void GetItemsInViewOrder_Grouped_InGroupOrder() + { + SkipUnlessWindows(); + + // Groups sorted by name, items sorted by value within the group + Assert.Equal([2, 4, 1, 3, 5], GetItems(sort: true, filter: false, group: true)); + } + + [Fact] + public void GetSelectedItemsInViewOrder_ViewOrderWithoutFilteredItems() + { + SkipUnlessWindows(); + + // Selected in the order 5 (filtered), 4, 1, 3 - returned in the order shown + Assert.Equal([1, 3, 4], GetSelectedItems([5, 4, 1, 3])); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static List GetItems(bool sort, bool filter, bool group) + { + return CreateView(sort, filter, group).GetItemsInViewOrder().Select(x => x.Value).ToList(); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static List GetSelectedItems(int[] selectedValues) + { + var selected = selectedValues.Select(value => Items.Single(x => x.Value == value)).ToList(); + + return CreateView(true, true, false).GetSelectedItemsInViewOrder(selected).Select(x => x.Value).ToList(); + } + + private static ListCollectionView CreateView(bool sort, bool filter, bool group) + { + var view = new ListCollectionView(Items.ToList()); + + if (group) + { + view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(Item.Group))); + view.SortDescriptions.Add(new SortDescription(nameof(Item.Group), ListSortDirection.Ascending)); + } + + if (sort) + view.SortDescriptions.Add(new SortDescription(nameof(Item.Value), ListSortDirection.Ascending)); + + if (filter) + view.Filter = x => ((Item)x).Value <= 4; + + return view; + } +} diff --git a/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs b/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs new file mode 100644 index 0000000000..9a75710894 --- /dev/null +++ b/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs @@ -0,0 +1,61 @@ +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Windows.Data; + +namespace NETworkManager.Utilities.WPF; + +/// +/// Extension methods for , e.g. to export or copy the rows of a grid in the order they +/// are shown. +/// +public static class CollectionViewExtensions +{ + /// + /// Gets the items of the view in the order they are shown: filtered, sorted and grouped (the items of the groups + /// in the order of the groups, also nested groups). Call it on the UI thread (the view is not thread-safe). + /// + /// Type of the items. + /// View of the items (e.g. the view a grid is bound to). + /// Items in the order shown. + public static List GetItemsInViewOrder(this ICollectionView view) + { + // Enumerating a grouped view returns the items in the sort order, not grouped + return view.Groups is { Count: > 0 } groups ? GetItems(groups).ToList() : view.Cast().ToList(); + } + + /// + /// Gets the selected items in the order they are shown in the view (the selected items of a grid are in the + /// order they were selected). Call it on the UI thread. + /// + /// Type of the items. + /// View of the items (e.g. the view a grid is bound to). + /// Selected items (e.g. DataGrid.SelectedItems). + /// Selected items in the order shown, without items that are not shown (e.g. filtered). + public static List GetSelectedItemsInViewOrder(this ICollectionView view, IEnumerable selectedItems) + { + var selected = new HashSet(selectedItems.Cast()); + + return view.GetItemsInViewOrder().Where(selected.Contains).ToList(); + } + + /// + /// Gets the items of groups (recursive for nested groups). + /// + private static IEnumerable GetItems(IEnumerable groupsOrItems) + { + foreach (var item in groupsOrItems) + { + if (item is CollectionViewGroup group) + { + foreach (var groupItem in GetItems(group.Items)) + yield return groupItem; + } + else + { + yield return (T)item; + } + } + } +} diff --git a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs index 8d43f81cf2..8cb258282e 100644 --- a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs @@ -1074,7 +1074,7 @@ private void CopySelectedResultsAction(object parameter) return; ClipboardHelper.SetClipboard(string.Join(Environment.NewLine, - GetSelectedResultsInGridOrder().Select(selector).Where(x => !string.IsNullOrEmpty(x)).Distinct())); + ResultsView.GetSelectedItemsInViewOrder(SelectedResults).Select(selector).Where(x => !string.IsNullOrEmpty(x)).Distinct())); } /// @@ -1306,7 +1306,7 @@ private void RescanSelectedHosts() if (IsRunning || _lastScanOptions == null) return; - var selectedIPAddresses = GetSelectedResultsInGridOrder().Select(x => x.IPAddress).ToHashSet(); + var selectedIPAddresses = ResultsView.GetSelectedItemsInViewOrder(SelectedResults).Select(x => x.IPAddress).ToHashSet(); if (selectedIPAddresses.Count == 0) return; @@ -1672,18 +1672,6 @@ private async Task CustomCommand(object guid) } } - /// - /// Gets the selected results in the order shown in the grid ( is in the order they - /// were selected). - /// - /// Selected results. - private List GetSelectedResultsInGridOrder() - { - var selectedResults = new HashSet(SelectedResults.Cast()); - - return ResultsView.Cast().Where(selectedResults.Contains).ToList(); - } - /// /// Exports the scan results. /// @@ -1705,8 +1693,8 @@ private Task Export() // export the copies in the background, so a large export doesn't freeze the window. In the // order shown in the grid (Results is in the order the hosts were found). var results = (instance.ExportAll - ? ResultsView.Cast() - : GetSelectedResultsInGridOrder()) + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults)) .Select(x => x.Clone()).ToList(); // Options of the shown scan (values of disabled probes are exported as empty values) diff --git a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs index 567f8ffba7..f6be387ca9 100644 --- a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs @@ -898,7 +898,7 @@ private void CopySelectedResultsAction(object parameter) return; ClipboardHelper.SetClipboard(string.Join(Environment.NewLine, - GetSelectedResultsInGridOrder().Select(selector).Where(x => !string.IsNullOrEmpty(x)).Distinct())); + ResultsView.GetSelectedItemsInViewOrder(SelectedResults).Select(selector).Where(x => !string.IsNullOrEmpty(x)).Distinct())); } public ICommand ExportCommand => new RelayCommand(_ => ExportAction()); @@ -1235,7 +1235,7 @@ private void RescanSelectedPorts() if (IsRunning || _lastPorts == null) return; - var rows = GetSelectedResultsInGridOrder(); + var rows = ResultsView.GetSelectedItemsInViewOrder(SelectedResults); if (rows.Count == 0) return; @@ -1537,28 +1537,6 @@ private void Stop() _cancellationTokenSource.Cancel(); } - /// - /// Gets the results in the order shown in the grid: grouped by host, sorted within the group. - /// - /// Results. - private IEnumerable GetResultsInGridOrder() - { - return ResultsView.Groups.Cast() - .SelectMany(group => group.Items.Cast()); - } - - /// - /// Gets the selected results in the order shown in the grid ( is in the order they - /// were selected). - /// - /// Selected results. - private List GetSelectedResultsInGridOrder() - { - var selectedResults = new HashSet(SelectedResults.Cast()); - - return GetResultsInGridOrder().Where(selectedResults.Contains).ToList(); - } - private Task Export() { var window = Application.Current.Windows.OfType().FirstOrDefault(x => x.IsActive); @@ -1576,8 +1554,8 @@ private Task Export() // export them in the background, so a large export doesn't freeze the window. In the order // shown in the grid (Results is in the order the ports were finished). var results = instance.ExportAll - ? GetResultsInGridOrder().ToList() - : GetSelectedResultsInGridOrder(); + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/WiFiViewModel.cs b/Source/NETworkManager/ViewModels/WiFiViewModel.cs index 283a4da165..4f8a1dbefa 100644 --- a/Source/NETworkManager/ViewModels/WiFiViewModel.cs +++ b/Source/NETworkManager/ViewModels/WiFiViewModel.cs @@ -703,7 +703,7 @@ private void CopySelectedNetworksAction(object parameter) return; ClipboardHelper.SetClipboard(string.Join(Environment.NewLine, - GetSelectedNetworksInGridOrder().Select(selector).Where(x => !string.IsNullOrEmpty(x)).Distinct())); + NetworksView.GetSelectedItemsInViewOrder(SelectedNetworks).Select(selector).Where(x => !string.IsNullOrEmpty(x)).Distinct())); } public ICommand ExportCommand => new RelayCommand(_ => ExportAction()); @@ -1471,16 +1471,6 @@ private async Task DisconnectAsync() await ScanAsync(SelectedAdapter, true, GlobalStaticConfiguration.ApplicationUIRefreshInterval); } - /// - /// Gets the selected networks in the order they are shown in the grid (not in the order they were selected). - /// - private List GetSelectedNetworksInGridOrder() - { - var selectedNetworks = new HashSet(SelectedNetworks.Cast()); - - return NetworksView.Cast().Where(selectedNetworks.Contains).ToList(); - } - private Task Export() { var childWindow = new ExportChildWindow(); @@ -1495,8 +1485,8 @@ private Task Export() // The networks shown in the grid (band filter, search) in their order. Copied on the UI thread, exported // in the background var networks = instance.ExportAll - ? NetworksView.Cast().ToList() - : GetSelectedNetworksInGridOrder(); + ? NetworksView.GetItemsInViewOrder() + : NetworksView.GetSelectedItemsInViewOrder(SelectedNetworks); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, networks)); } From 0186b1d070c6b50bdd28422c7d4a4c733c19c0f5 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:49:41 +0100 Subject: [PATCH 25/44] Export: Connections, Listeners and Neighbor Table in grid order (G2) Exports the rows shown (search) in the order shown, selected rows in the order shown; the file is written in the background. Co-Authored-By: Claude Opus 5.5 --- .../ViewModels/ConnectionsViewModel.cs | 12 +++++++----- .../NETworkManager/ViewModels/ListenersViewModel.cs | 11 +++++++---- .../ViewModels/NeighborTableViewModel.cs | 11 +++++++---- Website/docs/changelog/next-release.md | 3 +++ 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs index 9b3b191627..ddd7775962 100644 --- a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs +++ b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs @@ -312,11 +312,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast() - .ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Source/NETworkManager/ViewModels/ListenersViewModel.cs b/Source/NETworkManager/ViewModels/ListenersViewModel.cs index 0b4ae001ae..5d8b88b3bf 100644 --- a/Source/NETworkManager/ViewModels/ListenersViewModel.cs +++ b/Source/NETworkManager/ViewModels/ListenersViewModel.cs @@ -303,10 +303,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs b/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs index d6b3b2fc3d..4ade02d066 100644 --- a/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs +++ b/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs @@ -431,10 +431,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 034d3466a8..718d206f08 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -239,16 +239,19 @@ Release date: **xx.xx.2026** - The search filters after a short delay while typing instead of on every key press (smoother with many connections), `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; with **Automatically update every**, a countdown to the next refresh (`Next refresh in 00:04`). A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until it is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- **Export...** exports the entries shown (search) in the order shown (sorting), the selected entries in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Listeners** - The search filters after a short delay while typing instead of on every key press (smoother with many listeners), `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; with **Automatically update every**, a countdown to the next refresh (`Next refresh in 00:04`). A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until it is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- **Export...** exports the entries shown (search) in the order shown (sorting), the selected entries in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Neighbor Table** - The search filters after a short delay while typing instead of on every key press (smoother with many entries), `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; with **Automatically update every**, a countdown to the next refresh (`Next refresh in 00:04`). The line below the list only shows errors. A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until it is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- **Export...** exports the entries shown (search) in the order shown (sorting), the selected entries in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) ## Bug Fixes From 639246dbeb621520828c8e5736a2cdd62e4bee7d Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:50:08 +0100 Subject: [PATCH 26/44] Export: Firewall and Hosts File Editor in grid order (G3) Co-Authored-By: Claude Opus 5.5 --- .../NETworkManager/ViewModels/FirewallViewModel.cs | 11 +++++++---- .../ViewModels/HostsFileEditorViewModel.cs | 12 +++++++----- Website/docs/changelog/next-release.md | 2 ++ 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/Source/NETworkManager/ViewModels/FirewallViewModel.cs b/Source/NETworkManager/ViewModels/FirewallViewModel.cs index dd96babc4f..44cfb4fe3e 100644 --- a/Source/NETworkManager/ViewModels/FirewallViewModel.cs +++ b/Source/NETworkManager/ViewModels/FirewallViewModel.cs @@ -697,10 +697,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs b/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs index d61ed5d59c..ec3c8bbfad 100644 --- a/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs +++ b/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs @@ -301,11 +301,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast() - .ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 718d206f08..fc9e5be669 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -206,6 +206,7 @@ Release date: **xx.xx.2026** - Entries that don't change (e.g. enabling an already enabled entry, or confirming the edit dialog without changes) are no longer rewritten in the `hosts` file, so custom formatting such as tabs or alignment is kept. [#3624](https://github.com/BornToBeRoot/NETworkManager/pull/3624) - The search filters after a short delay while typing instead of on every key press (smoother with many entries), `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; the line below the list only shows errors. A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until it is finished. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- **Export** exports the entries shown (search) in the order shown (sorting), the selected entries in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Firewall** @@ -226,6 +227,7 @@ Release date: **xx.xx.2026** - Faster loading of the rules managed by NETworkManager if there are many of them (the ports, addresses, programs etc. of all rules are queried at once instead of per rule). [#3637](https://github.com/BornToBeRoot/NETworkManager/pull/3637) - `Enter` in the search box filters the rules right away instead of after the delay while typing. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - The time of the last refresh (`Reloaded at 14:32`, the date in the tooltip) is shown in the header instead of a status line below the list; the line below the list only shows errors (e.g. rules loaded with errors, a failed action). A manual refresh is faster (the minimum of 2.5 seconds runs while loading, not before) and the refresh icon spins until the rules are loaded (also with **Show all rules**). [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- **Export** exports the rules shown (search) in the order shown (sorting), the selected rules in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Discovery Protocol** From 840fc5b286949dbb662b6ddc03b25764a3e165d1 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:50:40 +0100 Subject: [PATCH 27/44] Export: DNS Lookup, SNTP Lookup and SNMP in grid order (G4) Co-Authored-By: Claude Opus 5.5 --- .../NETworkManager/ViewModels/DNSLookupViewModel.cs | 13 ++++++++----- Source/NETworkManager/ViewModels/SNMPViewModel.cs | 12 ++++++++---- .../ViewModels/SNTPLookupViewModel.cs | 12 ++++++++---- Website/docs/changelog/next-release.md | 9 +++++++++ 4 files changed, 33 insertions(+), 13 deletions(-) diff --git a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs index 4edb355348..53d5735e6e 100644 --- a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs @@ -7,6 +7,7 @@ using NETworkManager.Models.Network; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections; @@ -550,11 +551,13 @@ private Task Export() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults - .Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Source/NETworkManager/ViewModels/SNMPViewModel.cs b/Source/NETworkManager/ViewModels/SNMPViewModel.cs index 8ffdcf8914..23a369e21c 100644 --- a/Source/NETworkManager/ViewModels/SNMPViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNMPViewModel.cs @@ -7,6 +7,7 @@ using NETworkManager.Models.Network; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections; @@ -645,10 +646,13 @@ private Task Export() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? QueryResults - : new ObservableCollection(SelectedResults.Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs index 65bfee71ed..142955c0fb 100644 --- a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs @@ -7,6 +7,7 @@ using NETworkManager.Models.Network; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections; @@ -227,10 +228,13 @@ private Task Export() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index fc9e5be669..58650188f5 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -198,6 +198,15 @@ Release date: **xx.xx.2026** - Profiles: new option **DNS server** to use a DNS server of the profile instead of the one selected in the DNS lookup, with the same list and `Tab` completion. It can also be set in the group (used by the profiles of the group that don't override it). New option **Type** (record type) in the profile; without it, a profile is looked up with `PTR` for IP addresses and `A` for hostnames instead of the last selected record type. Configured DNS servers are referenced by the profile (changes apply, also after a rename), their IP addresses are saved as well and used, with a note, if the DNS server can't be found (e.g. a profile file shared from another computer). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) [#3667](https://github.com/BornToBeRoot/NETworkManager/pull/3667) - Several DNS servers can be entered, also names of configured DNS servers together with custom DNS servers (e.g. `Google Public DNS; Cloudflare; 9.9.9.9`), every DNS server is queried once; `[Windows DNS]` in a list adds the DNS servers of Windows. The list of the **DNS server** input shows the history and the configured DNS servers (name, with the IP addresses below), `Tab` completes the name of a DNS server that is being typed (e.g. `google; cl` → `google; Cloudflare`). The name of a DNS server must not contain `;` (replaced by `,` when updating). Also with the run command (`dns borntoberoot.net "Google Public DNS";cloudflare`). [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - IP addresses opened from another feature (e.g. **IP Scanner** > **DNS lookup** > **IP address**), from a profile or with the run command are looked up with `PTR` instead of the selected record type. [#3644](https://github.com/BornToBeRoot/NETworkManager/pull/3644) +- **Export...** exports the results in the order shown (sorting), the selected results in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) + +**SNMP** + +- **Export...** exports the results in the order shown (sorting), the selected results in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) + +**SNTP Lookup** + +- **Export...** exports the results in the order shown (sorting), the selected results in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Hosts File Editor** From ca36b4d771b2f7204dc6351aa7517a86a0b4e1d3 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:51:01 +0100 Subject: [PATCH 28/44] Export: Lookup (OUI / Port) and Subnet Calculator in grid order (G5) Co-Authored-By: Claude Opus 5.5 --- .../ViewModels/LookupOUILookupViewModel.cs | 12 ++++++++---- .../ViewModels/LookupPortViewModel.cs | 13 ++++++++----- .../SubnetCalculatorSubnettingViewModel.cs | 12 ++++++++---- Website/docs/changelog/next-release.md | 8 ++++++++ 4 files changed, 32 insertions(+), 13 deletions(-) diff --git a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs index 35b0ea1b5e..8ae4b0f3cc 100644 --- a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs @@ -5,6 +5,7 @@ using NETworkManager.Models.Lookup; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections; @@ -282,10 +283,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs index 9dfa14b708..8aac93aaff 100644 --- a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs @@ -6,6 +6,7 @@ using NETworkManager.Models.Network; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections; @@ -341,11 +342,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast() - .ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs index 8847bdacd7..f220a4e4f9 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs @@ -5,6 +5,7 @@ using NETworkManager.Models.Network; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections; @@ -170,10 +171,13 @@ private Task ExportAction() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : new ObservableCollection(SelectedResults.Cast().ToArray())); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 58650188f5..3ee6bbf8df 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -246,6 +246,14 @@ Release date: **xx.xx.2026** - Added an **Export...** button below the result, like in the other tools. [#3607](https://github.com/BornToBeRoot/NETworkManager/pull/3607) +**Subnet Calculator** + +- **Export...** (subnetting) exports the subnets in the order shown (sorting), the selected subnets in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) + +**Lookup** + +- **Export...** (OUI and port lookup) exports the results in the order shown (sorting), the selected results in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) + **Connections** - The search filters after a short delay while typing instead of on every key press (smoother with many connections), `Enter` filters right away. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) From abdf5fe49fc8fd49c698dc08cb667a46158f746b Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:51:22 +0100 Subject: [PATCH 29/44] Export: Traceroute in grid order (G6) Hops in the order shown (sorted by hop), also the selected hops. Co-Authored-By: Claude Opus 5.5 --- .../NETworkManager/ViewModels/TracerouteViewModel.cs | 12 ++++++++---- Website/docs/changelog/next-release.md | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs index d7ec5ec390..9ffc8afda0 100644 --- a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs @@ -9,6 +9,7 @@ using NETworkManager.Models.RDAP; using NETworkManager.Settings; using NETworkManager.Utilities; +using NETworkManager.Utilities.WPF; using NETworkManager.Views; using System; using System.Collections; @@ -458,10 +459,13 @@ private Task Export() try { - ExportManager.Export(instance.FilePath, instance.FileType, - instance.ExportAll - ? Results - : SelectedResults.Cast().ToArray()); + // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, + // exported in the background + var results = instance.ExportAll + ? ResultsView.GetItemsInViewOrder() + : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 3ee6bbf8df..76aeb7d4a9 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -192,6 +192,7 @@ Release date: **xx.xx.2026** - Added **RDAP...** to the context menu to query the registration data of the IP address, hostname or AS number of a hop in the [**RDAP**](../application/rdap.md) tool. [#3642](https://github.com/BornToBeRoot/NETworkManager/pull/3642) - The export contains the region name shown in the grid (`RegionName`, e.g. `Bavaria`) after the region code (`Region`, e.g. `BY`), like the **IP Geolocation** export. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **Export...** exports the hops in the order shown (by hop), the selected hops in the order shown instead of the order they were selected. The file is written in the background, so the window stays responsive. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **DNS Lookup** From d6134d140405cccd4b9de27edfae20452196780f Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:53:12 +0100 Subject: [PATCH 30/44] Docs: export of the results shown in the order shown (G7) Export rows of the tools link the export format, FAQ explains which results are exported, WiFi columns in the new order. Co-Authored-By: Claude Opus 5.5 --- Website/docs/application/connections.md | 2 +- Website/docs/application/dns-lookup.md | 2 +- Website/docs/application/firewall.md | 2 +- Website/docs/application/hosts-file-editor.md | 2 +- Website/docs/application/ip-scanner.md | 2 +- Website/docs/application/listeners.md | 2 +- Website/docs/application/lookup.md | 4 ++-- Website/docs/application/neighbor-table.md | 2 +- Website/docs/application/port-scanner.md | 4 ++-- Website/docs/application/snmp.md | 2 +- Website/docs/application/sntp-lookup.md | 2 +- Website/docs/application/traceroute.md | 2 +- Website/docs/application/wifi.md | 2 +- Website/docs/faq/export-format.md | 4 ++++ 14 files changed, 19 insertions(+), 15 deletions(-) diff --git a/Website/docs/application/connections.md b/Website/docs/application/connections.md index 03620747bb..35882c9dd3 100644 --- a/Website/docs/application/connections.md +++ b/Website/docs/application/connections.md @@ -21,7 +21,7 @@ The data shown is similar to the output of the `netstat` command. | Action | Description | |--------|-------------| | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ### Keyboard shortcuts diff --git a/Website/docs/application/dns-lookup.md b/Website/docs/application/dns-lookup.md index 10d1903128..02b5ed37c9 100644 --- a/Website/docs/application/dns-lookup.md +++ b/Website/docs/application/dns-lookup.md @@ -66,7 +66,7 @@ The DNS server can be selected from a list of configured servers or you can ente | Action | Description | | ------------- | ------------------------------------------------ | | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ## Profile diff --git a/Website/docs/application/firewall.md b/Website/docs/application/firewall.md index 5123129acf..050472651e 100644 --- a/Website/docs/application/firewall.md +++ b/Website/docs/application/firewall.md @@ -77,7 +77,7 @@ Multiple rules can be selected (`Ctrl` / `Shift` + click) to enable, disable or | **Copy as** | Opens the dialog pre-filled with the selected rule to create a new rule based on it (single rule only, not for rules with [unsupported values](#rules-not-managed-by-networkmanager)) | | **Delete** | Removes the selected rule or rules (after confirmation) | | **Copy** | Copies the rule information to the clipboard (single rule only) | -| **Export** | Exports the selected rules (or all rules) to a file (CSV, XML or JSON, incl. whether the rule is managed by NETworkManager and its source) | +| **Export** | Exports the rules shown (all or the selected ones) to a file in the order shown (CSV, XML or JSON, incl. whether the rule is managed by NETworkManager and its source), see [Export format](../faq/export-format.md) | ### Keyboard shortcuts diff --git a/Website/docs/application/hosts-file-editor.md b/Website/docs/application/hosts-file-editor.md index 205acc276a..f01cf1f65a 100644 --- a/Website/docs/application/hosts-file-editor.md +++ b/Website/docs/application/hosts-file-editor.md @@ -54,7 +54,7 @@ Multiple entries can be selected (`Ctrl` / `Shift` + click) to enable, disable, | **Copy as** | Opens the dialog pre-filled with the selected entry to create a new entry based on it (single entry only) | | **Delete** | Removes the selected entry or entries (after confirmation) | | **Copy** | Copies the entry information to the clipboard (single entry only) | -| **Export** | Exports the selected entries (or all entries) to a file | +| **Export** | Exports the entries shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ### Keyboard shortcuts diff --git a/Website/docs/application/ip-scanner.md b/Website/docs/application/ip-scanner.md index 133413bf2f..8c11bab1ef 100644 --- a/Website/docs/application/ip-scanner.md +++ b/Website/docs/application/ip-scanner.md @@ -86,7 +86,7 @@ Right-clicking a result allows forwarding device information to another tool (e. | **Custom commands** | Executes a [custom command](#custom-commands) for the host | | **Add profile...** | Creates a new profile with the host (IP address), the hostname as name and the MAC address for Wake on LAN | | **Copy** | Copies the selected information to the clipboard (values only when the probe / lookup is finished), also **OS**, **Open ports** and **Domain** as shown in the columns; with the optional requests also **mDNS hostname**, **Windows** > **Operating system** / **Time offset** / **Logged-on users**, **Web** > **Title** / **URL** / **Server** and **SNMP** > **Name** / **Description** / **Location** | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | A NetBIOS or mDNS name (shown as hostname if there is no DNS hostname) is not passed to other tools, because it may not be resolvable via DNS - the IP address is used instead. **DNS lookup...** / **RDAP...** > **Hostname** are only available with a DNS hostname. In [custom commands](#custom-commands), `{{Hostname}}` is the shown hostname (DNS, mDNS or NetBIOS). diff --git a/Website/docs/application/listeners.md b/Website/docs/application/listeners.md index eb509194dd..c33f5785dd 100644 --- a/Website/docs/application/listeners.md +++ b/Website/docs/application/listeners.md @@ -21,7 +21,7 @@ A network listener is a socket bound to a specific local IP address and port tha | Action | Description | |--------|-------------| | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ### Keyboard shortcuts diff --git a/Website/docs/application/lookup.md b/Website/docs/application/lookup.md index 11eec57dfc..12055f8fc3 100644 --- a/Website/docs/application/lookup.md +++ b/Website/docs/application/lookup.md @@ -25,7 +25,7 @@ The OUI (Organizationally Unique Identifier) is a 24-bit number assigned by the | Action | Description | |--------|-------------| | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ## Port @@ -44,4 +44,4 @@ A port is a logical construct that identifies a specific process to which networ | Action | Description | |--------|-------------| | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | diff --git a/Website/docs/application/neighbor-table.md b/Website/docs/application/neighbor-table.md index 50c07362d0..c100f6b91d 100644 --- a/Website/docs/application/neighbor-table.md +++ b/Website/docs/application/neighbor-table.md @@ -38,7 +38,7 @@ Without administrator privileges, the view is read-only. Use the **Restart as ad | Action | Description | |--------|-------------| | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | | **Delete** | Removes the selected entry | ### Keyboard shortcuts diff --git a/Website/docs/application/port-scanner.md b/Website/docs/application/port-scanner.md index 9a15131a52..d1011b386b 100644 --- a/Website/docs/application/port-scanner.md +++ b/Website/docs/application/port-scanner.md @@ -77,7 +77,7 @@ The **Ports** input lists the recently scanned ports (history) and the [port pro | **SNMP** | Opens the host (hostname if resolved, otherwise the IP address) in [SNMP](./snmp) | | **Add profile...** | Creates a new profile with the host (IP address), the hostname as name and the ports of the shown scan for the Port Scanner | | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | If multiple results are selected, **Rescan**, **Copy** > **IP address** / **Hostname** / **Port** / **IP address:Port** (one value per line, in the order shown, without duplicates; IPv6 as `[address]:port`) and **Export...** are available. @@ -94,7 +94,7 @@ Right-click the header of a host (group) for the actions of the host: The results are grouped by host (one group per IP address, the header shows the hostname, the IP address and the number of open ports) and sorted by IP address and port. The number of open, closed and timed out ports is shown below the **Result** header. A port is **open** if the connection was established, **closed** if the host refused the connection and **timed out** if there was no answer within the [timeout](#timeout-ms) (e.g. blocked by a firewall). Only open ports are shown, unless [Show closed ports](#show-closed-ports) is enabled (closed and timed out ports). The **Hostname** column is shown if [Resolve hostname](#resolve-hostname) was enabled when the scan was started. -The search box right of the **Result** header filters the results by IP address, hostname, port, protocol, service, description and status, also while the scan is running. **Export...** > all exports the filtered results; the counters always count all ports. +The search box right of the **Result** header filters the results by IP address, hostname, port, protocol, service, description and status, also while the scan is running. **Export...** > all exports the filtered results (grouped by host, in the order shown); the counters always count all ports. ### Changes since the last scan diff --git a/Website/docs/application/snmp.md b/Website/docs/application/snmp.md index d85e7a0d69..708b6f8a1e 100644 --- a/Website/docs/application/snmp.md +++ b/Website/docs/application/snmp.md @@ -46,7 +46,7 @@ Multiple OIDs (`.1.3.6.1.2.1.1; .1.3.6.1.2.1.2`) can be specified when using the | Action | Description | | ------------- | ----------------------------------------------- | | **Copy** | Copy the selected information to the clipboard. | -| **Export...** | Export the selected or all results to a file. | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ## Profile diff --git a/Website/docs/application/sntp-lookup.md b/Website/docs/application/sntp-lookup.md index 9cfa9d2522..101a4db874 100644 --- a/Website/docs/application/sntp-lookup.md +++ b/Website/docs/application/sntp-lookup.md @@ -21,7 +21,7 @@ SNTP (Simple Network Time Protocol) is a simplified version of NTP (Network Time | Action | Description | |--------|-------------| | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ## Settings diff --git a/Website/docs/application/traceroute.md b/Website/docs/application/traceroute.md index a31b5a460c..6d6d5fdb2f 100644 --- a/Website/docs/application/traceroute.md +++ b/Website/docs/application/traceroute.md @@ -28,7 +28,7 @@ Right-clicking a hop allows forwarding it to another tool (e.g. [Port Scanner](. | Action | Description | |--------|-------------| | **Copy** | Copies the selected information to the clipboard | -| **Export...** | Exports the selected or all results to a file | +| **Export...** | Exports the results shown (all or the selected ones) to a file in the order shown, see [Export format](../faq/export-format.md) | ### Map diff --git a/Website/docs/application/wifi.md b/Website/docs/application/wifi.md index 8b3d0e9c12..0adfb649b6 100644 --- a/Website/docs/application/wifi.md +++ b/Website/docs/application/wifi.md @@ -108,7 +108,7 @@ The status of the connection (`Connecting to ...`, the result or the error) is s ### Export -**Export...** exports the networks as CSV, XML or JSON: **all** exports the networks shown (filtered by band and search) in the order shown, **selected** the selected networks in the order shown. Columns / elements: `Bssid`, `Ssid`, `ChannelCenterFrequencyInKilohertz`, `SignalBars`, `IsWiFiDirect`, `NetworkRssiInDecibelMilliwatts`, `PhyKind`, `NetworkKind`, `NetworkAuthenticationType`, `NetworkEncryptionType`, `BeaconInterval`, `Uptime`, `IsConnected`, `Security`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated`, `Vendor` and `Change`. +**Export...** exports the networks as CSV, XML or JSON: **all** exports the networks shown (filtered by band and search) in the order shown, **selected** the selected networks in the order shown. Columns / elements in the order of the grid: `Ssid`, `IsConnected`, `Security`, `ChannelCenterFrequencyInKilohertz`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated`, `SignalBars`, `NetworkRssiInDecibelMilliwatts`, `NetworkAuthenticationType`, `NetworkEncryptionType`, `Bssid`, `Vendor`, `PhyKind`, `NetworkKind`, `IsWiFiDirect`, `BeaconInterval`, `Uptime` and `Change`, see [Export format](../faq/export-format.md). ### Keyboard shortcuts diff --git a/Website/docs/faq/export-format.md b/Website/docs/faq/export-format.md index 5348eb924d..60607fbfa6 100644 --- a/Website/docs/faq/export-format.md +++ b/Website/docs/faq/export-format.md @@ -17,6 +17,10 @@ Most tools can export their results with **Export...** (selected or all results) The CSV columns, the XML elements and the JSON keys have the same names and order. The columns are in a logical order: like they are shown in the tool, related values next to each other (e.g. the ping or the web page values of the **IP Scanner**). A new column is added where it belongs, so a script should read the columns by name (CSV header, XML element, JSON key) instead of by position. +## Which results are exported? + +**Export...** exports what is shown in the result: **All** exports the results shown (e.g. filtered by the search) in the order shown (sorting, grouping), **Selected** the selected results in the order shown (not in the order they were selected). + ## How are the values formatted? | Value | Format | From c038cd5fa8fd44341c4fe7a4fb0b46dd9e899871 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:56:38 +0100 Subject: [PATCH 31/44] Normalize line endings of ExportManager.IPScannerHostInfo.cs A lone CR at the end of the file (no final line break) prevented git from normalizing it, so it was stored with CRLF since E3. Content unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.IPScannerHostInfo.cs | 504 +++++++++--------- 1 file changed, 252 insertions(+), 252 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs index ec088405ff..8e1291457f 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs @@ -1,252 +1,252 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NETworkManager.Models.Network; - -namespace NETworkManager.Models.Export; - -public static partial class ExportManager -{ - /// - /// Method to export objects from type to a file. - /// - /// Path to the export file. - /// Allowed are CSV, XML or JSON. - /// Objects as to export. - /// - /// Options of the scan the hosts are from. Values of disabled probes are exported as empty values instead of - /// their placeholders (e.g. port status "Closed" if the port scan was disabled). - /// - public static void Export(string filePath, ExportFileType fileType, - IReadOnlyList collection, IPScannerResultOptions options) - { - // Skip if critical data is null - Export(filePath, fileType, collection.Where(info => info?.PingInfo != null), - GetIPScannerHostInfoExportFields(options), ApplicationName.IPScanner); - } - - /// - /// Exported fields of a (ports of a host, see ). - /// - private static readonly ExportField[] PortInfoExportFields = - [ - new(nameof(PortInfo.Port), x => x.Port), - new(nameof(PortInfo.LookupInfo.Protocol), x => x.LookupInfo.Protocol), - new(nameof(PortInfo.LookupInfo.Service), x => x.LookupInfo.Service), - new(nameof(PortInfo.LookupInfo.Description), x => x.LookupInfo.Description), - new(nameof(PortInfo.State), x => x.State) - ]; - - /// - /// Gets the exported fields of an , grouped by topic (host, ping, ports, NetBIOS, - /// web page, SNMP, Windows, change since the previous scan). Values of a probe that is still running - /// (export during a scan, or a scan canceled before the probe finished) or disabled are placeholders - exported - /// as empty values instead of a result. The ports are an (joined in the CSV - /// file, one element per port in XML, an array in JSON). - /// - /// Options of the scan the hosts are from. - /// Fields in the order of the columns. - private static ExportField[] GetIPScannerHostInfoExportFields(IPScannerResultOptions options) - { - var isWebPageRead = IsWebPageRead(options); - - Func IfEnabled(bool isEnabled, Func value) => - info => isEnabled ? value(info) : null; - - // Ping values only with a reply (time, TTL, bytes) - Func IfPingReply(Func value) => info => - GetPingInfo(info, options) is { } ping && HasPingReply(ping.Status) ? value(ping) : null; - - Func IfNetBIOS(Func value) => info => - GetNetBIOSInfo(info, options) is { } netBIOSInfo ? value(netBIOSInfo) : null; - - Func IfCertificate(Func value) => info => - GetWebCertificate(info, options) is { } certificate ? value(certificate) : null; - - // Windows host information: null (empty values) if disabled, "" if the host had none - Func IfWindows(Func value) => info => - options.WindowsEnabled ? info.Windows == null ? string.Empty : value(info.Windows) ?? string.Empty : null; - - // Number / bool like WebStatusCode / WebCertificateSelfSigned: null without a value - Func IfWindowsValue(Func value) => info => - options.WindowsEnabled && info.Windows != null ? value(info.Windows) : null; - - return - [ - // Host (the hostname is the DNS name, or the mDNS / NetBIOS name as fallback) - new(nameof(IPScannerHostInfo.IsReachable), x => x.IsReachable), - new(nameof(IPScannerHostInfo.DetectedBy), GetDetectedBy, true), - new(nameof(PingInfo.IPAddress), x => x.PingInfo.IPAddress), - new(nameof(IPScannerHostInfo.Hostname), x => x.Hostname, true), - new(nameof(IPScannerHostInfo.DNSHostname), x => x.DNSHostname, true), - new(nameof(IPScannerHostInfo.MDNSHostname), IfEnabled(options.MDNSEnabled, x => x.MDNSHostname), true), - new(nameof(IPScannerHostInfo.MACAddress), x => x.MACAddress), - new(nameof(IPScannerHostInfo.Vendor), x => x.Vendor, true), - new(nameof(IPScannerHostInfo.Role), GetRole, true), - new(nameof(IPScannerHostInfo.OSGuess), x => GetOSGuess(x, options)), - // Ping (time in ms, time / TTL / bytes only with a reply) - new("PingStatus", x => GetPingInfo(x, options)?.Status), - new(nameof(PingInfo.Timestamp), x => GetPingInfo(x, options)?.Timestamp), - new(nameof(PingInfo.Time), IfPingReply(x => x.Time)), - new(nameof(PingInfo.TTL), IfPingReply(x => x.TTL)), - new(nameof(PingInfo.Bytes), IfPingReply(x => x.Bytes)), - // Port scan - new("PortStatus", x => GetPortStatus(x, options)), - new(nameof(IPScannerHostInfo.Ports), x => new ExportList(nameof(PortInfo), - x.Ports != null && options.PortScanEnabled ? x.Ports : [], PortInfoExportFields), true), - // NetBIOS - new("NetBIOSIsReachable", IfNetBIOS(x => x.IsReachable)), - new("NetBIOSIPAddress", IfNetBIOS(x => x.IPAddress)), - new("NetBIOSComputerName", IfNetBIOS(x => x.ComputerName), true), - new("NetBIOSUserName", IfNetBIOS(x => x.UserName), true), - new("NetBIOSGroupName", IfNetBIOS(x => x.GroupName), true), - new("NetBIOSMACAddress", IfNetBIOS(x => x.MACAddress)), - new("NetBIOSVendor", IfNetBIOS(x => x.Vendor), true), - // Web page (only read with the port scan) - new(nameof(IPScannerHostInfo.WebURL), IfEnabled(isWebPageRead, x => x.WebURL), true), - new(nameof(IPScannerHostInfo.WebStatusCode), x => GetWebStatusCode(x, options)), - new(nameof(IPScannerHostInfo.WebTitle), IfEnabled(isWebPageRead, x => x.WebTitle), true), - new(nameof(IPScannerHostInfo.WebServer), IfEnabled(isWebPageRead, x => x.WebServer), true), - new(nameof(IPScannerHostInfo.WebPoweredBy), IfEnabled(isWebPageRead, x => x.WebPoweredBy), true), - new(nameof(IPScannerHostInfo.WebRealm), IfEnabled(isWebPageRead, x => x.WebRealm), true), - new(nameof(IPScannerHostInfo.WebRedirectURL), IfEnabled(isWebPageRead, x => x.WebRedirectURL), true), - new("WebCertificateSubject", IfCertificate(x => x.Subject), true), - new("WebCertificateIssuer", IfCertificate(x => x.Issuer), true), - new("WebCertificateNotAfter", IfCertificate(x => x.NotAfter.ToLocalTime())), - new("WebCertificateSelfSigned", IfCertificate(x => x.IsSelfSigned)), - // SNMP system information (SNMPError: SNMPv3 error of the host, e.g. "AuthenticationFailed") - new(nameof(IPScannerHostInfo.SNMPName), IfEnabled(options.SNMPEnabled, x => x.SNMPName), true), - new(nameof(IPScannerHostInfo.SNMPDescription), IfEnabled(options.SNMPEnabled, x => x.SNMPDescription), - true), - new(nameof(IPScannerHostInfo.SNMPLocation), IfEnabled(options.SNMPEnabled, x => x.SNMPLocation), true), - new(nameof(IPScannerHostInfo.SNMPError), - IfEnabled(options.SNMPEnabled, x => x.HasSNMPError ? x.SNMPError.ToString() : string.Empty), true), - // Windows host information (SMB / NTLM, NetApi). WindowsTimeOffset: seconds (time of the host minus the local - // time), WindowsError: Win32 error of the NetApi requests (e.g. 5 = access denied, 1326 = wrong username or - // password) - new("WindowsOS", IfWindows(x => x.OS), true), - new("WindowsEdition", IfWindows(x => x.Edition), true), - new("WindowsVersion", IfWindows(x => x.Version?.ToString())), - new("WindowsRole", IfWindows(x => x.Role == WindowsHostRole.Unknown ? string.Empty : x.Role.ToString())), - new("WindowsComputerName", IfWindows(x => x.ComputerName), true), - new("WindowsDomain", IfWindows(x => x.Domain), true), - new("WindowsTimeOffset", - IfWindowsValue(x => x.TimeOffset is { } offset ? Math.Round(offset.TotalSeconds, 3) : null)), - new("WindowsUsers", IfWindows(x => x.Users == null ? string.Empty : string.Join(ListSeparator, x.Users)), - true), - new("WindowsDescription", IfWindows(x => x.Description), true), - new("WindowsError", IfWindowsValue(x => x.Error == 0 ? null : x.Error)), - new("SMBDialect", IfWindows(x => x.SMB?.Dialect)), - new("SMBSigningRequired", IfWindowsValue(x => x.SMB?.SigningRequired)), - new("SMBServerGuid", IfWindows(x => x.SMB?.ServerGuid.ToString())), - // Change since the previous scan of the same input (empty without a previous scan / change) - new(nameof(IPScannerHostInfo.Change), x => x.Change == IPScannerHostChange.None ? null : x.Change), - new(nameof(IPScannerHostInfo.PreviousMACAddress), x => x.PreviousMACAddress) - ]; - } - - /// - /// Gets the probes a host answered (e.g. "ICMP, TCP"), null if it is unreachable. - /// - /// Host to get the probes for. - /// Probes or null. - private static string GetDetectedBy(IPScannerHostInfo info) - { - return info.DetectedBy == IPScannerDetectionMethod.None ? null : info.DetectedBy.ToString(); - } - - /// - /// Checks if the web pages were read in the scan: only with the port scan (only open ports are requested). - /// - /// Options of the scan the hosts are from. - /// True if the web pages were read. - private static bool IsWebPageRead(IPScannerResultOptions options) - { - return options.PortScanEnabled && options.WebPageEnabled; - } - - /// - /// Gets the HTTP status code of the web page of a host, null if none answered or the web page was not read. - /// - /// Host to get the status code for. - /// Options of the scan the host is from. - /// Status code or null. - private static int? GetWebStatusCode(IPScannerHostInfo info, IPScannerResultOptions options) - { - return IsWebPageRead(options) && info.WebStatusCode > 0 ? info.WebStatusCode : null; - } - - /// - /// Gets the TLS certificate of the web page of a host, null for http, if none answered or the web page was not - /// read. - /// - /// Host to get the certificate for. - /// Options of the scan the host is from. - /// Certificate or null. - private static WebCertificateInfo GetWebCertificate(IPScannerHostInfo info, IPScannerResultOptions options) - { - return IsWebPageRead(options) ? info.WebCertificate : null; - } - - /// - /// Gets the roles of a host for the local computer (e.g. "DefaultGateway, DNSServer"), null if it has none. - /// - /// Host to get the roles for. - /// Roles or null. - private static string GetRole(IPScannerHostInfo info) - { - return info.Role == IPScannerHostRole.None ? null : info.Role.ToString(); - } - - /// - /// Gets the operating system guessed from the TTL (e.g. "Windows"), null if there is no guess or it was disabled. - /// - /// Host to get the guess for. - /// Options of the scan the host is from. - /// Guessed operating system or null. - private static string GetOSGuess(IPScannerHostInfo info, IPScannerResultOptions options) - { - return options.ICMPEnabled && options.OSGuessEnabled && info.OSGuess != IPScannerOSGuess.None - ? info.OSGuess.ToString() - : null; - } - - /// - /// Gets the result of the ping to a host - null while the ping is still running or if it was disabled - /// (placeholder). - /// - /// Host to get the ping result for. - /// Options of the scan the host is from. - /// Result of the ping or null. - private static PingInfo GetPingInfo(IPScannerHostInfo info, IPScannerResultOptions options) - { - return info.IsPingPending || !options.ICMPEnabled ? null : info.PingInfo; - } - - /// - /// Gets the NetBIOS information of a host - null while the NetBIOS request is still running or if it was - /// disabled (placeholder). - /// - /// Host to get the NetBIOS information for. - /// Options of the scan the host is from. - /// NetBIOS information or null. - private static NetBIOSInfo GetNetBIOSInfo(IPScannerHostInfo info, IPScannerResultOptions options) - { - return info.IsNetBIOSPending || !options.NetBIOSEnabled ? null : info.NetBIOSInfo; - } - - /// - /// Gets the port status of a host: open if any port is open, otherwise closed - null while the port scan is - /// still running (no result yet) or if it was disabled. - /// - /// Host to get the port status for. - /// Options of the scan the host is from. - /// Port status or null. - private static PortState? GetPortStatus(IPScannerHostInfo info, IPScannerResultOptions options) - { - if (info.IsPortScanPending || !options.PortScanEnabled) - return null; - - return info.IsAnyPortOpen ? PortState.Open : PortState.Closed; - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using NETworkManager.Models.Network; + +namespace NETworkManager.Models.Export; + +public static partial class ExportManager +{ + /// + /// Method to export objects from type to a file. + /// + /// Path to the export file. + /// Allowed are CSV, XML or JSON. + /// Objects as to export. + /// + /// Options of the scan the hosts are from. Values of disabled probes are exported as empty values instead of + /// their placeholders (e.g. port status "Closed" if the port scan was disabled). + /// + public static void Export(string filePath, ExportFileType fileType, + IReadOnlyList collection, IPScannerResultOptions options) + { + // Skip if critical data is null + Export(filePath, fileType, collection.Where(info => info?.PingInfo != null), + GetIPScannerHostInfoExportFields(options), ApplicationName.IPScanner); + } + + /// + /// Exported fields of a (ports of a host, see ). + /// + private static readonly ExportField[] PortInfoExportFields = + [ + new(nameof(PortInfo.Port), x => x.Port), + new(nameof(PortInfo.LookupInfo.Protocol), x => x.LookupInfo.Protocol), + new(nameof(PortInfo.LookupInfo.Service), x => x.LookupInfo.Service), + new(nameof(PortInfo.LookupInfo.Description), x => x.LookupInfo.Description), + new(nameof(PortInfo.State), x => x.State) + ]; + + /// + /// Gets the exported fields of an , grouped by topic (host, ping, ports, NetBIOS, + /// web page, SNMP, Windows, change since the previous scan). Values of a probe that is still running + /// (export during a scan, or a scan canceled before the probe finished) or disabled are placeholders - exported + /// as empty values instead of a result. The ports are an (joined in the CSV + /// file, one element per port in XML, an array in JSON). + /// + /// Options of the scan the hosts are from. + /// Fields in the order of the columns. + private static ExportField[] GetIPScannerHostInfoExportFields(IPScannerResultOptions options) + { + var isWebPageRead = IsWebPageRead(options); + + Func IfEnabled(bool isEnabled, Func value) => + info => isEnabled ? value(info) : null; + + // Ping values only with a reply (time, TTL, bytes) + Func IfPingReply(Func value) => info => + GetPingInfo(info, options) is { } ping && HasPingReply(ping.Status) ? value(ping) : null; + + Func IfNetBIOS(Func value) => info => + GetNetBIOSInfo(info, options) is { } netBIOSInfo ? value(netBIOSInfo) : null; + + Func IfCertificate(Func value) => info => + GetWebCertificate(info, options) is { } certificate ? value(certificate) : null; + + // Windows host information: null (empty values) if disabled, "" if the host had none + Func IfWindows(Func value) => info => + options.WindowsEnabled ? info.Windows == null ? string.Empty : value(info.Windows) ?? string.Empty : null; + + // Number / bool like WebStatusCode / WebCertificateSelfSigned: null without a value + Func IfWindowsValue(Func value) => info => + options.WindowsEnabled && info.Windows != null ? value(info.Windows) : null; + + return + [ + // Host (the hostname is the DNS name, or the mDNS / NetBIOS name as fallback) + new(nameof(IPScannerHostInfo.IsReachable), x => x.IsReachable), + new(nameof(IPScannerHostInfo.DetectedBy), GetDetectedBy, true), + new(nameof(PingInfo.IPAddress), x => x.PingInfo.IPAddress), + new(nameof(IPScannerHostInfo.Hostname), x => x.Hostname, true), + new(nameof(IPScannerHostInfo.DNSHostname), x => x.DNSHostname, true), + new(nameof(IPScannerHostInfo.MDNSHostname), IfEnabled(options.MDNSEnabled, x => x.MDNSHostname), true), + new(nameof(IPScannerHostInfo.MACAddress), x => x.MACAddress), + new(nameof(IPScannerHostInfo.Vendor), x => x.Vendor, true), + new(nameof(IPScannerHostInfo.Role), GetRole, true), + new(nameof(IPScannerHostInfo.OSGuess), x => GetOSGuess(x, options)), + // Ping (time in ms, time / TTL / bytes only with a reply) + new("PingStatus", x => GetPingInfo(x, options)?.Status), + new(nameof(PingInfo.Timestamp), x => GetPingInfo(x, options)?.Timestamp), + new(nameof(PingInfo.Time), IfPingReply(x => x.Time)), + new(nameof(PingInfo.TTL), IfPingReply(x => x.TTL)), + new(nameof(PingInfo.Bytes), IfPingReply(x => x.Bytes)), + // Port scan + new("PortStatus", x => GetPortStatus(x, options)), + new(nameof(IPScannerHostInfo.Ports), x => new ExportList(nameof(PortInfo), + x.Ports != null && options.PortScanEnabled ? x.Ports : [], PortInfoExportFields), true), + // NetBIOS + new("NetBIOSIsReachable", IfNetBIOS(x => x.IsReachable)), + new("NetBIOSIPAddress", IfNetBIOS(x => x.IPAddress)), + new("NetBIOSComputerName", IfNetBIOS(x => x.ComputerName), true), + new("NetBIOSUserName", IfNetBIOS(x => x.UserName), true), + new("NetBIOSGroupName", IfNetBIOS(x => x.GroupName), true), + new("NetBIOSMACAddress", IfNetBIOS(x => x.MACAddress)), + new("NetBIOSVendor", IfNetBIOS(x => x.Vendor), true), + // Web page (only read with the port scan) + new(nameof(IPScannerHostInfo.WebURL), IfEnabled(isWebPageRead, x => x.WebURL), true), + new(nameof(IPScannerHostInfo.WebStatusCode), x => GetWebStatusCode(x, options)), + new(nameof(IPScannerHostInfo.WebTitle), IfEnabled(isWebPageRead, x => x.WebTitle), true), + new(nameof(IPScannerHostInfo.WebServer), IfEnabled(isWebPageRead, x => x.WebServer), true), + new(nameof(IPScannerHostInfo.WebPoweredBy), IfEnabled(isWebPageRead, x => x.WebPoweredBy), true), + new(nameof(IPScannerHostInfo.WebRealm), IfEnabled(isWebPageRead, x => x.WebRealm), true), + new(nameof(IPScannerHostInfo.WebRedirectURL), IfEnabled(isWebPageRead, x => x.WebRedirectURL), true), + new("WebCertificateSubject", IfCertificate(x => x.Subject), true), + new("WebCertificateIssuer", IfCertificate(x => x.Issuer), true), + new("WebCertificateNotAfter", IfCertificate(x => x.NotAfter.ToLocalTime())), + new("WebCertificateSelfSigned", IfCertificate(x => x.IsSelfSigned)), + // SNMP system information (SNMPError: SNMPv3 error of the host, e.g. "AuthenticationFailed") + new(nameof(IPScannerHostInfo.SNMPName), IfEnabled(options.SNMPEnabled, x => x.SNMPName), true), + new(nameof(IPScannerHostInfo.SNMPDescription), IfEnabled(options.SNMPEnabled, x => x.SNMPDescription), + true), + new(nameof(IPScannerHostInfo.SNMPLocation), IfEnabled(options.SNMPEnabled, x => x.SNMPLocation), true), + new(nameof(IPScannerHostInfo.SNMPError), + IfEnabled(options.SNMPEnabled, x => x.HasSNMPError ? x.SNMPError.ToString() : string.Empty), true), + // Windows host information (SMB / NTLM, NetApi). WindowsTimeOffset: seconds (time of the host minus the local + // time), WindowsError: Win32 error of the NetApi requests (e.g. 5 = access denied, 1326 = wrong username or + // password) + new("WindowsOS", IfWindows(x => x.OS), true), + new("WindowsEdition", IfWindows(x => x.Edition), true), + new("WindowsVersion", IfWindows(x => x.Version?.ToString())), + new("WindowsRole", IfWindows(x => x.Role == WindowsHostRole.Unknown ? string.Empty : x.Role.ToString())), + new("WindowsComputerName", IfWindows(x => x.ComputerName), true), + new("WindowsDomain", IfWindows(x => x.Domain), true), + new("WindowsTimeOffset", + IfWindowsValue(x => x.TimeOffset is { } offset ? Math.Round(offset.TotalSeconds, 3) : null)), + new("WindowsUsers", IfWindows(x => x.Users == null ? string.Empty : string.Join(ListSeparator, x.Users)), + true), + new("WindowsDescription", IfWindows(x => x.Description), true), + new("WindowsError", IfWindowsValue(x => x.Error == 0 ? null : x.Error)), + new("SMBDialect", IfWindows(x => x.SMB?.Dialect)), + new("SMBSigningRequired", IfWindowsValue(x => x.SMB?.SigningRequired)), + new("SMBServerGuid", IfWindows(x => x.SMB?.ServerGuid.ToString())), + // Change since the previous scan of the same input (empty without a previous scan / change) + new(nameof(IPScannerHostInfo.Change), x => x.Change == IPScannerHostChange.None ? null : x.Change), + new(nameof(IPScannerHostInfo.PreviousMACAddress), x => x.PreviousMACAddress) + ]; + } + + /// + /// Gets the probes a host answered (e.g. "ICMP, TCP"), null if it is unreachable. + /// + /// Host to get the probes for. + /// Probes or null. + private static string GetDetectedBy(IPScannerHostInfo info) + { + return info.DetectedBy == IPScannerDetectionMethod.None ? null : info.DetectedBy.ToString(); + } + + /// + /// Checks if the web pages were read in the scan: only with the port scan (only open ports are requested). + /// + /// Options of the scan the hosts are from. + /// True if the web pages were read. + private static bool IsWebPageRead(IPScannerResultOptions options) + { + return options.PortScanEnabled && options.WebPageEnabled; + } + + /// + /// Gets the HTTP status code of the web page of a host, null if none answered or the web page was not read. + /// + /// Host to get the status code for. + /// Options of the scan the host is from. + /// Status code or null. + private static int? GetWebStatusCode(IPScannerHostInfo info, IPScannerResultOptions options) + { + return IsWebPageRead(options) && info.WebStatusCode > 0 ? info.WebStatusCode : null; + } + + /// + /// Gets the TLS certificate of the web page of a host, null for http, if none answered or the web page was not + /// read. + /// + /// Host to get the certificate for. + /// Options of the scan the host is from. + /// Certificate or null. + private static WebCertificateInfo GetWebCertificate(IPScannerHostInfo info, IPScannerResultOptions options) + { + return IsWebPageRead(options) ? info.WebCertificate : null; + } + + /// + /// Gets the roles of a host for the local computer (e.g. "DefaultGateway, DNSServer"), null if it has none. + /// + /// Host to get the roles for. + /// Roles or null. + private static string GetRole(IPScannerHostInfo info) + { + return info.Role == IPScannerHostRole.None ? null : info.Role.ToString(); + } + + /// + /// Gets the operating system guessed from the TTL (e.g. "Windows"), null if there is no guess or it was disabled. + /// + /// Host to get the guess for. + /// Options of the scan the host is from. + /// Guessed operating system or null. + private static string GetOSGuess(IPScannerHostInfo info, IPScannerResultOptions options) + { + return options.ICMPEnabled && options.OSGuessEnabled && info.OSGuess != IPScannerOSGuess.None + ? info.OSGuess.ToString() + : null; + } + + /// + /// Gets the result of the ping to a host - null while the ping is still running or if it was disabled + /// (placeholder). + /// + /// Host to get the ping result for. + /// Options of the scan the host is from. + /// Result of the ping or null. + private static PingInfo GetPingInfo(IPScannerHostInfo info, IPScannerResultOptions options) + { + return info.IsPingPending || !options.ICMPEnabled ? null : info.PingInfo; + } + + /// + /// Gets the NetBIOS information of a host - null while the NetBIOS request is still running or if it was + /// disabled (placeholder). + /// + /// Host to get the NetBIOS information for. + /// Options of the scan the host is from. + /// NetBIOS information or null. + private static NetBIOSInfo GetNetBIOSInfo(IPScannerHostInfo info, IPScannerResultOptions options) + { + return info.IsNetBIOSPending || !options.NetBIOSEnabled ? null : info.NetBIOSInfo; + } + + /// + /// Gets the port status of a host: open if any port is open, otherwise closed - null while the port scan is + /// still running (no result yet) or if it was disabled. + /// + /// Host to get the port status for. + /// Options of the scan the host is from. + /// Port status or null. + private static PortState? GetPortStatus(IPScannerHostInfo info, IPScannerResultOptions options) + { + if (info.IsPortScanPending || !options.PortScanEnabled) + return null; + + return info.IsAnyPortOpen ? PortState.Open : PortState.Closed; + } +} \ No newline at end of file From 2002b9f6fb55769bfeeeb23c200c7c2602c9e68c Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:15:10 +0100 Subject: [PATCH 32/44] Fix: SNTP Lookup offset and round trip delay cut off (review #2) Both were calculated with integer (long) division: the offset in whole seconds, the delay in whole milliseconds. Now double, rounded to 1 ms / 0.01 ms. Converter names match their type (Double...). Co-Authored-By: Claude Opus 5.5 --- .../DoubleToSecondsStringConverter.cs | 2 +- Source/NETworkManager.Models/Network/SNTPLookup.cs | 10 ++++++---- Source/NETworkManager/Views/SNTPLookupView.xaml | 12 ++++++------ Website/docs/changelog/next-release.md | 1 + 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/Source/NETworkManager.Converters/DoubleToSecondsStringConverter.cs b/Source/NETworkManager.Converters/DoubleToSecondsStringConverter.cs index 6654400436..522575e566 100644 --- a/Source/NETworkManager.Converters/DoubleToSecondsStringConverter.cs +++ b/Source/NETworkManager.Converters/DoubleToSecondsStringConverter.cs @@ -4,7 +4,7 @@ namespace NETworkManager.Converters; -public sealed class IntToSecondsStringConverter : IValueConverter +public sealed class DoubleToSecondsStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { diff --git a/Source/NETworkManager.Models/Network/SNTPLookup.cs b/Source/NETworkManager.Models/Network/SNTPLookup.cs index 0a20f369c0..42b89480b6 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookup.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookup.cs @@ -79,17 +79,19 @@ private static SNTPDateTime GetNetworkTimeRfc2030(IPEndPoint server, int timeout var milliseconds = intPart * 1000 + fractionPart * 1000 / 0x100000000L; var networkTime = new DateTime(1900, 1, 1).AddMilliseconds((long)milliseconds); - // Calculate local offset with local start/end time and network time in seconds + // Offset of the local clock (local time in the middle of the request minus the network time) in seconds and + // round trip delay in milliseconds - as double, so a part of a second / millisecond isn't cut off. The network + // time has a resolution of 1 ms var roundTripDelayTicks = localEndTime.Ticks - localStartTime.Ticks; - var offsetInSeconds = (localStartTime.Ticks + roundTripDelayTicks / 2 - networkTime.Ticks) / - TimeSpan.TicksPerSecond; + var offsetInSeconds = Math.Round( + (localStartTime.Ticks + roundTripDelayTicks / 2.0 - networkTime.Ticks) / TimeSpan.TicksPerSecond, 3); return new SNTPDateTime { LocalStartTime = localStartTime, LocalEndTime = localEndTime, NetworkTime = networkTime, - RoundTripDelay = roundTripDelayTicks / TimeSpan.TicksPerMillisecond, + RoundTripDelay = Math.Round((double)roundTripDelayTicks / TimeSpan.TicksPerMillisecond, 2), Offset = offsetInSeconds }; } diff --git a/Source/NETworkManager/Views/SNTPLookupView.xaml b/Source/NETworkManager/Views/SNTPLookupView.xaml index 0617de47eb..da70ae96e9 100644 --- a/Source/NETworkManager/Views/SNTPLookupView.xaml +++ b/Source/NETworkManager/Views/SNTPLookupView.xaml @@ -16,8 +16,8 @@ - - + + @@ -148,11 +148,11 @@ Style="{StaticResource ResourceKey=CopyMenuItem}" /> diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 76aeb7d4a9..700032204d 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -442,6 +442,7 @@ Release date: **xx.xx.2026** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the SNTP server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the offset and round trip delay, the values are exported with a decimal point now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- Fixed the offset being cut off to whole seconds and the round trip delay to whole milliseconds (e.g. an offset of 0.25 s was shown and exported as `0 s`). The offset is shown with millisecond precision, the round trip delay with 0.01 ms. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Hosts File Editor** From 2b8224d07a870bf3e093589d15680fbfbcdcb3f2 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:15:21 +0100 Subject: [PATCH 33/44] Docs: export dates are local time, SNTP Lookup in UTC (review #1) The SNTP Lookup times are UTC (also in the grid); the export format said local time for all dates. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager.Models/Export/ExportManager.cs | 3 ++- Website/docs/faq/export-format.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index 6e8e9cd0e8..c98770626d 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -28,7 +28,8 @@ namespace NETworkManager.Models.Export; /// Numbers with a decimal point (invariant culture), without a unit (e.g. ping time in ms, offset in /// s - the unit is documented). Bools as True / False (CSV), true / false (XML). /// JSON: numbers and bools as JSON numbers / bools, everything else as text. -/// Date and time: local time as yyyy-MM-dd HH:mm:ss.fff, time span as [-][d.]hh:mm:ss[.fffffff]. +/// Date and time as shown in the tool (local time; SNTP Lookup: UTC) as yyyy-MM-dd HH:mm:ss.fff, +/// time span as [-][d.]hh:mm:ss[.fffffff]. /// Enums as their (English) name (e.g. Success, flags: ICMP, TCP). /// MAC addresses as AA:BB:CC:DD:EE:FF. /// Lists (e.g. IP addresses) as one text, separated by ; . diff --git a/Website/docs/faq/export-format.md b/Website/docs/faq/export-format.md index 60607fbfa6..c4283abf5b 100644 --- a/Website/docs/faq/export-format.md +++ b/Website/docs/faq/export-format.md @@ -29,7 +29,7 @@ The CSV columns, the XML elements and the JSON keys have the same names and orde | Number | Decimal point in every language (e.g. `10.5`), without a unit. JSON: number | | Time / duration | Number in a fixed unit: ping time in milliseconds (e.g. `4`), SNTP **Offset** in seconds and **RoundTripDelay** in milliseconds, **Speed** of a network interface in bit/s | | Yes / No | `True` / `False` (CSV), `true` / `false` (XML, JSON) | -| Date and time | Local time as `yyyy-MM-dd HH:mm:ss.fff` (e.g. `2026-11-08 10:15:30.123`) | +| Date and time | `yyyy-MM-dd HH:mm:ss.fff` (e.g. `2026-11-08 10:15:30.123`) in the time shown in the tool: local time, **SNTP Lookup** in UTC | | Status, type, state | English name (e.g. `Success`, `TimedOut`, `Open`, `Tcp`), several values separated by `, ` (e.g. `ICMP, TCP`) | | MAC address | `AA:BB:CC:DD:EE:FF` | | List (e.g. IP addresses) | One value, separated by `; ` (e.g. `10.0.0.53; 10.0.0.54`) | From adb3029732668c8feb66bd341dae93b2c57e921e Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:16:17 +0100 Subject: [PATCH 34/44] Grid order: one call for Export... > All / Selected (review #5) GetItemsInViewOrder(all, selectedItems) replaces the copied ExportAll ? ... : ... block in 15 view models. Co-Authored-By: Claude Opus 5.5 --- .../Utilities/CollectionViewExtensionsTests.cs | 18 ++++++++++++++++++ .../CollectionViewExtensions.cs | 14 ++++++++++++++ .../ViewModels/ConnectionsViewModel.cs | 4 +--- .../ViewModels/DNSLookupViewModel.cs | 4 +--- .../ViewModels/FirewallViewModel.cs | 4 +--- .../ViewModels/HostsFileEditorViewModel.cs | 4 +--- .../ViewModels/IPScannerViewModel.cs | 4 +--- .../ViewModels/ListenersViewModel.cs | 4 +--- .../ViewModels/LookupOUILookupViewModel.cs | 4 +--- .../ViewModels/LookupPortViewModel.cs | 4 +--- .../ViewModels/NeighborTableViewModel.cs | 4 +--- .../ViewModels/PortScannerViewModel.cs | 4 +--- .../NETworkManager/ViewModels/SNMPViewModel.cs | 4 +--- .../ViewModels/SNTPLookupViewModel.cs | 4 +--- .../SubnetCalculatorSubnettingViewModel.cs | 4 +--- .../ViewModels/TracerouteViewModel.cs | 4 +--- .../NETworkManager/ViewModels/WiFiViewModel.cs | 4 +--- 17 files changed, 47 insertions(+), 45 deletions(-) diff --git a/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs b/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs index 9557d0e810..fa46f7d760 100644 --- a/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs +++ b/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs @@ -63,6 +63,24 @@ public void GetSelectedItemsInViewOrder_ViewOrderWithoutFilteredItems() Assert.Equal([1, 3, 4], GetSelectedItems([5, 4, 1, 3])); } + [Fact] + public void GetItemsInViewOrder_AllOrSelected() + { + SkipUnlessWindows(); + + // All shown (export > All) vs. selected (export > Selected), both in the order shown + Assert.Equal([1, 2, 3, 4], GetItemsAllOrSelected(true, [5, 4, 1, 3])); + Assert.Equal([1, 3, 4], GetItemsAllOrSelected(false, [5, 4, 1, 3])); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static List GetItemsAllOrSelected(bool all, int[] selectedValues) + { + var selected = selectedValues.Select(value => Items.Single(x => x.Value == value)).ToList(); + + return CreateView(true, true, false).GetItemsInViewOrder(all, selected).Select(x => x.Value).ToList(); + } + [MethodImpl(MethodImplOptions.NoInlining)] private static List GetItems(bool sort, bool filter, bool group) { diff --git a/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs b/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs index 9a75710894..e4e34d93d3 100644 --- a/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs +++ b/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs @@ -40,6 +40,20 @@ public static List GetSelectedItemsInViewOrder(this ICollectionView view, return view.GetItemsInViewOrder().Where(selected.Contains).ToList(); } + /// + /// Gets all items or only the selected items in the order they are shown, e.g. for Export... > All / + /// Selected. Call it on the UI thread. + /// + /// Type of the items. + /// View of the items (e.g. the view a grid is bound to). + /// True for all items shown, false for the selected items. + /// Selected items (e.g. DataGrid.SelectedItems), only used if not all. + /// Items in the order shown. + public static List GetItemsInViewOrder(this ICollectionView view, bool all, IEnumerable selectedItems) + { + return all ? view.GetItemsInViewOrder() : view.GetSelectedItemsInViewOrder(selectedItems); + } + /// /// Gets the items of groups (recursive for nested groups). /// diff --git a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs index ddd7775962..97d78fd806 100644 --- a/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs +++ b/Source/NETworkManager/ViewModels/ConnectionsViewModel.cs @@ -314,9 +314,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs index 53d5735e6e..c3d78e3485 100644 --- a/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/DNSLookupViewModel.cs @@ -553,9 +553,7 @@ private Task Export() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/FirewallViewModel.cs b/Source/NETworkManager/ViewModels/FirewallViewModel.cs index 44cfb4fe3e..9871c8dd08 100644 --- a/Source/NETworkManager/ViewModels/FirewallViewModel.cs +++ b/Source/NETworkManager/ViewModels/FirewallViewModel.cs @@ -699,9 +699,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs b/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs index ec3c8bbfad..c955c80d98 100644 --- a/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs +++ b/Source/NETworkManager/ViewModels/HostsFileEditorViewModel.cs @@ -303,9 +303,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs index 8cb258282e..0cbb65156a 100644 --- a/Source/NETworkManager/ViewModels/IPScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/IPScannerViewModel.cs @@ -1692,9 +1692,7 @@ private Task Export() // Copy the results on the UI thread (they are still updated while a scan is running) and // export the copies in the background, so a large export doesn't freeze the window. In the // order shown in the grid (Results is in the order the hosts were found). - var results = (instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults)) + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults) .Select(x => x.Clone()).ToList(); // Options of the shown scan (values of disabled probes are exported as empty values) diff --git a/Source/NETworkManager/ViewModels/ListenersViewModel.cs b/Source/NETworkManager/ViewModels/ListenersViewModel.cs index 5d8b88b3bf..0761a4b9c2 100644 --- a/Source/NETworkManager/ViewModels/ListenersViewModel.cs +++ b/Source/NETworkManager/ViewModels/ListenersViewModel.cs @@ -305,9 +305,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs index 8ae4b0f3cc..06e10e9b06 100644 --- a/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupOUILookupViewModel.cs @@ -285,9 +285,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs index 8aac93aaff..576a541a65 100644 --- a/Source/NETworkManager/ViewModels/LookupPortViewModel.cs +++ b/Source/NETworkManager/ViewModels/LookupPortViewModel.cs @@ -344,9 +344,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs b/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs index 4ade02d066..108328d794 100644 --- a/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs +++ b/Source/NETworkManager/ViewModels/NeighborTableViewModel.cs @@ -433,9 +433,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs index f6be387ca9..69ecdc6965 100644 --- a/Source/NETworkManager/ViewModels/PortScannerViewModel.cs +++ b/Source/NETworkManager/ViewModels/PortScannerViewModel.cs @@ -1553,9 +1553,7 @@ private Task Export() // Copy the results on the UI thread (they may still change while a scan is running) and // export them in the background, so a large export doesn't freeze the window. In the order // shown in the grid (Results is in the order the ports were finished). - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/SNMPViewModel.cs b/Source/NETworkManager/ViewModels/SNMPViewModel.cs index 23a369e21c..fae5366719 100644 --- a/Source/NETworkManager/ViewModels/SNMPViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNMPViewModel.cs @@ -648,9 +648,7 @@ private Task Export() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs index 142955c0fb..b69cd859c8 100644 --- a/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs +++ b/Source/NETworkManager/ViewModels/SNTPLookupViewModel.cs @@ -230,9 +230,7 @@ private Task Export() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs index f220a4e4f9..f36825f5c1 100644 --- a/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs +++ b/Source/NETworkManager/ViewModels/SubnetCalculatorSubnettingViewModel.cs @@ -173,9 +173,7 @@ private Task ExportAction() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs index 9ffc8afda0..f4429f0ac6 100644 --- a/Source/NETworkManager/ViewModels/TracerouteViewModel.cs +++ b/Source/NETworkManager/ViewModels/TracerouteViewModel.cs @@ -461,9 +461,7 @@ private Task Export() { // The rows shown in the grid (search / filter) in the order shown (sorting). Copied on the UI thread, // exported in the background - var results = instance.ExportAll - ? ResultsView.GetItemsInViewOrder() - : ResultsView.GetSelectedItemsInViewOrder(SelectedResults); + var results = ResultsView.GetItemsInViewOrder(instance.ExportAll, SelectedResults); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } diff --git a/Source/NETworkManager/ViewModels/WiFiViewModel.cs b/Source/NETworkManager/ViewModels/WiFiViewModel.cs index 4f8a1dbefa..2a8b5c8a47 100644 --- a/Source/NETworkManager/ViewModels/WiFiViewModel.cs +++ b/Source/NETworkManager/ViewModels/WiFiViewModel.cs @@ -1484,9 +1484,7 @@ private Task Export() { // The networks shown in the grid (band filter, search) in their order. Copied on the UI thread, exported // in the background - var networks = instance.ExportAll - ? NetworksView.GetItemsInViewOrder() - : NetworksView.GetSelectedItemsInViewOrder(SelectedNetworks); + var networks = NetworksView.GetItemsInViewOrder(instance.ExportAll, SelectedNetworks); await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, networks)); } From e0740a158d9d9e7de3df9b183c46380d43166956 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:17:03 +0100 Subject: [PATCH 35/44] Ping Monitor: export in the background (review #6) The history was added on the ping thread while the export copied it on the UI thread (List not thread-safe). It is updated in the dispatcher callback now (after the session check), the export copies it and writes the file in the background like the other tools. Co-Authored-By: Claude Opus 5.5 --- .../ViewModels/PingMonitorViewModel.cs | 14 ++++++++------ Website/docs/changelog/next-release.md | 1 + 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs index 93eee43dcf..62c2ca8833 100644 --- a/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs +++ b/Source/NETworkManager/ViewModels/PingMonitorViewModel.cs @@ -640,8 +640,10 @@ public Task Export() try { - ExportManager.Export(instance.FilePath, instance.FileType, - new ObservableCollection(_pingInfoList)); + // Copied on the UI thread (the history is updated there while pinging), exported in the background + var results = _pingInfoList.ToList(); + + await Task.Run(() => ExportManager.Export(instance.FilePath, instance.FileType, results)); } catch (Exception ex) { @@ -765,9 +767,12 @@ private void Ping_PingReceived(object sender, PingReceivedArgs e) 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 below and + // 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; @@ -779,9 +784,6 @@ private void Ping_PingReceived(object sender, PingReceivedArgs e) UpdateXAxisWindow(timeInfo.DateTime); UpdateYAxis(); }); - - // Add to history - _pingInfoList.Add(e.Args); } /// diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 700032204d..6ebc0cbef1 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -187,6 +187,7 @@ Release date: **xx.xx.2026** - IP addresses can be excluded with `!` in the host input (also in profiles and the run command), e.g. `10.0.0.0/24; !10.0.0.1; !10.0.0.200-254`: IP addresses, ranges, subnets and hostnames (nothing is scanned if an excluded hostname can't be resolved). [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) - The notification shows the tool in its header (icon and name), a click opens the **Ping Monitor**; down uses the red of the application. The message is a line with the IP address and the status in its color (e.g. `10.0.0.1 · Up`) like the notifications of the **IP Scanner** and the **Port Scanner** (was `Host is up`). [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) - **Play sound on status change** is off by default (the popup stays on); an existing setting is kept. [#3685](https://github.com/BornToBeRoot/NETworkManager/pull/3685) +- **Export...** writes the file in the background, so the window stays responsive with a long history. The history is only updated on the UI thread, so an export while pinging can no longer fail or miss results. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Traceroute** From 9bc4074c73aa8c974e189e3b07d9b88f2405985e Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:22:44 +0100 Subject: [PATCH 36/44] Fix: SNTP Lookup local time in the DST hour, socket of failed requests (final review #1, #2) DateTime.UtcNow instead of DateTime.Now.ToUniversalTime() (ambiguous in the repeated hour), UdpClient disposed also if Send / Receive throws. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager.Models/Network/SNTPLookup.cs | 10 +++++----- Website/docs/changelog/next-release.md | 1 + 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Source/NETworkManager.Models/Network/SNTPLookup.cs b/Source/NETworkManager.Models/Network/SNTPLookup.cs index 42b89480b6..8f45d83ff6 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookup.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookup.cs @@ -58,19 +58,19 @@ private static SNTPDateTime GetNetworkTimeRfc2030(IPEndPoint server, int timeout var ntpData = new byte[48]; // RFC 2030 ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) - var udpClient = new UdpClient(server.AddressFamily); + // Disposed also if the request fails (e.g. timeout) + using var udpClient = new UdpClient(server.AddressFamily); udpClient.Client.SendTimeout = timeout; udpClient.Client.ReceiveTimeout = timeout; udpClient.Connect(server); - var localStartTime = DateTime.Now.ToUniversalTime(); + // UtcNow: a local time is ambiguous in the hour repeated at the end of the daylight saving time + var localStartTime = DateTime.UtcNow; udpClient.Send(ntpData, ntpData.Length); ntpData = udpClient.Receive(ref server); - var localEndTime = DateTime.Now.ToUniversalTime(); - - udpClient.Close(); + var localEndTime = DateTime.UtcNow; var intPart = ((ulong)ntpData[40] << 24) | ((ulong)ntpData[41] << 16) | ((ulong)ntpData[42] << 8) | ntpData[43]; var fractionPart = ((ulong)ntpData[44] << 24) | ((ulong)ntpData[45] << 16) | ((ulong)ntpData[46] << 8) | diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 6ebc0cbef1..b9a4ec4e08 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -444,6 +444,7 @@ Release date: **xx.xx.2026** - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the SNTP server profiles in the settings. The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - Fixed the CSV export breaking the row with a decimal comma (e.g. German) in the offset and round trip delay, the values are exported with a decimal point now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - Fixed the offset being cut off to whole seconds and the round trip delay to whole milliseconds (e.g. an offset of 0.25 s was shown and exported as `0 s`). The offset is shown with millisecond precision, the round trip delay with 0.01 ms. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- Fixed a wrong offset of about one hour for a lookup in the hour that is repeated at the end of the daylight saving time, and the network connection of a failed request (e.g. timeout) not being closed. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **Hosts File Editor** From 94aa1a92a990ee0ae59d81c0a93809ca30b10e7e Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:23:22 +0100 Subject: [PATCH 37/44] SNTP Lookup: offset with the NTP sign (final review #3) Server time minus local time (positive if the local clock is behind), like NTP tools and the IP Scanner WindowsTimeOffset (host minus local). Documented in sntp-lookup.md, breaking change in the changelog. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager.Models/Network/SNTPDateTime.cs | 3 ++- Source/NETworkManager.Models/Network/SNTPLookup.cs | 8 ++++---- Website/docs/application/sntp-lookup.md | 2 ++ Website/docs/changelog/next-release.md | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Source/NETworkManager.Models/Network/SNTPDateTime.cs b/Source/NETworkManager.Models/Network/SNTPDateTime.cs index c95f97c39c..4c30beb210 100644 --- a/Source/NETworkManager.Models/Network/SNTPDateTime.cs +++ b/Source/NETworkManager.Models/Network/SNTPDateTime.cs @@ -35,7 +35,8 @@ public SNTPDateTime() public double RoundTripDelay { get; set; } /// - /// Offset to the local clock in seconds. + /// Offset of the local clock in seconds like NTP: network time minus local time (positive if the local clock is + /// behind). /// public double Offset { get; set; } } \ No newline at end of file diff --git a/Source/NETworkManager.Models/Network/SNTPLookup.cs b/Source/NETworkManager.Models/Network/SNTPLookup.cs index 8f45d83ff6..57c08e8e89 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookup.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookup.cs @@ -79,12 +79,12 @@ private static SNTPDateTime GetNetworkTimeRfc2030(IPEndPoint server, int timeout var milliseconds = intPart * 1000 + fractionPart * 1000 / 0x100000000L; var networkTime = new DateTime(1900, 1, 1).AddMilliseconds((long)milliseconds); - // Offset of the local clock (local time in the middle of the request minus the network time) in seconds and - // round trip delay in milliseconds - as double, so a part of a second / millisecond isn't cut off. The network - // time has a resolution of 1 ms + // Offset like NTP (network time minus the local time in the middle of the request, positive if the local clock is + // behind: the correction for the local clock) in seconds and round trip delay in milliseconds - as double, so a + // part of a second / millisecond isn't cut off. The network time has a resolution of 1 ms var roundTripDelayTicks = localEndTime.Ticks - localStartTime.Ticks; var offsetInSeconds = Math.Round( - (localStartTime.Ticks + roundTripDelayTicks / 2.0 - networkTime.Ticks) / TimeSpan.TicksPerSecond, 3); + (networkTime.Ticks - (localStartTime.Ticks + roundTripDelayTicks / 2.0)) / TimeSpan.TicksPerSecond, 3); return new SNTPDateTime { diff --git a/Website/docs/application/sntp-lookup.md b/Website/docs/application/sntp-lookup.md index 101a4db874..bd2ebf4b67 100644 --- a/Website/docs/application/sntp-lookup.md +++ b/Website/docs/application/sntp-lookup.md @@ -8,6 +8,8 @@ keywords: [NETworkManager, SNTP lookup, NTP, time server, time synchronization, With **SNTP Lookup** you can query one or more SNTP servers to get the current network time and view the offset to the local clock. +The **Offset** (seconds) is the time of the server minus the local time, like in NTP tools (e.g. `w32tm /stripchart`): positive if the local clock is behind, negative if it is ahead. The times are shown in UTC. + :::info SNTP (Simple Network Time Protocol) is a simplified version of NTP (Network Time Protocol) used for synchronizing clocks between devices on a network. It is designed for scenarios where precise timing is not critical. SNTP servers obtain their time from upstream NTP or SNTP servers and distribute it to clients. SNTP operates over UDP and uses port 123 by default. It is widely supported by operating systems and network devices. diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index b9a4ec4e08..a290b16c8c 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -27,7 +27,7 @@ Release date: **xx.xx.2026** - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns are `Timestamp`, `IPAddress`, `Hostname`, `Status`, `Time`, `TTL`, `Bytes` (status first, like the ping of the **IP Scanner**). [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) -- **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **SNTP Lookup**: the export contains `Offset` (seconds) and `RoundTripDelay` (milliseconds) as numbers with a decimal point (e.g. `-0.25`) instead of text with the unit (`-0.25 s`, `10.5 ms`), like in all exports. The **Offset** (also in the grid) uses the sign of NTP: time of the server minus the local time (positive if the local clock is behind), the opposite of before. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Firewall**: the columns of the export are in the order of the grid: `IsEnabled` first, the local and remote address before the port (`LocalAddresses`, `LocalPorts`, `RemoteAddresses`, `RemotePorts`), then `Program`, `InterfaceType`, `NetworkProfiles` and `Description`. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Discovery Protocol**: the columns of the export are in the order shown: `Management` and `ChassisId` (new) after `IPAddress`, `LocalConnection` and `LocalInterface` (new) at the end. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **IP Geolocation**: the columns of the export are in the order shown: `Query` (IP address) and `Reverse` after `Currency`, then the network (`Isp`, `Org`, `As`, `Asname`, `Hosting`, `Proxy`, `Mobile`), like the geolocation in the **Traceroute** export. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) From 8fdd766aabcc8bd8f202f8ee62e78029093d5953 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:23:57 +0100 Subject: [PATCH 38/44] Export: WiFi beacon interval / uptime as numbers (final review #6) BeaconInterval in ms, Uptime in whole seconds instead of time span text, like every other duration of the exports (FAQ: number in a fixed unit). Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.WiFiNetworkInfo.cs | 6 ++++-- Source/NETworkManager.Models/Export/ExportManager.cs | 3 ++- Website/docs/application/wifi.md | 2 +- Website/docs/changelog/next-release.md | 2 +- Website/docs/faq/export-format.md | 2 +- 5 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs index e6479bc651..771c016fb7 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs @@ -33,8 +33,10 @@ public static partial class ExportManager new(nameof(WiFiNetworkInfo.AvailableNetwork.PhyKind), x => x.AvailableNetwork.PhyKind), new(nameof(WiFiNetworkInfo.AvailableNetwork.NetworkKind), x => x.AvailableNetwork.NetworkKind), new(nameof(WiFiNetworkInfo.AvailableNetwork.IsWiFiDirect), x => x.AvailableNetwork.IsWiFiDirect), - new(nameof(WiFiNetworkInfo.AvailableNetwork.BeaconInterval), x => x.AvailableNetwork.BeaconInterval), - new(nameof(WiFiNetworkInfo.AvailableNetwork.Uptime), x => x.AvailableNetwork.Uptime), + // Durations as number like in the other exports: ms (e.g. 102.4) / whole seconds + new(nameof(WiFiNetworkInfo.AvailableNetwork.BeaconInterval), + x => x.AvailableNetwork.BeaconInterval.TotalMilliseconds), + new(nameof(WiFiNetworkInfo.AvailableNetwork.Uptime), x => (long)x.AvailableNetwork.Uptime.TotalSeconds), // Change since the previous scan of the same adapter (empty without a previous scan / change) new(nameof(WiFiNetworkInfo.Change), x => x.Change == WiFiNetworkChange.None ? null : x.Change) ]; diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index c98770626d..3b0e8f464f 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -29,7 +29,8 @@ namespace NETworkManager.Models.Export; /// s - the unit is documented). Bools as True / False (CSV), true / false (XML). /// JSON: numbers and bools as JSON numbers / bools, everything else as text. /// Date and time as shown in the tool (local time; SNTP Lookup: UTC) as yyyy-MM-dd HH:mm:ss.fff, -/// time span as [-][d.]hh:mm:ss[.fffffff]. +/// durations as numbers in a fixed unit (see above; a time span only as fallback: +/// [-][d.]hh:mm:ss[.fffffff]). /// Enums as their (English) name (e.g. Success, flags: ICMP, TCP). /// MAC addresses as AA:BB:CC:DD:EE:FF. /// Lists (e.g. IP addresses) as one text, separated by ; . diff --git a/Website/docs/application/wifi.md b/Website/docs/application/wifi.md index 0adfb649b6..6e960f4a64 100644 --- a/Website/docs/application/wifi.md +++ b/Website/docs/application/wifi.md @@ -108,7 +108,7 @@ The status of the connection (`Connecting to ...`, the result or the error) is s ### Export -**Export...** exports the networks as CSV, XML or JSON: **all** exports the networks shown (filtered by band and search) in the order shown, **selected** the selected networks in the order shown. Columns / elements in the order of the grid: `Ssid`, `IsConnected`, `Security`, `ChannelCenterFrequencyInKilohertz`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated`, `SignalBars`, `NetworkRssiInDecibelMilliwatts`, `NetworkAuthenticationType`, `NetworkEncryptionType`, `Bssid`, `Vendor`, `PhyKind`, `NetworkKind`, `IsWiFiDirect`, `BeaconInterval`, `Uptime` and `Change`, see [Export format](../faq/export-format.md). +**Export...** exports the networks as CSV, XML or JSON: **all** exports the networks shown (filtered by band and search) in the order shown, **selected** the selected networks in the order shown. Columns / elements in the order of the grid: `Ssid`, `IsConnected`, `Security`, `ChannelCenterFrequencyInKilohertz`, `Channel`, `ChannelWidth` (MHz), `ChannelWidthEstimated`, `SignalBars`, `NetworkRssiInDecibelMilliwatts`, `NetworkAuthenticationType`, `NetworkEncryptionType`, `Bssid`, `Vendor`, `PhyKind`, `NetworkKind`, `IsWiFiDirect`, `BeaconInterval` (ms), `Uptime` (s) and `Change`, see [Export format](../faq/export-format.md). ### Keyboard shortcuts diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index a290b16c8c..43b1028773 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -22,7 +22,7 @@ Release date: **xx.xx.2026** - Removed the **ThreadPool additional min. threads** setting (Settings > General) and the application-wide `ThreadPool.SetMinThreads` workaround it configured for the IP Scanner and Port Scanner. It's no longer needed now that both scan engines use non-blocking async concurrency instead of blocking calls. [#3564](https://github.com/BornToBeRoot/NETworkManager/pull/3564) - **Exports (CSV, XML, JSON)**: the exports of all tools now use the same format, see [Export format](../faq/export-format.md). Columns may have been reordered (like shown in the tool) or added, and values are formatted the same way in every tool (e.g. numbers without unit and with a decimal point, dates as `yyyy-MM-dd HH:mm:ss.fff`, MAC addresses as `AA:BB:CC:DD:EE:FF`, empty values instead of placeholders like `-/-`). If you process exports with scripts or other tools, check them after the update and read the columns by name instead of by position. The changes of each tool are listed below. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) -- **WiFi**: the columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **WiFi**: the export contains `BeaconInterval` (milliseconds, e.g. `102.4`) and `Uptime` (seconds) as numbers instead of text (`00:00:00.1024000`), like the durations of all exports. The columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns are `Timestamp`, `IPAddress`, `Hostname`, `Status`, `Time`, `TTL`, `Bytes` (status first, like the ping of the **IP Scanner**). [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) diff --git a/Website/docs/faq/export-format.md b/Website/docs/faq/export-format.md index c4283abf5b..28a0259f2c 100644 --- a/Website/docs/faq/export-format.md +++ b/Website/docs/faq/export-format.md @@ -27,7 +27,7 @@ The CSV columns, the XML elements and the JSON keys have the same names and orde | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Empty value | Empty in CSV, empty element in XML, `null` in JSON (e.g. the ping time without a reply) | | Number | Decimal point in every language (e.g. `10.5`), without a unit. JSON: number | -| Time / duration | Number in a fixed unit: ping time in milliseconds (e.g. `4`), SNTP **Offset** in seconds and **RoundTripDelay** in milliseconds, **Speed** of a network interface in bit/s | +| Time / duration | Number in a fixed unit: ping time in milliseconds (e.g. `4`), SNTP **Offset** in seconds and **RoundTripDelay** in milliseconds, WiFi **BeaconInterval** in milliseconds and **Uptime** in seconds, **Speed** of a network interface in bit/s | | Yes / No | `True` / `False` (CSV), `true` / `false` (XML, JSON) | | Date and time | `yyyy-MM-dd HH:mm:ss.fff` (e.g. `2026-11-08 10:15:30.123`) in the time shown in the tool: local time, **SNTP Lookup** in UTC | | Status, type, state | English name (e.g. `Success`, `TimedOut`, `Open`, `Tcp`), several values separated by `, ` (e.g. `ICMP, TCP`) | From e47628e17ab552b6a924c56b663f043c3f6c3fc5 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:24:58 +0100 Subject: [PATCH 39/44] Export: remove characters XML does not allow (final review #7) A control character (e.g. in SNMP data) made XDocument.Save throw, so the whole XML export failed. The XML writer removes invalid characters (valid surrogate pairs are kept), CSV / JSON are unchanged. Test added. Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.cs | 36 +++++++++++++++++-- .../Export/ExportManagerTests.cs | 10 ++++++ Website/docs/changelog/next-release.md | 1 + 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index 3b0e8f464f..7d79902d2d 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -8,6 +8,7 @@ using System.Numerics; using System.Text; using System.Xml.Linq; +using XmlConvert = System.Xml.XmlConvert; using NETworkManager.Utilities; using Newtonsoft.Json; @@ -224,11 +225,42 @@ private static IEnumerable ToXmlElements(string name, object value) } /// - /// Gets the value of a XML element: bools as XML bools (true / false), everything else as text. + /// Gets the value of a XML element: bools as XML bools (true / false), everything else as text + /// without the characters XML doesn't allow (e.g. control characters in SNMP data), which would fail the whole + /// export. /// private static object ToXmlValue(object value) { - return value is bool ? value : ToText(value); + return value is bool ? value : RemoveInvalidXmlChars(ToText(value)); + } + + /// + /// Removes the characters that are not allowed in XML 1.0 (e.g. 0x00, 0x1B, a single surrogate). + /// + /// Text to clean. + /// Text without invalid characters (the same instance if it has none). + private static string RemoveInvalidXmlChars(string text) + { + if (text == null || text.All(XmlConvert.IsXmlChar)) + return text; + + var stringBuilder = new StringBuilder(text.Length); + + for (var i = 0; i < text.Length; i++) + { + if (XmlConvert.IsXmlChar(text[i])) + { + stringBuilder.Append(text[i]); + } + else if (i + 1 < text.Length && XmlConvert.IsXmlSurrogatePair(text[i + 1], text[i])) + { + // Valid surrogate pair (e.g. an emoji) + stringBuilder.Append(text, i, 2); + i++; + } + } + + return stringBuilder.ToString(); } /// diff --git a/Source/NETworkManager.Tests/Export/ExportManagerTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerTests.cs index 6e1006bfe3..dc42ad4bf7 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerTests.cs @@ -93,6 +93,16 @@ public void NoItems_HeaderOnly() Assert.Empty(files.JsonItems); } + [Fact] + public void Xml_InvalidCharactersRemoved() + { + // Control characters (e.g. in SNMP data) are not allowed in XML 1.0 - the export must not fail + var files = ExportAll((f, t) => ExportManager.Export(f, t, [new OUIInfo("00:11:22", "Ven\0dor\u001B \U0001F600")])); + + Assert.Equal("Vendor \U0001F600", files.XmlValue("Vendor")); + Assert.Equal("Ven\0dor\u001B \U0001F600", (string)files.JsonValue("Vendor")); + } + [Fact] public void Txt_NotSupported() { diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 43b1028773..0f652f7908 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -438,6 +438,7 @@ Release date: **xx.xx.2026** - Fixed `Enter` in the search box of the OID profiles dialog closing the dialog with **OK**. It only filters the OID profiles now. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - Fixed columns that couldn't be made wider than the window (by dragging or double-clicking the gripper) in the result and the OID profiles (dialog, settings). The grid scrolls horizontally now, the last (or main) column still fills the remaining width. [#3557](https://github.com/BornToBeRoot/NETworkManager/issues/3557) - Fixed the CSV export breaking the row if the data contains a comma or a quote. The data is quoted now. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- Fixed the XML export failing (no file) if the data contains control characters that XML doesn't allow (e.g. binary `OctetString` values). These characters are removed in the XML file, CSV and JSON contain the data unchanged. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) **SNTP Lookup** From 8821636ca892592c5ba8e1c7d1fefe5882cc22c5 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:25:05 +0100 Subject: [PATCH 40/44] Docs: export format explains empty vs. empty text in the IP Scanner (final review #5) Co-Authored-By: Claude Opus 5.5 --- Website/docs/faq/export-format.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Website/docs/faq/export-format.md b/Website/docs/faq/export-format.md index 28a0259f2c..ace6bc5a21 100644 --- a/Website/docs/faq/export-format.md +++ b/Website/docs/faq/export-format.md @@ -34,6 +34,8 @@ The CSV columns, the XML elements and the JSON keys have the same names and orde | MAC address | `AA:BB:CC:DD:EE:FF` | | List (e.g. IP addresses) | One value, separated by `; ` (e.g. `10.0.0.53; 10.0.0.54`) | +**IP Scanner**: an empty value (`null` in JSON) means the value is not available - the probe is disabled or was still running (e.g. export during a scan). An empty text (`""` in JSON) means the probe ran, but the host had no value (e.g. **Windows** values of a host without Windows host information, **SNMPError** without an error). **Ports** is an empty array in JSON if no port was found or the port scan is disabled (see **PortStatus**). + In the CSV file, text that may contain a comma (e.g. hostname, description, comment) is always enclosed in quotes (`"`), any other value only if it contains a comma, a quote or a line break. A quote in a value is doubled (`""`), as defined in [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180), e.g. for `Import-Csv` in PowerShell. The ports of a host in the **IP Scanner** export are one value in the CSV file (`Port/Protocol/Service/Description/State`, ports separated by `;`), one `PortInfo` element per port in the XML file and an array of objects in the JSON file. From 3f8bbd0d2ba4dad1c4bc75f265277701299ad07a Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:35:54 +0100 Subject: [PATCH 41/44] Export: CSV ports parseable, empty values unquoted, streamed (review 3 #1, #2, #7) - IP Scanner CSV Ports: Port/Protocol/State (service / description are free text with / and ;), ExportList gets its CSV fields; JSON / XML keep all fields - An empty value stays empty in a quoted CSV column, an empty text is "", like null / "" in JSON - CSV written line by line with a StreamWriter - FAQ: CSV formula warning (values are exported as they are) Co-Authored-By: Claude Opus 5.5 --- .../Export/ExportManager.IPScannerHostInfo.cs | 16 ++++-- .../Export/ExportManager.cs | 54 +++++++++++++------ .../Export/ExportManagerIPScannerTests.cs | 4 +- .../Export/ExportManagerTests.cs | 13 +++++ Website/docs/changelog/next-release.md | 2 +- Website/docs/faq/export-format.md | 10 +++- 6 files changed, 77 insertions(+), 22 deletions(-) diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs index 8e1291457f..67573650d7 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs @@ -37,12 +37,21 @@ public static void Export(string filePath, ExportFileType fileType, new(nameof(PortInfo.State), x => x.State) ]; + /// + /// Exported fields of a in the CSV file: without service and description (free text, may + /// contain / or ;), so the value can be split again (e.g. 80/Tcp/Open; 443/Tcp/Closed). + /// + private static readonly ExportField[] PortInfoCsvExportFields = + [ + PortInfoExportFields[0], PortInfoExportFields[1], PortInfoExportFields[4] + ]; + /// /// Gets the exported fields of an , grouped by topic (host, ping, ports, NetBIOS, /// web page, SNMP, Windows, change since the previous scan). Values of a probe that is still running /// (export during a scan, or a scan canceled before the probe finished) or disabled are placeholders - exported - /// as empty values instead of a result. The ports are an (joined in the CSV - /// file, one element per port in XML, an array in JSON). + /// as empty values instead of a result. The ports are an (port / protocol / + /// state joined in the CSV file, one element per port in XML, an array in JSON). /// /// Options of the scan the hosts are from. /// Fields in the order of the columns. @@ -93,7 +102,8 @@ Func IfWindowsValue(Func val // Port scan new("PortStatus", x => GetPortStatus(x, options)), new(nameof(IPScannerHostInfo.Ports), x => new ExportList(nameof(PortInfo), - x.Ports != null && options.PortScanEnabled ? x.Ports : [], PortInfoExportFields), true), + x.Ports != null && options.PortScanEnabled ? x.Ports : [], PortInfoExportFields, + PortInfoCsvExportFields), true), // NetBIOS new("NetBIOSIsReachable", IfNetBIOS(x => x.IsReachable)), new("NetBIOSIPAddress", IfNetBIOS(x => x.IPAddress)), diff --git a/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs index 7d79902d2d..32f7489ad8 100644 --- a/Source/NETworkManager.Models/Export/ExportManager.cs +++ b/Source/NETworkManager.Models/Export/ExportManager.cs @@ -99,23 +99,32 @@ private sealed record ExportField(string Name, Func GetValue, bool /// /// Value with a list of objects that have fields of their own (e.g. the ports of a host): in the CSV file the - /// values of an item are separated by / and the items by ;, in the XML file every item is an - /// element (), in the JSON file an array of objects. + /// values of the of an item are separated by / and the items by ; + /// (only fields without free text, so the value can be split again), in the XML file every item is an element + /// () with all fields, in the JSON file an array of objects with all fields. /// /// Type of the items. /// Name of the XML element of an item. /// Items to export. - /// Exported fields of an item. + /// Exported fields of an item (XML, JSON). + /// Exported fields of an item in the CSV file (without free text). private sealed record ExportList( string ItemName, IEnumerable Items, - IReadOnlyList> Fields) : IExportList + IReadOnlyList> Fields, + IReadOnlyList> CsvFields) : IExportList { /// public IEnumerable> GetItems() { return Items.Select(item => Fields.Select(field => (field.Name, field.GetValue(item)))); } + + /// + public IEnumerable> GetCsvItems() + { + return Items.Select(item => CsvFields.Select(field => field.GetValue(item))); + } } /// @@ -132,6 +141,12 @@ private interface IExportList /// Gets the names and values of the fields of every item. /// IEnumerable> GetItems(); + + /// + /// Gets the values of the CSV fields of every item (values without free text, so the joined value can be + /// split again). + /// + IEnumerable> GetCsvItems(); } #endregion @@ -172,23 +187,32 @@ private static void Export(string filePath, ExportFileType fileType, IEnumera /// private static void CreateCsv(string filePath, IEnumerable collection, IReadOnlyList> fields) { - var stringBuilder = new StringBuilder(); + // Written line by line (a large result isn't kept in memory as one string), UTF-8 without BOM + using var writer = new StreamWriter(filePath); - stringBuilder.AppendLine(string.Join(",", fields.Select(field => field.Name))); + writer.WriteLine(string.Join(",", fields.Select(field => field.Name))); foreach (var info in collection) - stringBuilder.AppendLine(string.Join(",", fields.Select(field => - { - var fieldValue = field.GetValue(info); + writer.WriteLine(string.Join(",", fields.Select(field => ToCsvValue(field, field.GetValue(info))))); + } - var value = fieldValue is IExportList list - ? string.Join(";", list.GetItems().Select(item => string.Join("/", item.Select(x => ToText(x.Value))))) - : ToText(fieldValue); + /// + /// Formats a value for the CSV file. An empty value (null, also a list without items) stays empty - also + /// in a quoted column, so it differs from an empty text (""), like null and "" in JSON. + /// + private static string ToCsvValue(ExportField field, object fieldValue) + { + var value = fieldValue is IExportList list + ? string.Join(ListSeparator, + list.GetCsvItems().Select(item => string.Join("/", item.Select(ToText)))) is { Length: > 0 } items + ? items + : null + : ToText(fieldValue); - return field.IsQuoted || IsQuoteRequired(value) ? CsvHelper.QuoteString(value) : value; - }))); + if (value == null) + return string.Empty; - File.WriteAllText(filePath, stringBuilder.ToString()); + return field.IsQuoted || IsQuoteRequired(value) ? CsvHelper.QuoteString(value) : value; } /// diff --git a/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs index b0b83d79f7..f19c177ad8 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerIPScannerTests.cs @@ -226,7 +226,8 @@ public void Ports_AllFormats() var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateHostWithPorts()], AllEnabled)); Assert.Equal(CsvHeader.Split(',').Length, files.CsvRows[0].Count); - Assert.Equal("80/Tcp/http/World Wide Web, HTTP/Open;443/Tcp/https/TLS/Closed", files.CsvValue("Ports")); + // CSV: port / protocol / state only (service and description are free text with "/" or ";") + Assert.Equal("80/Tcp/Open; 443/Tcp/Closed", files.CsvValue("Ports")); // XML: one element per port (no element for the list) var ports = files.XmlItems[0].Elements(nameof(PortInfo)).ToList(); @@ -251,6 +252,7 @@ public void Ports_PortScanDisabled_Empty() var files = ExportAll((f, t) => ExportManager.Export(f, t, [CreateHostWithPorts()], options)); Assert.Equal("", files.CsvValue("Ports")); + Assert.DoesNotContain("\"\"", files.CsvLines[1].Split(',')[CsvHeader.Split(',').ToList().IndexOf("Ports")]); Assert.Equal("", files.CsvValue("PortStatus")); Assert.Empty(files.XmlItems[0].Elements(nameof(PortInfo))); Assert.Empty((JArray)files.JsonValue("Ports")); diff --git a/Source/NETworkManager.Tests/Export/ExportManagerTests.cs b/Source/NETworkManager.Tests/Export/ExportManagerTests.cs index dc42ad4bf7..dc9122b5c1 100644 --- a/Source/NETworkManager.Tests/Export/ExportManagerTests.cs +++ b/Source/NETworkManager.Tests/Export/ExportManagerTests.cs @@ -60,6 +60,19 @@ public void Empty_IsEmpty() Assert.Equal(JTokenType.Null, files.JsonValue("Vendor").Type); } + [Fact] + public void Csv_EmptyValueVsEmptyText() + { + // Empty value: empty (also in a quoted column), empty text: "" - like null and "" in JSON + var files = ExportAll((f, t) => ExportManager.Export(f, t, + [new OUIInfo("00:11:22", null), new OUIInfo("00:11:23", "")])); + + Assert.Equal("00:11:22,", files.CsvLines[1]); + Assert.Equal("00:11:23,\"\"", files.CsvLines[2]); + Assert.Equal(JTokenType.Null, files.JsonItems[0]["Vendor"]!.Type); + Assert.Equal("", (string)files.JsonItems[1]["Vendor"]); + } + [Fact] public void Json_NumberAsNumber_EnumAsText() { diff --git a/Website/docs/changelog/next-release.md b/Website/docs/changelog/next-release.md index 0f652f7908..34f264e4ff 100644 --- a/Website/docs/changelog/next-release.md +++ b/Website/docs/changelog/next-release.md @@ -23,7 +23,7 @@ Release date: **xx.xx.2026** - **Exports (CSV, XML, JSON)**: the exports of all tools now use the same format, see [Export format](../faq/export-format.md). Columns may have been reordered (like shown in the tool) or added, and values are formatted the same way in every tool (e.g. numbers without unit and with a decimal point, dates as `yyyy-MM-dd HH:mm:ss.fff`, MAC addresses as `AA:BB:CC:DD:EE:FF`, empty values instead of placeholders like `-/-`). If you process exports with scripts or other tools, check them after the update and read the columns by name instead of by position. The changes of each tool are listed below. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Network Interface**: the export contains the MAC address (`PhysicalAddress`) as `AA:BB:CC:DD:EE:FF` instead of `AABBCCDDEEFF`, the DHCP lease (`DhcpLeaseObtained`, `DhcpLeaseExpires`) as `2026-11-08 10:15:30.123` in every format and language (empty without DHCP), and lists of IP addresses separated by `; ` instead of `;`, like in all exports. The IPv6 link-local address comes before the IPv6 address, like in the details. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **WiFi**: the export contains `BeaconInterval` (milliseconds, e.g. `102.4`) and `Uptime` (seconds) as numbers instead of text (`00:00:00.1024000`), like the durations of all exports. The columns of the export are in the order of the grid (SSID, connected, security, frequency, channel, channel width, signal, authentication, encryption, BSSID, vendor, ...) instead of the BSSID first and the values shown in the grid at the end. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) -- **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) +- **IP Scanner**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns of the export are grouped by topic instead of new columns being appended at the end: host (`IsReachable`, `DetectedBy`, `IPAddress`, hostnames, MAC address, vendor, role, OS), ping, port scan, NetBIOS, web page, SNMP, Windows host information and the change since the last scan. The ports in the CSV export contain port, protocol and state (`80/Tcp/Open; 443/Tcp/Closed`) instead of also service and description, which can contain `/` and `;` (JSON / XML unchanged). [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Port Scanner**: the JSON export uses the key `State` for the port state (like CSV and XML) instead of `Status`. Scripts that read `Status` have to be adjusted. [#3660](https://github.com/BornToBeRoot/NETworkManager/pull/3660) - **Ping Monitor**: the export contains the ping time (`Time`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`, `-/-`). `Time`, `TTL` and `Bytes` are empty without a reply instead of `-/-` / `0`, like in all exports. The columns are `Timestamp`, `IPAddress`, `Hostname`, `Status`, `Time`, `TTL`, `Bytes` (status first, like the ping of the **IP Scanner**). [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) - **Traceroute**: the export contains the times (`Time1` - `Time3`) as a number of milliseconds (e.g. `4`) instead of text (`4 ms`), empty without a reply instead of `-/-`, like in all exports. [#3696](https://github.com/BornToBeRoot/NETworkManager/pull/3696) diff --git a/Website/docs/faq/export-format.md b/Website/docs/faq/export-format.md index ace6bc5a21..49917f04e8 100644 --- a/Website/docs/faq/export-format.md +++ b/Website/docs/faq/export-format.md @@ -25,7 +25,7 @@ The CSV columns, the XML elements and the JSON keys have the same names and orde | Value | Format | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Empty value | Empty in CSV, empty element in XML, `null` in JSON (e.g. the ping time without a reply) | +| Empty value | Empty in CSV (also in a column with quotes), empty element in XML, `null` in JSON (e.g. the ping time without a reply). An empty text is `""` in CSV and JSON | | Number | Decimal point in every language (e.g. `10.5`), without a unit. JSON: number | | Time / duration | Number in a fixed unit: ping time in milliseconds (e.g. `4`), SNTP **Offset** in seconds and **RoundTripDelay** in milliseconds, WiFi **BeaconInterval** in milliseconds and **Uptime** in seconds, **Speed** of a network interface in bit/s | | Yes / No | `True` / `False` (CSV), `true` / `false` (XML, JSON) | @@ -38,4 +38,10 @@ The CSV columns, the XML elements and the JSON keys have the same names and orde In the CSV file, text that may contain a comma (e.g. hostname, description, comment) is always enclosed in quotes (`"`), any other value only if it contains a comma, a quote or a line break. A quote in a value is doubled (`""`), as defined in [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180), e.g. for `Import-Csv` in PowerShell. -The ports of a host in the **IP Scanner** export are one value in the CSV file (`Port/Protocol/Service/Description/State`, ports separated by `;`), one `PortInfo` element per port in the XML file and an array of objects in the JSON file. +:::warning + +Values are exported as they are, also text from the network (e.g. a web page title or an SNMP description). A value that starts with `=`, `+`, `-` or `@` may be run as a formula when the CSV file is opened in a spreadsheet application like Excel - open exports of networks you don't trust as text, or use the JSON / XML export. + +::: + +The ports of a host in the **IP Scanner** export are one value in the CSV file with port, protocol and state (`Port/Protocol/State`, ports separated by `; `, e.g. `80/Tcp/Open; 443/Tcp/Closed`), one `PortInfo` element per port in the XML file and an array of objects in the JSON file - both also with the service and description. From 46d4f0d5cadc8385810001f8d19c812e4a6fb4f2 Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:36:41 +0100 Subject: [PATCH 42/44] SNTP Lookup: no "-0" offset (review 3 #3) A tiny negative offset rounded to 0 was shown / exported as -0. Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager.Models/Network/SNTPLookup.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Source/NETworkManager.Models/Network/SNTPLookup.cs b/Source/NETworkManager.Models/Network/SNTPLookup.cs index 57c08e8e89..d42ffc4dce 100644 --- a/Source/NETworkManager.Models/Network/SNTPLookup.cs +++ b/Source/NETworkManager.Models/Network/SNTPLookup.cs @@ -84,7 +84,8 @@ private static SNTPDateTime GetNetworkTimeRfc2030(IPEndPoint server, int timeout // part of a second / millisecond isn't cut off. The network time has a resolution of 1 ms var roundTripDelayTicks = localEndTime.Ticks - localStartTime.Ticks; var offsetInSeconds = Math.Round( - (networkTime.Ticks - (localStartTime.Ticks + roundTripDelayTicks / 2.0)) / TimeSpan.TicksPerSecond, 3); + (networkTime.Ticks - (localStartTime.Ticks + roundTripDelayTicks / 2.0)) / TimeSpan.TicksPerSecond, 3) + + 0.0; // + 0.0: no "-0" if a tiny negative offset is rounded to 0 return new SNTPDateTime { From 069e0222d0cf7f5036fc506610153d99c7a8491c Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:36:41 +0100 Subject: [PATCH 43/44] Grid order: selected items by reference (review 3 #4) Two equal items (e.g. records) are still two rows; only the selected one is returned. Test added (Windows only). Co-Authored-By: Claude Opus 5.5 --- .../CollectionViewExtensionsTests.cs | 21 +++++++++++++++++++ .../CollectionViewExtensions.cs | 5 +++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs b/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs index fa46f7d760..3480b6fd9f 100644 --- a/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs +++ b/Source/NETworkManager.Tests/Utilities/CollectionViewExtensionsTests.cs @@ -73,6 +73,27 @@ public void GetItemsInViewOrder_AllOrSelected() Assert.Equal([1, 3, 4], GetItemsAllOrSelected(false, [5, 4, 1, 3])); } + [Fact] + public void GetSelectedItemsInViewOrder_EqualItems_OnlySelectedOne() + { + SkipUnlessWindows(); + + // Two equal records: only the selected instance is returned (by reference, not by value) + Assert.Equal(1, GetSelectedOfTwoEqualItems()); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int GetSelectedOfTwoEqualItems() + { + var first = new Item("a", 1); + var second = new Item("a", 1); + var view = new ListCollectionView(new List { first, second }); + + var selected = view.GetSelectedItemsInViewOrder(new List { second }); + + return selected.Count(x => ReferenceEquals(x, second)) == 1 && selected.Count == 1 ? 1 : 0; + } + [MethodImpl(MethodImplOptions.NoInlining)] private static List GetItemsAllOrSelected(bool all, int[] selectedValues) { diff --git a/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs b/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs index e4e34d93d3..da33b96981 100644 --- a/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs +++ b/Source/NETworkManager.Utilities.WPF/CollectionViewExtensions.cs @@ -35,9 +35,10 @@ public static List GetItemsInViewOrder(this ICollectionView view) /// Selected items in the order shown, without items that are not shown (e.g. filtered). public static List GetSelectedItemsInViewOrder(this ICollectionView view, IEnumerable selectedItems) { - var selected = new HashSet(selectedItems.Cast()); + // By reference: two equal items (e.g. records) are still two rows, only the selected one is returned + var selected = new HashSet(selectedItems.Cast(), ReferenceEqualityComparer.Instance); - return view.GetItemsInViewOrder().Where(selected.Contains).ToList(); + return view.GetItemsInViewOrder().Where(item => selected.Contains(item)).ToList(); } /// From b5b5474eb1bdf482f323e70575dd6c1c14056ebf Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:36:41 +0100 Subject: [PATCH 44/44] Remove unused usings (review 3 #8) Co-Authored-By: Claude Opus 5.5 --- Source/NETworkManager/ViewModels/FirewallViewModel.cs | 1 - Source/NETworkManager/ViewModels/WiFiViewModel.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/Source/NETworkManager/ViewModels/FirewallViewModel.cs b/Source/NETworkManager/ViewModels/FirewallViewModel.cs index 9871c8dd08..1950914afa 100644 --- a/Source/NETworkManager/ViewModels/FirewallViewModel.cs +++ b/Source/NETworkManager/ViewModels/FirewallViewModel.cs @@ -14,7 +14,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; diff --git a/Source/NETworkManager/ViewModels/WiFiViewModel.cs b/Source/NETworkManager/ViewModels/WiFiViewModel.cs index 2a8b5c8a47..949ca1cf9b 100644 --- a/Source/NETworkManager/ViewModels/WiFiViewModel.cs +++ b/Source/NETworkManager/ViewModels/WiFiViewModel.cs @@ -21,7 +21,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks;