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/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.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.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.DiscoveryProtocolPackageInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs
index 9e58a7f136..3946074658 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.DiscoveryProtocolPackageInfo.cs
@@ -1,16 +1,30 @@
-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
{
+ ///
+ /// Exported fields of a in the order shown.
+ ///
+ 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.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)
+ ];
+
///
/// Method to export objects from type to a file.
///
@@ -20,93 +34,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.Models/Export/ExportManager.FirewallRule.cs b/Source/NETworkManager.Models/Export/ExportManager.FirewallRule.cs
index a38710469e..daf8abe184 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 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.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.LocalAddresses), x => x.LocalAddressesDisplay, true),
+ new(nameof(FirewallRule.LocalPorts), x => x.LocalPortsDisplay, true),
+ new(nameof(FirewallRule.RemoteAddresses), x => x.RemoteAddressesDisplay, 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)
+ ];
+
///
/// 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..5e6e949338 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.IPGeolocationInfo.cs
@@ -1,139 +1,52 @@
-using System;
using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Xml.Linq;
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 in the order shown: location, time zone and currency,
+ /// IP address, network (same order as the geolocation 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(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),
+ // 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.Hosting), x => x.Hosting),
+ new(nameof(IPGeolocationInfo.Proxy), x => x.Proxy),
+ new(nameof(IPGeolocationInfo.Mobile), x => x.Mobile)
+ ];
///
- /// 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.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.IPScannerHostInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs
index 7c938be4df..67573650d7 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs
@@ -1,14 +1,7 @@
-using System;
+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;
@@ -27,236 +20,141 @@ public static partial class ExportManager
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);
- }
+ // Skip if critical data is null
+ Export(filePath, fileType, collection.Where(info => info?.PingInfo != null),
+ GetIPScannerHostInfoExportFields(options), ApplicationName.IPScanner);
}
///
- /// Value of an exported column (CSV) / element (XML, JSON key), see .
+ /// Exported fields of a (ports of a host, 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);
+ 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 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).
+ /// 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).
///
- /// 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)
+ 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 (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.
+ private static ExportField[] GetIPScannerHostInfoExportFields(IPScannerResultOptions options)
{
- var ping = GetPingInfo(info, options);
- var netBIOSInfo = GetNetBIOSInfo(info, options);
- var certificate = GetWebCertificate(info, options);
+ var isWebPageRead = IsWebPageRead(options);
- // Windows host information: null (empty values) if disabled, "" if the host had none
- var windows = options.WindowsEnabled ? info.Windows : null;
+ Func IfEnabled(bool isEnabled, Func value) =>
+ info => isEnabled ? value(info) : null;
- string IfEnabled(bool isEnabled, string value) => isEnabled ? value : 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;
- string IfWindows(Func value) =>
- options.WindowsEnabled ? windows == null ? string.Empty : value(windows) ?? string.Empty : 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
- object IfWindowsValue(Func value) => windows == null ? null : value(windows);
+ Func IfWindowsValue(Func value) => info =>
+ options.WindowsEnabled && info.Windows != null ? value(info.Windows) : null;
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
+ // 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,
+ PortInfoCsvExportFields), 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, info.HasSNMPError ? info.SNMPError.ToString() : string.Empty), true),
- // Windows host information (SMB / NTLM, NetApi)
+ 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),
- // 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("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)
];
}
- ///
- /// 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.
///
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.Models/Export/ExportManager.NetworkInterface.cs b/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs
index 6b28e6b4f9..542c118629 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.NetworkInterface.cs
@@ -1,146 +1,63 @@
-using System;
+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 in the order of the details: interface, IPv4 (incl.
+ /// DHCP), IPv6, DNS.
///
- /// 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.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),
+ 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.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)
+ ];
///
- /// 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.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.PingInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs
index be2027702a..9a7a55ca35 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.PingInfo.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.PingInfo.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 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 (status, time, TTL, bytes like the ping of the IP Scanner). Time
+ /// (ms), TTL and bytes 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.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.Bytes), x => HasPingReply(x.Status) ? x.Bytes : null)
+ ];
///
- /// 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.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.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.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.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.Models/Export/ExportManager.TracerouteHopInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs
index d02e220bcc..dc229e6970 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.TracerouteHopInfo.cs
@@ -1,17 +1,42 @@
-using System;
+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)),
+ 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),
+ 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 +46,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.Models/Export/ExportManager.WiFiNetworkInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs
index d33a86bf35..771c016fb7 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.WiFiNetworkInfo.cs
@@ -1,62 +1,44 @@
-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.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 in the order of the grid: network, security, channel,
+ /// signal, access point, other values of the network and the change since the previous scan.
///
- /// 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),
+ 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.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.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),
+ // 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.ToString())
+ new(nameof(WiFiNetworkInfo.Change), x => x.Change == WiFiNetworkChange.None ? null : x.Change)
];
///
@@ -67,81 +49,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/Source/NETworkManager.Models/Export/ExportManager.cs b/Source/NETworkManager.Models/Export/ExportManager.cs
index d502f50509..32f7489ad8 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.cs
@@ -1,11 +1,44 @@
-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 XmlConvert = System.Xml.XmlConvert;
+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. 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).
+/// 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,
+/// 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 ; .
+/// 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 +47,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 +82,309 @@ 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 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 (XML, JSON).
+ /// Exported fields of an item in the CSV file (without free text).
+ private sealed record ExportList(
+ string ItemName,
+ IEnumerable Items,
+ 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)));
+ }
+ }
+
+ ///
+ /// 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();
+
+ ///
+ /// 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
+
+ #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)
+ {
+ // 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);
+
+ writer.WriteLine(string.Join(",", fields.Select(field => field.Name)));
+
+ foreach (var info in collection)
+ writer.WriteLine(string.Join(",", fields.Select(field => ToCsvValue(field, field.GetValue(info)))));
+ }
+
+ ///
+ /// 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);
+
+ if (value == null)
+ return string.Empty;
+
+ return field.IsQuoted || IsQuoteRequired(value) ? CsvHelper.QuoteString(value) : value;
+ }
+
+ ///
+ /// 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
+ /// 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 : 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();
+ }
+
+ ///
+ /// 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),
+ // Empty list: empty value
+ IEnumerable list => list.Cast