diff --git a/insight.sln b/insight.sln
index 57b9b5c..4cde53e 100644
--- a/insight.sln
+++ b/insight.sln
@@ -39,6 +39,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Remote.Shared", "sr
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Remote.Windows", "src\Remote\Insight.Remote.Windows\Insight.Remote.Windows.csproj", "{AF313B47-3079-407F-91D1-9989C1E1AF2A}"
EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Insight.Infrastructure.Web", "src\Core\Insight.Infrastructure.Web\Insight.Infrastructure.Web.csproj", "{39B81A0D-A88C-44D3-9624-1A19C78A4310}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -85,6 +87,10 @@ Global
{AF313B47-3079-407F-91D1-9989C1E1AF2A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF313B47-3079-407F-91D1-9989C1E1AF2A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF313B47-3079-407F-91D1-9989C1E1AF2A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {39B81A0D-A88C-44D3-9624-1A19C78A4310}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {39B81A0D-A88C-44D3-9624-1A19C78A4310}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {39B81A0D-A88C-44D3-9624-1A19C78A4310}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {39B81A0D-A88C-44D3-9624-1A19C78A4310}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -100,6 +106,7 @@ Global
{2A391CA2-F96B-4DB7-80AA-0668A5141640} = {140F73DD-29D3-4C44-809B-5B470880AA0D}
{5C4697BD-BC97-484F-9DB1-CA87E2BEAA4B} = {D4D7BF4A-B2E3-470A-A14C-FC658FF7461D}
{AF313B47-3079-407F-91D1-9989C1E1AF2A} = {D4D7BF4A-B2E3-470A-A14C-FC658FF7461D}
+ {39B81A0D-A88C-44D3-9624-1A19C78A4310} = {88B03853-2215-4E52-8986-0E76602E5F21}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F376A326-7590-4E7E-AB9B-76CED8527AB0}
diff --git a/src/Agent/Insight.Agent/Insight.Agent.csproj b/src/Agent/Insight.Agent/Insight.Agent.csproj
index 52dabcf..2dc4de2 100644
--- a/src/Agent/Insight.Agent/Insight.Agent.csproj
+++ b/src/Agent/Insight.Agent/Insight.Agent.csproj
@@ -2,17 +2,24 @@
Exe
- net7.0
+ net8.0
+ latest
Insight.Agent
Insight
agent
2023.12.14.0
enable
enable
+ none
+
+
+
+
+
- none
+ none
@@ -20,14 +27,14 @@
-
-
-
+
+
+
-
-
-
+
+
+
diff --git a/src/Agent/Insight.Agent/Network/AgentSession.cs b/src/Agent/Insight.Agent/Network/AgentSession.cs
index b13df10..8b23245 100644
--- a/src/Agent/Insight.Agent/Network/AgentSession.cs
+++ b/src/Agent/Insight.Agent/Network/AgentSession.cs
@@ -5,14 +5,10 @@ using Vaitr.Network;
namespace Insight.Agent.Network;
-public class AgentSession : TcpSession
+public class AgentSession(IEnumerable> handlers, ISerializer serializer, ILogger logger)
+ : TcpSession(serializer, logger)
{
- private readonly IEnumerable> _handlers;
-
- public AgentSession(IEnumerable> handlers, ISerializer serializer, ILogger logger) : base(serializer, logger)
- {
- _handlers = handlers;
- }
+ private readonly IEnumerable> _handlers = handlers;
protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken)
{
diff --git a/src/Agent/Insight.Agent/Network/Handlers/CustomHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/CustomHandler.cs
index 8330a6c..46e6a1a 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/CustomHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/CustomHandler.cs
@@ -2,20 +2,12 @@
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
-using Microsoft.Extensions.Logging;
namespace Insight.Agent.Network.Handlers;
-public class CustomHandler : IMessageHandler
+public class CustomHandler(ScriptService scriptService) : IMessageHandler
{
- private readonly ScriptService _scriptService;
- private readonly ILogger _logger;
-
- public CustomHandler(ScriptService scriptService, ILogger logger)
- {
- _scriptService = scriptService;
- _logger = logger;
- }
+ private readonly ScriptService _scriptService = scriptService;
public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
@@ -29,6 +21,7 @@ public class CustomHandler : IMessageHandler
private async ValueTask OnRequestAsync(AgentSession sender, Request request, CancellationToken cancellationToken)
{
+ if (request.RequestData is null) return;
var result = await _scriptService.QueryAsync(request.RequestData);
await sender.SendAsync(new Response(request)
diff --git a/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs
index d18393c..75b7670 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/DriveHandler.cs
@@ -59,7 +59,7 @@ public class DriveHandler : IMessageHandler
drive.InterfaceType = @object.GetValue(properties, "interfacetype")?.Trim();
drive.FirmwareRevision = @object.GetValue(properties, "firmwarerevision")?.Trim();
drive.PNPDeviceID = @object.GetValue(properties, "pnpdeviceid")?.Trim();
- drive.Volumes = new List();
+ drive.Volumes = [];
var diskpartition = @object.GetRelated("win32_diskpartition");
using (diskpartition)
@@ -155,7 +155,7 @@ public class DriveHandler : IMessageHandler
{
using (collection2)
{
- foreach (ManagementObject @object2 in collection2)
+ foreach (ManagementObject @object2 in collection2.Cast())
{
var properties2 = @object2.GetPropertyHashes();
diff --git a/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs
index e5b5b1b..92402ca 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/InterfaceHandler.cs
@@ -19,7 +19,7 @@ public class InterfaceHandler : IMessageHandler
case InventoryRequest:
{
var result = new Collection();
- result.AddRange(GetInterfaces());
+ if (GetInterfaces() is List interfaces) result.AddRange(interfaces);
await sender.SendAsync(result, cancellationToken);
break;
@@ -27,10 +27,10 @@ public class InterfaceHandler : IMessageHandler
}
}
- private static List GetInterfaces()
+ private static List? GetInterfaces()
{
if (NetworkInterface.GetIsNetworkAvailable() is false) return null;
- if (NetworkInterface.GetAllNetworkInterfaces().Any() is false) return null;
+ if (NetworkInterface.GetAllNetworkInterfaces().Length == 0) return null;
var interfaces = new List();
@@ -99,7 +99,7 @@ public class InterfaceHandler : IMessageHandler
using (collection)
{
- foreach (ManagementObject @object in collection)
+ foreach (ManagementObject @object in collection.Cast())
{
var properties = @object.GetPropertyHashes();
@@ -185,7 +185,7 @@ public class InterfaceHandler : IMessageHandler
{
var addresses = new List();
- if (unicastCollection.Any() is false) return addresses;
+ if (unicastCollection.Count == 0) return addresses;
foreach (var unicast in unicastCollection)
{
@@ -210,7 +210,7 @@ public class InterfaceHandler : IMessageHandler
{
var addresses = new List();
- if (addressCollection.Any() is false) return addresses;
+ if (addressCollection.Count == 0) return addresses;
foreach (var address in addressCollection)
{
@@ -224,7 +224,7 @@ public class InterfaceHandler : IMessageHandler
{
var addresses = new List();
- if (addressCollection.Any() is false) return addresses;
+ if (addressCollection.Count == 0) return addresses;
foreach (var address in addressCollection)
{
diff --git a/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs
index 4869735..324a357 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/MainboardHandler.cs
@@ -14,12 +14,12 @@ public class MainboardHandler : IMessageHandler
switch (message)
{
case InventoryRequest:
- await sender.SendAsync(GetMainboard(), cancellationToken);
+ if (GetMainboard() is Mainboard mainboard) await sender.SendAsync(mainboard, cancellationToken);
break;
}
}
- private static Mainboard GetMainboard()
+ private static Mainboard? GetMainboard()
{
using var searcher = new ManagementObjectSearcher
{
diff --git a/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs
index ef15546..ed62a70 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/OperationSystemHandler.cs
@@ -41,7 +41,7 @@ public class OperationSystemHandler : IMessageHandler
using (collection)
{
- foreach (ManagementObject @object in collection)
+ foreach (ManagementObject @object in collection.Cast())
{
var properties = @object.GetPropertyHashes();
@@ -51,7 +51,8 @@ public class OperationSystemHandler : IMessageHandler
if (@object.TryGetValue(properties, "osarchitecture", out var architecture))
{
- if (architecture is not null && architecture.ToLower().Contains("64")) os.Architecture = Architecture.X64;
+ if (architecture is not null && architecture.Contains("64", StringComparison.CurrentCultureIgnoreCase))
+ os.Architecture = Architecture.X64;
}
else
{
diff --git a/src/Agent/Insight.Agent/Network/Handlers/ProxyHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/ProxyHandler.cs
index e837e98..22956b3 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/ProxyHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/ProxyHandler.cs
@@ -2,20 +2,12 @@
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
-using Microsoft.Extensions.Logging;
namespace Insight.Agent.Network.Handlers;
-public class ProxyHandler : IMessageHandler
+public class ProxyHandler(ScriptService scriptService) : IMessageHandler
{
- private readonly ScriptService _scriptService;
- private readonly ILogger _logger;
-
- public ProxyHandler(ScriptService scriptService, ILogger logger)
- {
- _scriptService = scriptService;
- _logger = logger;
- }
+ private readonly ScriptService _scriptService = scriptService;
public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
@@ -29,6 +21,7 @@ public class ProxyHandler : IMessageHandler
private async ValueTask OnProxyRequestAsync(AgentSession sender, Proxy proxyRequest, CancellationToken cancellationToken)
{
+ if (proxyRequest.Message?.RequestData is null) return;
var result = await _scriptService.QueryAsync(proxyRequest.Message.RequestData);
await sender.SendAsync(new Proxy()
diff --git a/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs
index cfe9342..acb5755 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/ServiceHandler.cs
@@ -30,7 +30,7 @@ public class ServiceHandler : IMessageHandler
var services = new List();
var serviceControllers = ServiceController.GetServices()?.OrderBy(s => s.DisplayName)?.ToList();
- if (serviceControllers is null || serviceControllers.Any() is false) throw new InvalidOperationException("SERVICE Collection NULL");
+ if (serviceControllers is null || serviceControllers.Count == 0) throw new InvalidOperationException("SERVICE Collection NULL");
foreach (var sc in serviceControllers)
{
@@ -102,7 +102,7 @@ public class ServiceHandler : IMessageHandler
}
}
- if (services2.Any() is false) return services;
+ if (services2.Count == 0) return services;
foreach (var svc in services)
{
@@ -117,6 +117,6 @@ public class ServiceHandler : IMessageHandler
svc.Delay = map.Delay;
}
- return services.OrderBy(x => x.Name).ToList();
+ return [.. services.OrderBy(x => x.Name)];
}
}
\ No newline at end of file
diff --git a/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs
index b393ae5..886a062 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/SessionHandler.cs
@@ -48,7 +48,7 @@ public class SessionHandler : IMessageHandler
//public const int WTS_CURRENT_SESSION = -1;
[DllImport("wtsapi32.dll")]
- static extern int WTSEnumerateSessions(
+ private static extern int WTSEnumerateSessions(
nint pServer,
[MarshalAs(UnmanagedType.U4)] int iReserved,
[MarshalAs(UnmanagedType.U4)] int iVersion,
@@ -64,7 +64,7 @@ public class SessionHandler : IMessageHandler
out uint iBytesReturned);
[DllImport("wtsapi32.dll")]
- static extern void WTSFreeMemory(
+ private static extern void WTSFreeMemory(
nint pMemory);
[StructLayout(LayoutKind.Sequential)]
diff --git a/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs
index 18bb8a1..7f71a64 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/StoragePoolHandler.cs
@@ -89,121 +89,6 @@ public class StoragePoolHandler : IMessageHandler
return pools;
}
- private static List GetPhysicalDisks()
- {
- using var searcher = new ManagementObjectSearcher
- {
- Scope = new ManagementScope(@"root\microsoft\windows\storage"),
- Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname from msft_physicaldisk")
- };
-
- if (searcher.TryGet(out var collection) is false)
- {
- searcher.Query = new ObjectQuery("select * from msft_physicaldisk");
-
- if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
- }
-
- var disks = new List();
-
- using (collection)
- {
- foreach (ManagementObject @object in collection.Cast())
- {
- var disk = new PhysicalDisk();
-
- var properties = @object.GetPropertyHashes();
-
- disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim();
- disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim();
- disk.Manufacturer = @object.GetValue(properties, "manufacturer")?.Trim();
- disk.Model = @object.GetValue(properties, "model")?.Trim();
- disk.MediaType = @object.GetValue(properties, "mediatype");
- disk.BusType = @object.GetValue(properties, "bustype");
-
- if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null)
- {
- disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList();
- }
-
- disk.Health = (PhysicalDisk.HealthState)@object.GetValue(properties, "healthstatus");
-
- if (@object.TryGetValue(properties, "supportedusages", out var supportedusages) && supportedusages is not null)
- {
- disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList();
- }
-
- disk.Usage = @object.GetValue(properties, "usage");
- disk.PhysicalLocation = @object.GetValue(properties, "physicallocation")?.Trim();
- disk.SerialNumber = @object.GetValue(properties, "serialnumber")?.Trim();
- disk.FirmwareVersion = @object.GetValue(properties, "firmwareversion")?.Trim();
- disk.Size = @object.GetValue(properties, "size");
- disk.AllocatedSize = @object.GetValue(properties, "allocatedsize");
- disk.LogicalSectorSize = @object.GetValue(properties, "logicalsectorsize");
- disk.PhysicalSectorSize = @object.GetValue(properties, "physicalsectorsize");
- disk.VirtualDiskFootprint = @object.GetValue(properties, "virtualdiskfootprint");
-
- disks.Add(disk);
- }
- }
-
- return disks;
- }
-
- private static List GetVirtualDisks()
- {
- using var searcher = new ManagementObjectSearcher
- {
- Scope = new ManagementScope(@"root\microsoft\windows\storage"),
- Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname, access, provisioningtype, physicaldiskredundancy, resiliencysettingname, isdeduplicationenabled, issnapshot, operationalstatus, healthstatus, size, allocatedsize, footprintonpool, readcachesize, writecachesize from msft_virtualdisk")
- };
-
- if (searcher.TryGet(out var collection) is false)
- {
- searcher.Query = new ObjectQuery("select * from msft_virtualdisk");
-
- if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
- }
-
- var disks = new List();
-
- using (collection)
- {
- foreach (ManagementObject @object in collection.Cast())
- {
- var disk = new VirtualDisk();
-
- var properties = @object.GetPropertyHashes();
-
- disk.UniqueId = @object.GetValue(properties, "uniqueid")?.Trim();
- disk.Name = @object.GetValue(properties, "name")?.Trim();
- disk.FriendlyName = @object.GetValue(properties, "friendlyname")?.Trim();
- disk.AccessType = (AccessTypeEnum)@object.GetValue(properties, "access");
- disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue(properties, "provisioningtype");
- disk.PhysicalDiskRedundancy = @object.GetValue(properties, "physicaldiskredundancy");
- disk.ResiliencySettingName = @object.GetValue(properties, "resiliencysettingname")?.Trim();
- disk.Deduplication = @object.GetValue(properties, "isdeduplicationenabled");
- disk.IsSnapshot = @object.GetValue(properties, "issnapshot");
-
- if (@object.TryGetValue(properties, "operationalstatus", out var operationals) && operationals is not null)
- {
- disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList();
- }
-
- disk.Health = (VirtualDisk.HealthState)@object.GetValue(properties, "healthstatus");
- disk.Size = @object.GetValue(properties, "size");
- disk.AllocatedSize = @object.GetValue(properties, "allocatedsize");
- disk.FootprintOnPool = @object.GetValue(properties, "footprintonpool");
- disk.ReadCacheSize = @object.GetValue(properties, "readcachesize");
- disk.WriteCacheSize = @object.GetValue(properties, "writecachesize");
-
- disks.Add(disk);
- }
- }
-
- return disks;
- }
-
private static List QueryPhysicalDisksByStoragePool(string storagePoolObjectId)
{
using var searcher = new ManagementObjectSearcher
@@ -218,7 +103,7 @@ public class StoragePoolHandler : IMessageHandler
using (collection)
{
- foreach (ManagementObject @object in collection)
+ foreach (ManagementObject @object in collection.Cast())
{
var disk = new PhysicalDisk();
@@ -275,7 +160,7 @@ public class StoragePoolHandler : IMessageHandler
using (collection)
{
- foreach (ManagementObject @object in collection)
+ foreach (ManagementObject @object in collection.Cast())
{
var disk = new VirtualDisk();
diff --git a/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs
index 49269d7..0a7e7d4 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/SystemInfoHandler.cs
@@ -87,7 +87,6 @@ public class SystemInfoHandler : IMessageHandler
private static string GetWindowsProductKeyFromDigitalProductId(byte[] digitalProductId, DigitalProductIdVersion digitalProductIdVersion)
{
-
var productKey = digitalProductIdVersion == DigitalProductIdVersion.Windows8AndUp
? DecodeProductKeyWin8AndUp(digitalProductId)
: DecodeProductKey(digitalProductId);
@@ -124,7 +123,7 @@ public class SystemInfoHandler : IMessageHandler
var digitMapIndex = 0;
for (var j = decodeStringLength - 1; j >= 0; j--)
{
- var byteValue = digitMapIndex << 8 | (byte)hexPid[j];
+ var byteValue = digitMapIndex << 8 | (byte)hexPid[j]!;
hexPid[j] = (byte)(byteValue / 24);
digitMapIndex = byteValue % 24;
decodedChars[i] = digits[digitMapIndex];
@@ -148,17 +147,17 @@ public class SystemInfoHandler : IMessageHandler
var current = 0;
for (var j = 14; j >= 0; j--)
{
- current = current * 256;
+ current *= 256;
current = digitalProductId[j + keyOffset] + current;
digitalProductId[j + keyOffset] = (byte)(current / 24);
- current = current % 24;
+ current %= 24;
last = current;
}
key = digits[current] + key;
}
var keypart1 = key.Substring(1, last);
- var keypart2 = key.Substring(last + 1, key.Length - (last + 1));
+ var keypart2 = key[(last + 1)..];
key = keypart1 + "N" + keypart2;
for (var i = 5; i < key.Length; i += 6)
diff --git a/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs
index 80454a2..1679d7e 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/UpdateHandler.cs
@@ -10,7 +10,7 @@ using UpdateCollection = Insight.Domain.Network.Agent.Messages.UpdateCollection;
namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
-public class UpdateHandler : IMessageHandler
+public partial class UpdateHandler : IMessageHandler
{
public async ValueTask HandleAsync(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
@@ -60,7 +60,7 @@ public class UpdateHandler : IMessageHandler
try
{
- var rx = new Regex(@"KB(\d+)");
+ var rx = KnowledgeBaseRegex();
update.Hotfix = rx.Match(wupdate.Title).Value;
}
catch (Exception)
@@ -125,4 +125,7 @@ public class UpdateHandler : IMessageHandler
return updates;
}
+
+ [GeneratedRegex(@"KB(\d+)")]
+ private static partial Regex KnowledgeBaseRegex();
}
\ No newline at end of file
diff --git a/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs
index 76b5602..e681b8e 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/UserHandler.cs
@@ -32,7 +32,7 @@ public class UserHandler : IMessageHandler
foreach (var u in users)
{
- u.Groups = new List();
+ u.Groups = [];
foreach (var ug in usergrouping.Where(ug => ug.UserDomain == u.Domain && ug.UserName == u.Name))
{
@@ -67,7 +67,7 @@ public class UserHandler : IMessageHandler
using (collection)
{
- foreach (ManagementObject @object in collection)
+ foreach (ManagementObject @object in collection.Cast())
{
var group = new Group();
@@ -83,7 +83,7 @@ public class UserHandler : IMessageHandler
}
}
- return groups.OrderBy(x => x.Name)?.ToList();
+ return [.. groups.OrderBy(x => x.Name)];
}
private static List QueryUsers()
@@ -105,7 +105,7 @@ public class UserHandler : IMessageHandler
using (collection)
{
- foreach (ManagementObject @object in collection)
+ foreach (ManagementObject @object in collection.Cast())
{
var user = new User();
@@ -150,7 +150,7 @@ public class UserHandler : IMessageHandler
using (collection)
{
- foreach (ManagementObject @object in collection)
+ foreach (ManagementObject @object in collection.Cast())
{
var usergroup = new UserGroupMap();
diff --git a/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs b/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs
index f8c843f..793ae19 100644
--- a/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs
+++ b/src/Agent/Insight.Agent/Network/Handlers/VirtualMaschineHandler.cs
@@ -341,7 +341,7 @@ public class VirtualMaschineHandler : IMessageHandler
{
conf.ParentId = parentGuid.ToString();
- parentConfig.Childs ??= new List();
+ parentConfig.Childs ??= [];
parentConfig.Childs.Add(conf);
}
else
diff --git a/src/Agent/Insight.Agent/Program.cs b/src/Agent/Insight.Agent/Program.cs
index 807ac7a..3b07be9 100644
--- a/src/Agent/Insight.Agent/Program.cs
+++ b/src/Agent/Insight.Agent/Program.cs
@@ -9,6 +9,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
+using System.Runtime.Versioning;
using Vaitr.Network;
using Vaitr.Network.Hosting;
@@ -66,29 +67,13 @@ internal class Program
options.UseSerializer>();
});
- services.AddSingleton, CustomHandler>();
- services.AddSingleton, ProxyHandler>();
services.AddSingleton, AuthenticationHandler>();
- services.AddSingleton, DriveHandler>();
- services.AddSingleton, InterfaceHandler>();
- services.AddSingleton, MainboardHandler>();
- services.AddSingleton, MemoryHandler>();
- services.AddSingleton, OperationSystemHandler>();
- services.AddSingleton, PrinterHandler>();
- services.AddSingleton, ProcessorHandler>();
- services.AddSingleton, ServiceHandler>();
- services.AddSingleton, SessionHandler>();
- services.AddSingleton, SoftwareHandler>();
- services.AddSingleton, StoragePoolHandler>();
- services.AddSingleton, SystemInfoHandler>();
- services.AddSingleton, UpdateHandler>();
- services.AddSingleton, UserHandler>();
- services.AddSingleton, VideocardHandler>();
- services.AddSingleton, VirtualMaschineHandler>();
-
+ services.AddSingleton, ProxyHandler>();
+ services.AddSingleton, CustomHandler>();
+
+ if (OperatingSystem.IsWindows()) ServiceCollectionExtensions.InjectWindowsHandler(services);
// GLOBAL DEPENDENCIES
- //services.AddSingleton();
services.AddTransient(provider => new HttpClient(new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
@@ -99,4 +84,30 @@ internal class Program
var host = builder.Build();
await host.RunAsync().ConfigureAwait(false);
}
+}
+
+internal static class ServiceCollectionExtensions
+{
+ [SupportedOSPlatform("windows")]
+ internal static IServiceCollection InjectWindowsHandler(this IServiceCollection services)
+ {
+ services.AddSingleton, DriveHandler>();
+ services.AddSingleton, InterfaceHandler>();
+ services.AddSingleton, MainboardHandler>();
+ services.AddSingleton, MemoryHandler>();
+ services.AddSingleton, OperationSystemHandler>();
+ services.AddSingleton, PrinterHandler>();
+ services.AddSingleton, ProcessorHandler>();
+ services.AddSingleton, ServiceHandler>();
+ services.AddSingleton, SessionHandler>();
+ services.AddSingleton, SoftwareHandler>();
+ services.AddSingleton, StoragePoolHandler>();
+ services.AddSingleton, SystemInfoHandler>();
+ services.AddSingleton, UpdateHandler>();
+ services.AddSingleton, UserHandler>();
+ services.AddSingleton, VideocardHandler>();
+ services.AddSingleton, VirtualMaschineHandler>();
+
+ return services;
+ }
}
\ No newline at end of file
diff --git a/src/Agent/Insight.Agent/Services/CollectorService.cs b/src/Agent/Insight.Agent/Services/CollectorService.cs
index 03ac923..2058aeb 100644
--- a/src/Agent/Insight.Agent/Services/CollectorService.cs
+++ b/src/Agent/Insight.Agent/Services/CollectorService.cs
@@ -5,12 +5,7 @@ using System.Runtime.Versioning;
namespace Insight.Agent.Services;
[SupportedOSPlatform("linux")]
-public partial class CollectorService
+public partial class CollectorService(ILogger? logger = null)
{
- public ILogger Logger { get; }
-
- public CollectorService(ILogger? logger = null)
- {
- Logger = logger ?? NullLogger.Instance;
- }
+ public ILogger Logger { get; } = logger ?? NullLogger.Instance;
}
\ No newline at end of file
diff --git a/src/Agent/Insight.Agent/Services/Configurator.cs b/src/Agent/Insight.Agent/Services/Configurator.cs
index 3dbfa76..44fbace 100644
--- a/src/Agent/Insight.Agent/Services/Configurator.cs
+++ b/src/Agent/Insight.Agent/Services/Configurator.cs
@@ -4,12 +4,14 @@ namespace Insight.Agent.Services;
public static class Configurator
{
+ private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNameCaseInsensitive = true, WriteIndented = true };
+
public static async ValueTask ReadAsync(string file, CancellationToken cancellationToken = default)
where TConfig : class
{
var json = await File.ReadAllTextAsync(file, cancellationToken);
- if (JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, WriteIndented = true }) is not TConfig config)
+ if (JsonSerializer.Deserialize(json, _serializerOptions) is not TConfig config)
{
throw new InvalidDataException($"Failed to deserialize ({file})");
}
@@ -31,7 +33,7 @@ public static class Configurator
{
var json = await File.ReadAllTextAsync(file, cancellationToken);
- if (JsonSerializer.Deserialize>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, WriteIndented = true }) is not IDictionary config)
+ if (JsonSerializer.Deserialize>(json, _serializerOptions) is not IDictionary config)
{
throw new InvalidDataException($"Failed to deserialize ({file})");
}
@@ -89,7 +91,7 @@ public static class Configurator
private static async ValueTask WriteToFileAsync(TData data, string file, CancellationToken cancellationToken)
{
- var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true });
+ var json = JsonSerializer.Serialize(data, _serializerOptions);
await File.WriteAllTextAsync(file, json, cancellationToken);
}
diff --git a/src/Agent/Insight.Agent/Services/EventService.cs b/src/Agent/Insight.Agent/Services/EventService.cs
index b2520a9..e14d8da 100644
--- a/src/Agent/Insight.Agent/Services/EventService.cs
+++ b/src/Agent/Insight.Agent/Services/EventService.cs
@@ -163,7 +163,7 @@ internal class EventService : BackgroundService
};
}
- _queue.Writer.WriteAsync(@event, default);
+ _ = _queue.Writer.WriteAsync(@event, default);
}
catch (Exception) { } // app crash
}
diff --git a/src/Agent/Insight.Agent/Services/ScriptService.cs b/src/Agent/Insight.Agent/Services/ScriptService.cs
index 32e4eda..f77c3c4 100644
--- a/src/Agent/Insight.Agent/Services/ScriptService.cs
+++ b/src/Agent/Insight.Agent/Services/ScriptService.cs
@@ -4,17 +4,14 @@ using System.Management.Automation.Runspaces;
namespace Insight.Agent.Services;
-public class ScriptService
+public class ScriptService(ILogger logger)
{
- private readonly ILogger _logger;
-
- public ScriptService(ILogger logger)
- {
- _logger = logger;
- }
+ private readonly ILogger _logger = logger;
public async Task QueryAsync(string query)
{
+ _logger.LogDebug("QueryAsync ({query})", query);
+
var result = new QueryResult();
var errors = new List();
diff --git a/src/Agent/Insight.Agent/Services/UpdateService.cs b/src/Agent/Insight.Agent/Services/UpdateService.cs
index f879069..18df6fe 100644
--- a/src/Agent/Insight.Agent/Services/UpdateService.cs
+++ b/src/Agent/Insight.Agent/Services/UpdateService.cs
@@ -12,19 +12,12 @@ using System.Text.Json;
namespace Insight.Agent.Services;
-internal class UpdateService : BackgroundService
+internal class UpdateService(HttpClient httpClient, IConfiguration configuration, ILogger logger) : BackgroundService
{
- private readonly Uri _uri;
+ private readonly Uri _uri = configuration.GetValue("api") ?? throw new Exception($"api value not set (appsettings)");
- private readonly HttpClient _httpClient;
- private readonly ILogger _logger;
-
- public UpdateService(HttpClient httpClient, IConfiguration configuration, ILogger logger)
- {
- _httpClient = httpClient;
- _uri = configuration.GetValue("api") ?? throw new Exception($"api value not set (appsettings)");
- _logger = logger;
- }
+ private readonly HttpClient _httpClient = httpClient;
+ private readonly ILogger _logger = logger;
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
@@ -42,7 +35,7 @@ internal class UpdateService : BackgroundService
_logger.LogInformation("Update Result: {result}", result?.Success);
if (result?.UpdateErrors is not null)
{
- _logger.LogError("Update Errors: {errors}", string.Concat(result?.UpdateErrors));
+ _logger.LogError("Update Errors: {errors}", string.Concat(result.UpdateErrors));
}
}
catch (OperationCanceledException) { }
@@ -198,7 +191,7 @@ internal class UpdateService : BackgroundService
await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken);
// extract update archive from temp to app dir (overwrite)
- ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true);
+ ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory!.FullName, true);
// delete temp folder
if (temp.Exists) temp.Delete(true);
@@ -229,7 +222,7 @@ internal class UpdateService : BackgroundService
var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName);
- if (matched is null || matched.Any() is false) return false;
+ if (matched is null || matched.Length == 0) return false;
if (matched.Any(p =>
p.MainModule is not null &&
@@ -262,7 +255,7 @@ internal class UpdateService : BackgroundService
var matched = System.Diagnostics.Process.GetProcessesByName(bin.FullName);
- if (matched is null || matched.Any() is false) return true;
+ if (matched is null || matched.Length == 0) return true;
foreach (var procsInfo in matched.Where(p =>
p.MainModule is not null &&
@@ -312,7 +305,7 @@ internal class UpdateService : BackgroundService
await File.WriteAllBytesAsync(updateFile.FullName, await update.Content.ReadAsByteArrayAsync(cancellationToken), cancellationToken);
// extract update archive from temp to app dir (overwrite)
- ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory?.FullName, true);
+ ZipFile.ExtractToDirectory(updateFile.FullName, bin.Directory!.FullName, true);
// delete temp folder
if (temp.Exists) temp.Delete(true);
@@ -353,7 +346,7 @@ internal class UpdateService : BackgroundService
public bool ApiAvailable { get; set; } = false;
public bool UpdateAvailable { get; set; } = false;
public bool Success { get; set; } = false;
- public List ApiErrors { get; } = new();
- public List UpdateErrors { get; } = new();
+ public List ApiErrors { get; } = [];
+ public List UpdateErrors { get; } = [];
}
}
\ No newline at end of file
diff --git a/src/Agent/Insight.Agent/Services/_Collector/_Os.cs b/src/Agent/Insight.Agent/Services/_Collector/_Os.cs
index 34db513..b74254d 100644
--- a/src/Agent/Insight.Agent/Services/_Collector/_Os.cs
+++ b/src/Agent/Insight.Agent/Services/_Collector/_Os.cs
@@ -21,10 +21,9 @@ public partial class CollectorService
output = stream.ReadToEnd();
// clean output
- var clean = Regex
- .Replace(output
+ var clean = CleanRegex().Replace(output
.Trim()
- .Replace("\t", " "), @"[ ]{2,}", " ");
+ .Replace("\t", " "), " ");
var elements = clean.Split(Array.Empty(), StringSplitOptions.RemoveEmptyEntries);
@@ -36,13 +35,12 @@ public partial class CollectorService
// linebreak list conversion
var lines = new List(output
- .Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
+ .Split(separator, StringSplitOptions.RemoveEmptyEntries))
.Select(l =>
{
- return Regex
- .Replace(l
+ return CleanRegex().Replace(l
.Trim()
- .Replace("\t", " "), @"[ ]{2,}", " ");
+ .Replace("\t", " "), " ");
})
.ToList();
@@ -62,13 +60,12 @@ public partial class CollectorService
// linebreak list conversion
lines = new List(output
- .Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
+ .Split(separator, StringSplitOptions.RemoveEmptyEntries))
.Select(l =>
{
- return Regex
- .Replace(l
+ return CleanRegex().Replace(l
.Trim()
- .Replace("\t", " "), @"[ ]{2,}", " ");
+ .Replace("\t", " "), " ");
})
.ToList();
@@ -102,4 +99,9 @@ public partial class CollectorService
return os;
}
+
+ private static readonly string[] separator = ["\n", "\r\n"];
+
+ [GeneratedRegex(@"[ ]{2,}")]
+ private static partial Regex CleanRegex();
}
\ No newline at end of file
diff --git a/src/Agent/Insight.Agent/Services/_Collector/_Session.cs b/src/Agent/Insight.Agent/Services/_Collector/_Session.cs
index fd42981..a393ee1 100644
--- a/src/Agent/Insight.Agent/Services/_Collector/_Session.cs
+++ b/src/Agent/Insight.Agent/Services/_Collector/_Session.cs
@@ -17,11 +17,11 @@ public partial class CollectorService
var output = "w".Bash();
// linebreak list conversion
- var lines = output.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
+ var lines = output.Split(separatorArray, StringSplitOptions.RemoveEmptyEntries).ToList();
lines = lines.Select(l =>
{
- return Regex.Replace(l.Trim().Replace("\t", " "), @"[ ]{2,}", " ");
+ return CleanOutputRegex().Replace(l.Trim().Replace("\t", " "), " ");
}).ToList();
// cleaning
@@ -46,4 +46,9 @@ public partial class CollectorService
return sessions;
}
+
+ private static readonly string[] separatorArray = ["\n", "\r\n"];
+
+ [GeneratedRegex(@"[ ]{2,}")]
+ private static partial Regex CleanOutputRegex();
}
\ No newline at end of file
diff --git a/src/Api/Insight.Api/Controllers/AccountController.cs b/src/Api/Insight.Api/Controllers/AccountController.cs
index 3510438..4d80252 100644
--- a/src/Api/Insight.Api/Controllers/AccountController.cs
+++ b/src/Api/Insight.Api/Controllers/AccountController.cs
@@ -1,31 +1,29 @@
using Insight.Api.Models;
+using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Models;
using Insight.Infrastructure.Services;
+using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using MongoDB.Driver;
namespace Insight.Api.Controllers;
[ApiController, Route("api/accounts")]
-public class AccountController : ControllerBase
+public class AccountController(IdentityService identityService, IServiceScopeFactory scopeFactory) : ControllerBase
{
- private readonly IdentityService _identityService;
- private readonly AccountService _accountService;
- private readonly ILogger _logger;
-
- public AccountController(IdentityService identityService, AccountService accountService, ILogger logger)
- {
- _identityService = identityService;
- _accountService = accountService;
- _logger = logger;
- }
+ private readonly IdentityService _identityService = identityService;
+ private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
[HttpGet, Authorize]
public async Task Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{
+ using var scope = _scopeFactory.CreateScope();
+ var collection = scope.ServiceProvider.GetRequiredService().User();
+
try
{
- var result = await _accountService.GetAsync(
+ var result = await collection.GetPagedAsync(
offset: request.Offset,
limit: request.Limit,
request: Request,
diff --git a/src/Api/Insight.Api/Controllers/AgentController.cs b/src/Api/Insight.Api/Controllers/AgentController.cs
index 0a1e5b9..c1d10cc 100644
--- a/src/Api/Insight.Api/Controllers/AgentController.cs
+++ b/src/Api/Insight.Api/Controllers/AgentController.cs
@@ -1,28 +1,26 @@
-using Insight.Infrastructure.Models;
-using Insight.Infrastructure.Services;
+using Insight.Infrastructure.Entities;
+using Insight.Infrastructure.Models;
+using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using MongoDB.Driver;
namespace Insight.Api.Controllers;
[ApiController, Route("api/agents")]
-public class AgentController : ControllerBase
+public class AgentController(IServiceScopeFactory scopeFactory) : ControllerBase
{
- private readonly AgentService _agentService;
- private readonly ILogger _logger;
-
- public AgentController(AgentService agentService, ILogger logger)
- {
- _agentService = agentService;
- _logger = logger;
- }
+ private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
[HttpGet, Authorize]
public async Task Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{
+ using var scope = _scopeFactory.CreateScope();
+ var collection = scope.ServiceProvider.GetRequiredService().Agent();
+
try
{
- var result = await _agentService.GetAsync(
+ var result = await collection.GetPagedAsync(
offset: request.Offset,
limit: request.Limit,
request: Request,
diff --git a/src/Api/Insight.Api/Controllers/CustomerController.cs b/src/Api/Insight.Api/Controllers/CustomerController.cs
index 4aedc19..ddc94a2 100644
--- a/src/Api/Insight.Api/Controllers/CustomerController.cs
+++ b/src/Api/Insight.Api/Controllers/CustomerController.cs
@@ -1,28 +1,26 @@
-using Insight.Infrastructure.Models;
-using Insight.Infrastructure.Services;
+using Insight.Infrastructure.Entities;
+using Insight.Infrastructure.Models;
+using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using MongoDB.Driver;
namespace Insight.Api.Controllers;
[ApiController, Route("api/customers")]
-public class CustomerController : ControllerBase
+public class CustomerController(IServiceScopeFactory scopeFactory) : ControllerBase
{
- private readonly CustomerService _customerService;
- private readonly ILogger _logger;
-
- public CustomerController(CustomerService customerService, ILogger logger)
- {
- _customerService = customerService;
- _logger = logger;
- }
+ private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
[HttpGet, Authorize]
public async Task Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{
+ using var scope = _scopeFactory.CreateScope();
+ var collection = scope.ServiceProvider.GetRequiredService().Customer();
+
try
{
- var result = await _customerService.GetAsync(
+ var result = await collection.GetPagedAsync(
offset: request.Offset,
limit: request.Limit,
request: Request,
diff --git a/src/Api/Insight.Api/Controllers/HostController.cs b/src/Api/Insight.Api/Controllers/HostController.cs
index d8eb5c5..ccd9fea 100644
--- a/src/Api/Insight.Api/Controllers/HostController.cs
+++ b/src/Api/Insight.Api/Controllers/HostController.cs
@@ -1,28 +1,26 @@
-using Insight.Infrastructure.Models;
-using Insight.Infrastructure.Services;
+using Insight.Infrastructure.Entities;
+using Insight.Infrastructure.Models;
+using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using MongoDB.Driver;
namespace Insight.Api.Controllers;
[ApiController, Route("api/hosts")]
-public class HostController : ControllerBase
+public class HostController(IServiceScopeFactory scopeFactory) : ControllerBase
{
- private readonly HostService _hostService;
- private readonly ILogger _logger;
-
- public HostController(HostService hostService, ILogger logger)
- {
- _hostService = hostService;
- _logger = logger;
- }
+ private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
[HttpGet, Authorize]
public async Task Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
{
+ using var scope = _scopeFactory.CreateScope();
+ var collection = scope.ServiceProvider.GetRequiredService().Host();
+
try
{
- var result = await _hostService.GetAsync(
+ var result = await collection.GetPagedAsync(
offset: request.Offset,
limit: request.Limit,
request: Request,
diff --git a/src/Api/Insight.Api/Controllers/InventoryController.cs b/src/Api/Insight.Api/Controllers/InventoryController.cs
index 4327843..14e0e23 100644
--- a/src/Api/Insight.Api/Controllers/InventoryController.cs
+++ b/src/Api/Insight.Api/Controllers/InventoryController.cs
@@ -1,6 +1,6 @@
using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Models;
-using Insight.Infrastructure.Services;
+using Insight.Infrastructure.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
@@ -11,20 +11,16 @@ using System.Text.RegularExpressions;
namespace Insight.Api.Controllers;
[ApiController, Route("api/inventory")]
-public class InventoryController : ControllerBase
+public class InventoryController(IServiceScopeFactory scopeFactory) : ControllerBase
{
- private readonly InventoryService _inventoryService;
- private readonly ILogger _logger;
-
- public InventoryController(InventoryService inventoryService, ILogger logger)
- {
- _inventoryService = inventoryService;
- _logger = logger;
- }
+ private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
[HttpGet, Authorize]
public async Task Get([FromQuery] HostApplicationEntity request, [FromQuery] PagedDataRequest meta, CancellationToken cancellationToken)
{
+ using var scope = _scopeFactory.CreateScope();
+ var collection = scope.ServiceProvider.GetRequiredService().HostApplication();
+
try
{
var filter = Builders.Filter.Empty;
@@ -38,7 +34,7 @@ public class InventoryController : ControllerBase
if (request.Name is not null)
filter &= Builders.Filter.Regex(p => p.Name, new BsonRegularExpression(new Regex(request.Name, RegexOptions.IgnoreCase)));
- var result = await _inventoryService.GetAsync(
+ var result = await collection.GetPagedAsync(
filter: filter,
offset: meta.Offset,
limit: meta.Limit,
diff --git a/src/Api/Insight.Api/Controllers/SetupController.cs b/src/Api/Insight.Api/Controllers/SetupController.cs
index 831a922..fe03166 100644
--- a/src/Api/Insight.Api/Controllers/SetupController.cs
+++ b/src/Api/Insight.Api/Controllers/SetupController.cs
@@ -3,14 +3,9 @@
namespace Insight.Server.Controllers;
[ApiController, Route("api/setup")]
-public class SetupController : ControllerBase
+public class SetupController(ILogger logger) : ControllerBase
{
- private readonly ILogger _logger;
-
- public SetupController(ILogger logger)
- {
- _logger = logger;
- }
+ private readonly ILogger _logger = logger;
[HttpGet("windows")]
public async Task GetAsync(CancellationToken cancellationToken)
diff --git a/src/Api/Insight.Api/Controllers/TokenController.cs b/src/Api/Insight.Api/Controllers/TokenController.cs
index 9c36083..12825b1 100644
--- a/src/Api/Insight.Api/Controllers/TokenController.cs
+++ b/src/Api/Insight.Api/Controllers/TokenController.cs
@@ -6,14 +6,9 @@ using Microsoft.AspNetCore.Mvc;
namespace Insight.Api.Controllers;
[ApiController, Route("api/token", Order = 0)]
-public class TokenController : ControllerBase
+public class TokenController(TokenService tokenService) : ControllerBase
{
- private readonly TokenService _tokenService;
-
- public TokenController(TokenService tokenService)
- {
- _tokenService = tokenService;
- }
+ private readonly TokenService _tokenService = tokenService;
///
/// Access Token Request
@@ -21,6 +16,9 @@ public class TokenController : ControllerBase
[HttpPost, AllowAnonymous]
public async Task Authentication([FromBody] TokenRequest request)
{
+ if (request.Username is null) return BadRequest("username is null");
+ if (request.Password is null) return BadRequest("password is null");
+
try
{
var result = await _tokenService.GetAsync(request.Username, request.Password, request.Code, HttpContext.Connection.RemoteIpAddress).ConfigureAwait(false);
diff --git a/src/Api/Insight.Api/Controllers/UpdateController.cs b/src/Api/Insight.Api/Controllers/UpdateController.cs
index 173a636..712f2fa 100644
--- a/src/Api/Insight.Api/Controllers/UpdateController.cs
+++ b/src/Api/Insight.Api/Controllers/UpdateController.cs
@@ -5,14 +5,9 @@ using Microsoft.AspNetCore.Mvc;
namespace Insight.Server.Controllers;
[ApiController, Route("api/update")]
-public class UpdateController : ControllerBase
+public class UpdateController(ILogger logger) : ControllerBase
{
- private readonly ILogger _logger;
-
- public UpdateController(ILogger logger)
- {
- _logger = logger;
- }
+ private readonly ILogger _logger = logger;
[HttpGet("updater/windows")]
public IActionResult UpdaterWindows()
@@ -35,7 +30,7 @@ public class UpdateController : ControllerBase
var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly);
- if (versions is null || versions.Any() is false) return NotFound();
+ if (versions is null || versions.Length == 0) return NotFound();
var latest = versions.OrderBy(x => x.Name).FirstOrDefault();
@@ -73,7 +68,7 @@ public class UpdateController : ControllerBase
var versions = updateDir.GetFiles("*.zip", SearchOption.TopDirectoryOnly);
- if (versions is null || versions.Any() is false) return NotFound();
+ if (versions is null || versions.Length == 0) return NotFound();
var latest = versions.OrderBy(x => x.Name).FirstOrDefault();
diff --git a/src/Api/Insight.Api/Extensions/ServiceExtensions.cs b/src/Api/Insight.Api/Extensions/ServiceExtensions.cs
index afd32de..51342ce 100644
--- a/src/Api/Insight.Api/Extensions/ServiceExtensions.cs
+++ b/src/Api/Insight.Api/Extensions/ServiceExtensions.cs
@@ -6,7 +6,7 @@ namespace Insight.Api.Hosting;
public static class ServiceExtensions
{
- internal static IServiceCollection AddSwaggerServices(this IServiceCollection services, IConfiguration configuration)
+ internal static IServiceCollection AddSwaggerServices(this IServiceCollection services)
{
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
diff --git a/src/Api/Insight.Api/Insight.Api.csproj b/src/Api/Insight.Api/Insight.Api.csproj
index 2d4f1d9..e67d2bf 100644
--- a/src/Api/Insight.Api/Insight.Api.csproj
+++ b/src/Api/Insight.Api/Insight.Api.csproj
@@ -1,43 +1,36 @@
-
-
- net7.0
- Insight
- api
- 2023.12.14.0
- Insight.Api
- enable
- enable
- 4ae1d3bf-869e-4963-8a19-35634507d3b3
-
- false
- false
-
-
- True
- $(NoWarn);1591
-
-
-
- none
-
-
-
- none
-
+ True
+ $(NoWarn);1591
+ none
+
-
-
-
-
-
-
+
+
+
+
+
+
-
+
+
-
-
+
+
\ No newline at end of file
diff --git a/src/Api/Insight.Api/Program.cs b/src/Api/Insight.Api/Program.cs
index 8e2b778..d9dea66 100644
--- a/src/Api/Insight.Api/Program.cs
+++ b/src/Api/Insight.Api/Program.cs
@@ -40,12 +40,12 @@ internal class Program
builder.Services.AddAuthorization();
// WEBSERVICES
- builder.Services.AddProxyServices(builder.Configuration);
- builder.Services.AddRoutingServices(builder.Configuration);
+ builder.Services.AddProxyServices();
+ builder.Services.AddRoutingServices();
builder.Services.AddControllers();
// SWAGGER
- builder.Services.AddSwaggerServices(builder.Configuration);
+ builder.Services.AddSwaggerServices();
//builder.Services.AddControllers();
//builder.Services.AddEndpointsApiExplorer();
diff --git a/src/Core/Insight.Domain/Constants/Configuration.cs b/src/Core/Insight.Domain/Constants/Configuration.cs
index 812b469..0e79218 100644
--- a/src/Core/Insight.Domain/Constants/Configuration.cs
+++ b/src/Core/Insight.Domain/Constants/Configuration.cs
@@ -1,4 +1,5 @@
-using System.Net;
+using System.Diagnostics;
+using System.Net;
using System.Reflection;
namespace Insight.Domain.Constants;
@@ -7,6 +8,14 @@ public static class Configuration
{
public static string Hostname => Dns.GetHostEntry("localhost").HostName;
public static Version Version => Assembly.GetEntryAssembly()?.GetName().Version ?? throw new ArgumentNullException("Version");
- public static DirectoryInfo? AppDirectory => string.IsNullOrWhiteSpace(Environment.ProcessPath) ? null : new DirectoryInfo(Environment.ProcessPath).Parent;
+ public static DirectoryInfo? AppDirectory => AppDirectoryHelper();
public static string DefaultConfig => Path.Combine(AppDirectory?.FullName ?? string.Empty, "config.json");
+
+ private static DirectoryInfo? AppDirectoryHelper()
+ {
+ using var proc = Process.GetCurrentProcess();
+
+ if (proc?.MainModule?.FileName is null) throw new InvalidOperationException("MainModule not found");
+ return new DirectoryInfo(proc.MainModule.FileName).Parent;
+ }
}
\ No newline at end of file
diff --git a/src/Core/Insight.Domain/Enums/CategoryEnum.cs b/src/Core/Insight.Domain/Enums/CategoryEnum.cs
index 739b5fd..847e096 100644
--- a/src/Core/Insight.Domain/Enums/CategoryEnum.cs
+++ b/src/Core/Insight.Domain/Enums/CategoryEnum.cs
@@ -2,6 +2,7 @@
public enum CategoryEnum
{
+ None = 0,
Network = 1,
System = 2,
Application = 3,
diff --git a/src/Core/Insight.Domain/Insight.Domain.csproj b/src/Core/Insight.Domain/Insight.Domain.csproj
index 88c6256..31bc155 100644
--- a/src/Core/Insight.Domain/Insight.Domain.csproj
+++ b/src/Core/Insight.Domain/Insight.Domain.csproj
@@ -1,25 +1,25 @@
- net7.0
- true
+ net8.0
+ latest
+ enable
enable
Insight.Domain
Insight
- 2023.12.14.0
+ 2023.12.15.0
+ none
+
+
+
+
+ 9193
-
-
+
+
+
-
-
- none
-
-
-
- none
-
\ No newline at end of file
diff --git a/src/Core/Insight.Domain/Models/Result.cs b/src/Core/Insight.Domain/Models/Result.cs
index 85f6934..5e07353 100644
--- a/src/Core/Insight.Domain/Models/Result.cs
+++ b/src/Core/Insight.Domain/Models/Result.cs
@@ -1,5 +1,4 @@
using MessagePack;
-using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
@@ -31,17 +30,17 @@ public class Result
}
[IgnoreDataMember]
- public Exception? Exception { get; init; }
+ public Exception? Exception { get; set; }
[IgnoreDataMember]
- [MemberNotNullWhen(true, nameof(Exception))]
+ //[MemberNotNullWhen(true, nameof(Exception))]
public bool HadException => Exception is not null;
[DataMember]
- public bool IsSuccess { get; init; }
+ public bool IsSuccess { get; set; }
[DataMember]
- public string Reason { get; init; } = string.Empty;
+ public string Reason { get; set; } = string.Empty;
public static Result Fail(string reason)
@@ -130,19 +129,19 @@ public class Result
}
[IgnoreDataMember]
- public Exception? Exception { get; init; }
+ public Exception? Exception { get; set; }
[IgnoreDataMember]
- [MemberNotNullWhen(true, nameof(Exception))]
+ //[MemberNotNullWhen(true, nameof(Exception))]
public bool HadException => Exception is not null;
[DataMember]
- [MemberNotNullWhen(true, nameof(Value))]
- public bool IsSuccess { get; init; }
+ //[MemberNotNullWhen(true, nameof(Value))]
+ public bool IsSuccess { get; set; }
[DataMember]
- public string Reason { get; init; } = string.Empty;
+ public string Reason { get; set; } = string.Empty;
[DataMember]
- public T? Value { get; init; }
+ public T? Value { get; set; }
}
diff --git a/src/Core/Insight.Domain/Models/Token.cs b/src/Core/Insight.Domain/Models/Token.cs
index 44718f3..280373d 100644
--- a/src/Core/Insight.Domain/Models/Token.cs
+++ b/src/Core/Insight.Domain/Models/Token.cs
@@ -27,28 +27,17 @@ public class TokenResponse
public string? RefreshToken { get; set; }
}
-public class TokenRevokeRequest
+public class TokenRevokeRequest(string token, string? reason)
{
[JsonPropertyName("token"), Required]
- public string? Token { get; set; }
+ public string? Token { get; set; } = token;
[JsonPropertyName("reason")]
- public string? Reason { get; set; }
-
- public TokenRevokeRequest(string token, string? reason)
- {
- Token = token;
- Reason = reason;
- }
+ public string? Reason { get; set; } = reason;
}
-public class TokenRefreshRequest
+public class TokenRefreshRequest(string token)
{
[JsonPropertyName("token"), Required]
- public string? Token { get; set; }
-
- public TokenRefreshRequest(string token)
- {
- Token = token;
- }
+ public string? Token { get; set; } = token;
}
\ No newline at end of file
diff --git a/src/Core/Insight.Domain/Network/Agent/Messages/Interface.cs b/src/Core/Insight.Domain/Network/Agent/Messages/Interface.cs
index 3c985b6..241d7da 100644
--- a/src/Core/Insight.Domain/Network/Agent/Messages/Interface.cs
+++ b/src/Core/Insight.Domain/Network/Agent/Messages/Interface.cs
@@ -182,6 +182,6 @@ public partial class IPAddress2 : IMessage
IsIPv6Multicast = address.IsIPv6Multicast;
IsIPv6SiteLocal = address.IsIPv6SiteLocal;
IsIPv6Teredo = address.IsIPv6Teredo;
- IsIPv6UniqueLocal = address.IsIPv6UniqueLocal;
+ //IsIPv6UniqueLocal = address.IsIPv6UniqueLocal;
}
}
\ No newline at end of file
diff --git a/src/Core/Insight.Domain/Network/IMessage.cs b/src/Core/Insight.Domain/Network/IMessage.cs
index 39da489..35421e8 100644
--- a/src/Core/Insight.Domain/Network/IMessage.cs
+++ b/src/Core/Insight.Domain/Network/IMessage.cs
@@ -6,10 +6,6 @@ namespace Insight.Domain.Network;
[MemoryPackUnion(0, typeof(Agent.Messages.AuthenticationRequest))]
[MemoryPackUnion(1, typeof(Agent.Messages.AuthenticationResponse))]
[MemoryPackUnion(2, typeof(Agent.Messages.InventoryRequest))]
-//[MemoryPackUnion(3, typeof(Agent.Messages.ConsoleQueryRequest))]
-//[MemoryPackUnion(4, typeof(Agent.Messages.ConsoleQueryResponse))]
-//[MemoryPackUnion(5, typeof(Proxy))]
-//[MemoryPackUnion(6, typeof(Proxy))]
[MemoryPackUnion(7, typeof(Agent.Messages.Event))]
[MemoryPackUnion(8, typeof(Agent.Messages.Trap))]
[MemoryPackUnion(9, typeof(Agent.Messages.Mainboard))]
diff --git a/src/Core/Insight.Infrastructure/Extensions/HttpRequestExtensions.cs b/src/Core/Insight.Infrastructure.Web/Extensions/HttpRequestExtensions.cs
similarity index 96%
rename from src/Core/Insight.Infrastructure/Extensions/HttpRequestExtensions.cs
rename to src/Core/Insight.Infrastructure.Web/Extensions/HttpRequestExtensions.cs
index 7d6ca72..a18fca6 100644
--- a/src/Core/Insight.Infrastructure/Extensions/HttpRequestExtensions.cs
+++ b/src/Core/Insight.Infrastructure.Web/Extensions/HttpRequestExtensions.cs
@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Http.Extensions;
namespace Insight.Infrastructure;
-public static class HttpRequestExtensions
+public static partial class HttpRequestExtensions
{
public static void AddPagination(this HttpRequest request, PagedList pagelist)
{
diff --git a/src/Core/Insight.Infrastructure.Web/Extensions/HttpResponseExtensions.cs b/src/Core/Insight.Infrastructure.Web/Extensions/HttpResponseExtensions.cs
new file mode 100644
index 0000000..b449964
--- /dev/null
+++ b/src/Core/Insight.Infrastructure.Web/Extensions/HttpResponseExtensions.cs
@@ -0,0 +1,18 @@
+using Insight.Infrastructure.Models;
+using Microsoft.AspNetCore.Http;
+using System.Text.Json;
+
+namespace Insight.Infrastructure;
+
+public static partial class HttpResponseExtensions
+{
+ private static readonly JsonSerializerOptions _options = new()
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase
+ };
+
+ public static void AddPagination(this HttpResponse response, PagedList pagelist)
+ {
+ response.Headers.Append("X-Pagination", JsonSerializer.Serialize(pagelist.Meta as PagedHeaderData, _options));
+ }
+}
\ No newline at end of file
diff --git a/src/Core/Insight.Infrastructure.Web/Extensions/MongoCollectionExtensions.cs b/src/Core/Insight.Infrastructure.Web/Extensions/MongoCollectionExtensions.cs
new file mode 100644
index 0000000..ba9c355
--- /dev/null
+++ b/src/Core/Insight.Infrastructure.Web/Extensions/MongoCollectionExtensions.cs
@@ -0,0 +1,44 @@
+using Insight.Infrastructure.Models;
+using Microsoft.AspNetCore.Http;
+using MongoDB.Bson;
+using MongoDB.Driver;
+
+namespace Insight.Infrastructure.Web;
+
+public static class MongoCollectionExtensions
+{
+ public static async Task> GetPagedAsync(
+ this IMongoCollection collection,
+ HttpRequest request,
+ HttpResponse response,
+ FilterDefinition? filter = null,
+ SortDefinition? sort = null,
+ int offset = 0,
+ int limit = 10,
+ CancellationToken cancellationToken = default)
+ {
+ var result = await Infrastructure.MongoCollectionExtensions.GetPagedAsync(collection, filter, sort, offset, limit, cancellationToken).ConfigureAwait(false);
+
+ request?.AddPagination(result);
+ response?.AddPagination(result);
+
+ return result;
+ }
+
+ public static async Task> GetPagedAsync(
+ this IMongoCollection collection,
+ HttpRequest request,
+ HttpResponse response,
+ IAggregateFluent query,
+ int offset = 0,
+ int limit = 10,
+ CancellationToken cancellationToken = default)
+ {
+ var result = await Infrastructure.MongoCollectionExtensions.GetPagedAsync(collection, query, offset, limit, cancellationToken).ConfigureAwait(false);
+
+ request?.AddPagination(result);
+ response?.AddPagination(result);
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/src/Core/Insight.Infrastructure.Web/Extensions/ServiceExtensions.cs b/src/Core/Insight.Infrastructure.Web/Extensions/ServiceExtensions.cs
new file mode 100644
index 0000000..ad9100b
--- /dev/null
+++ b/src/Core/Insight.Infrastructure.Web/Extensions/ServiceExtensions.cs
@@ -0,0 +1,229 @@
+using AspNetCore.Identity.MongoDbCore.Extensions;
+using AspNetCore.Identity.MongoDbCore.Infrastructure;
+using Insight.Infrastructure.Entities;
+using Insight.Infrastructure.Services;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.HttpOverrides;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Primitives;
+using Microsoft.IdentityModel.Tokens;
+using Microsoft.Net.Http.Headers;
+using MongoDB.Bson;
+using System.Text;
+
+namespace Insight.Infrastructure;
+
+public static partial class ServiceExtensions
+{
+ public static IServiceCollection AddTokenServices(this IServiceCollection services, IConfiguration configuration)
+ {
+ var options = new Models.TokenOptions(
+ key: configuration.GetValue(Appsettings.JwtKey) ?? throw new Exception($"{Appsettings.JwtKey} value not set (appsettings)"),
+ expires: configuration.GetValue(Appsettings.JwtExp) ?? throw new Exception($"{Appsettings.JwtExp} value not set (appsettings)"),
+ audience: configuration.GetValue(Appsettings.JwtAudience) ?? throw new Exception($"{Appsettings.JwtAudience} value not set (appsettings)"),
+ issuer: configuration.GetValue(Appsettings.JwtIssuer) ?? throw new Exception($"{Appsettings.JwtIssuer} value not set (appsettings)"));
+
+ services.AddSingleton(options);
+ services.AddTransient();
+
+ return services;
+ }
+
+ public static IServiceCollection AddProxyServices(this IServiceCollection services)
+ {
+ // add before routing
+ services.Configure(options =>
+ {
+ options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
+ });
+
+ return services;
+ }
+
+ public static IServiceCollection AddRoutingServices(this IServiceCollection services)
+ {
+ // add after proxy
+ services.AddRouting(options =>
+ {
+ options.LowercaseUrls = true;
+ });
+
+ return services;
+ }
+
+ public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration configuration)
+ {
+ var connectionString = configuration.GetValue(Appsettings.Database) ?? throw new Exception($"{Appsettings.Database} value not set (appsettings)");
+
+ services.AddIdentity