refactor: change deserialization procedure in DeserializeXml to use Xml.Linq

This commit is contained in:
cuqmbr 2022-08-15 14:44:44 +03:00
parent f11b17746a
commit 573299ed48
4 changed files with 102 additions and 1194 deletions

View File

@ -9,6 +9,57 @@ public static class CliOptionsHandlers
public static void UniversalHandler(FileInfo? inputFile,
FileInfo? outputFile, bool useDatabase, string? sqlQuery)
{
// Validate input file
if (inputFile != null)
{
if (!inputFile.Exists)
{
Console.WriteLine("Input file doesn't exist.");
return;
}
}
// Validate output file
if (outputFile != null)
{
if (!Directory.Exists(outputFile.DirectoryName))
{
Console.WriteLine("Output directory doesn't exist.");
return;
}
// If output file with the same name already exists
// prompt user to change a name of the file
while (outputFile.Exists)
{
Console.Write("Output file already exists. Do you want to overwrite it? [y/N] ");
var opt = Console.ReadLine();
if (String.IsNullOrEmpty(opt) || opt.ToLower() == "no" ||
opt.ToLower() == "n")
{
Console.Write("Enter a <new_name>[.kml]: ");
var name = Console.ReadLine();
if (String.IsNullOrEmpty(name))
{
continue;
}
outputFile = new FileInfo(
Path.Join(outputFile.DirectoryName, name));
continue;
}
if (opt.ToLower() == "yes" ||
opt.ToLower() == "y")
{
break;
}
}
}
// Run some logic based on options combination
if (inputFile != null && outputFile != null)
{
var wirelessNetworks = Helpers.DeserializeXml(inputFile);
@ -58,6 +109,11 @@ public static class CliOptionsHandlers
using var dbContext = new DatabaseContext();
Console.WriteLine(dbContext.Database.ExecuteSqlRaw(sqlQuery));
}
else
{
Console.WriteLine("Options combination is unsupported or some option lacks an argument." +
"\nUse --help to see use case examples.");
}
}
private static string GetKmlString(IEnumerable<WirelessNetwork> wirelessNetworks)

View File

@ -1,5 +1,4 @@
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Linq;
using netxml2kml.Models;
namespace netxml2kml.Methods;
@ -9,61 +8,53 @@ public static class Helpers
public static WirelessNetwork[] DeserializeXml(FileInfo inputFile)
{
/* Deserialize to MonoXSD autogenerated class model */
var xmlSerializer = new XmlSerializer(typeof(detectionrun));
var detectionRun = (detectionrun?) xmlSerializer.Deserialize(
XmlReader.Create(inputFile.OpenRead(),
new XmlReaderSettings {DtdProcessing = DtdProcessing.Parse}));
/* Convert machine deserialization to readable class format */
var srcTree = XDocument.Load(inputFile.OpenRead());
var srcNets = srcTree.Root!.Elements("wireless-network")
.Where(wn => wn.Attribute("type")!.Value != "probe").ToList();
var wirelessNetworks =
new WirelessNetwork[detectionRun!.wirelessnetwork.Count(wn =>
wn.type != "probe")];
var wirelessNetworks = new WirelessNetwork[srcNets.Count];
for (int i = 0; i < detectionRun.wirelessnetwork.Length; i++)
for (int i = 0; i < srcNets.Count; i++)
{
var detectionRunWirelessNetwork = detectionRun.wirelessnetwork[i];
Console.WriteLine(i);
var srcNet = srcNets[i];
// If wireless network is a client skip
if (detectionRunWirelessNetwork.type == "probe")
{
continue;
}
var essid = srcNet.Element("SSID")!.Element("essid")!.Value;
wirelessNetworks[i] = new()
{
Essid = detectionRunWirelessNetwork.SSID.First().essid?.First().Value,
Encryption = detectionRunWirelessNetwork.SSID.First().encryption?.Last()?.Value,
Bssid = detectionRunWirelessNetwork.BSSID,
Manufacturer = detectionRunWirelessNetwork.manuf,
FrequencyMhz = Math.Round(Double.Parse(detectionRunWirelessNetwork.freqmhz.Substring(0, 2)) / 10, 1, MidpointRounding.ToPositiveInfinity),
MaxSignalDbm = Int32.Parse(detectionRunWirelessNetwork.snrinfo.First().max_signal_dbm),
MaxLatitude = Double.Parse(detectionRunWirelessNetwork.gpsinfo.First().maxlat),
MaxLongitude = Double.Parse(detectionRunWirelessNetwork.gpsinfo.First().maxlon),
MaxAltitude = Double.Parse(detectionRunWirelessNetwork.gpsinfo.First().maxalt),
FirstSeenDate = StringToDate(detectionRunWirelessNetwork.firsttime),
LastUpdateDate = StringToDate(detectionRunWirelessNetwork.lasttime)
Essid = essid != "" ? essid : null,
Encryption = srcNet.Element("SSID")!.Elements("encryption").LastOrDefault()?.Value,
Bssid = srcNet.Element("BSSID")!.Value,
Manufacturer = srcNet.Element("manuf")!.Value,
FrequencyMhz = Math.Round(Double.Parse(srcNet.Element("freqmhz")!.Value.Substring(0, 2)) / 10, 1, MidpointRounding.ToPositiveInfinity),
MaxSignalDbm = Int32.Parse(srcNet.Element("snr-info")!.Element("max_signal_dbm")!.Value),
MaxLatitude = Double.Parse(srcNet.Element("gps-info")!.Element("max-lat")!.Value),
MaxLongitude = Double.Parse(srcNet.Element("gps-info")!.Element("max-lon")!.Value),
MaxAltitude = Double.Parse(srcNet.Element("gps-info")!.Element("max-alt")!.Value),
FirstSeenDate = StringToDate(srcNet.Attribute("first-time")!.Value),
LastUpdateDate = StringToDate(srcNet.Attribute("last-time")!.Value)
};
// If wireless network has no clients continue
if (detectionRunWirelessNetwork.wirelessclient == null)
if (!srcNet.Elements("wireless-client").Any())
{
continue;
}
var wirelessConnections = new List<WirelessConnection>(detectionRunWirelessNetwork.wirelessclient.Length);
var wirelessConnections = new List<WirelessConnection>(srcNet.Elements("wireless-client").Count());
foreach (var wc in detectionRunWirelessNetwork.wirelessclient)
foreach (var wc in srcNet.Elements("wireless-client").ToArray())
{
wirelessConnections.Add(new WirelessConnection
{
WirelessClient = new WirelessClient
{
Mac = wc.clientmac,
Manufacturer = wc.clientmanuf,
FirstSeenDate = StringToDate(wc.firsttime),
LastUpdateDate = StringToDate(wc.lasttime)
Mac = wc.Element("client-mac")!.Value,
Manufacturer = wc.Element("client-manuf")!.Value,
FirstSeenDate = StringToDate(wc.Attribute("first-time")!.Value),
LastUpdateDate = StringToDate(wc.Attribute("last-time")!.Value)
},
WirelessNetwork = wirelessNetworks[i]
});
@ -72,7 +63,7 @@ public static class Helpers
wirelessNetworks[i].WirelessConnections = wirelessConnections;
}
return wirelessNetworks;
return wirelessNetworks.ToArray();
}
public static DateTime StringToDate(string dateString)

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
using System.CommandLine;
using System.CommandLine;
using netxml2kml.Methods;
namespace netxml2kml;
@ -8,22 +8,34 @@ class Program
static async Task<int> Main(string[] args)
{
// Define CLI parser options, commands & handlers
var inputOption = new Option<FileInfo?>(
aliases: new[] {"-i", "--input"},
description: "Path to the file to be converted.");
description: "Path to the file to be converted.")
{
Arity = ArgumentArity.ZeroOrOne
};
var outputOption = new Option<FileInfo?>(
aliases: new[] {"-o", "--output"},
description: "The name of the file to be created.");
description: "The name of the file to be created.")
{
Arity = ArgumentArity.ZeroOrOne
};
var databaseOption = new Option<bool>(
aliases: new[] {"-d", "--use-database"},
description: "Use database. Save/retrieve wireless networks and clients to/from sqlite database.");
description: "Use database. Save/retrieve wireless networks and clients to/from sqlite database.")
{
Arity = ArgumentArity.ZeroOrOne
};
var queryOption = new Option<string?>(
aliases: new[] {"-q", "--query"},
description: "Filter input using sql query.");
description: "Filter input using sql query.")
{
Arity = ArgumentArity.ZeroOrOne
};
var rootCommand = new RootCommand("netxml2kml .netxml to .kml converter.");
rootCommand.AddOption(inputOption);