insight/src/Agent/Insight.Agent/Internals/Extensions.cs

68 lines
1.8 KiB
C#
Raw Normal View History

2023-09-21 18:58:32 +02:00
using System.Management;
using System.Runtime.Versioning;
2023-09-22 22:16:56 +02:00
namespace Insight.Agent;
public static class ManagmentExtensions
2023-09-21 18:58:32 +02:00
{
2023-09-22 22:16:56 +02:00
[SupportedOSPlatform("windows")]
public static HashSet<string> GetPropertyHashes(this ManagementBaseObject @object)
2023-09-21 18:58:32 +02:00
{
2023-09-22 22:16:56 +02:00
var properties = new HashSet<string>();
foreach (var property in @object.Properties)
2023-09-21 18:58:32 +02:00
{
2023-09-22 22:16:56 +02:00
properties.Add(property.Name);
}
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
return properties;
}
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
[SupportedOSPlatform("windows")]
internal static bool TryGet(this ManagementObjectSearcher searcher, out ManagementObjectCollection collection)
{
collection = searcher.Get();
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
try
2023-09-21 18:58:32 +02:00
{
2023-09-22 22:16:56 +02:00
_ = collection.Count;
return true;
2023-09-21 18:58:32 +02:00
}
2023-09-22 22:16:56 +02:00
catch (ManagementException)
2023-09-21 18:58:32 +02:00
{
2023-09-22 22:16:56 +02:00
collection.Dispose();
return false;
}
}
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
[SupportedOSPlatform("windows")]
internal static T? GetValue<T>(this ManagementObject @object, HashSet<string> properties, string key)
{
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return default;
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
if (@object[key] is not T obj)
{
return default;
2023-09-21 18:58:32 +02:00
}
2023-09-22 22:16:56 +02:00
return obj;
}
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
[SupportedOSPlatform("windows")]
internal static bool TryGetValue<T>(this ManagementBaseObject @object, HashSet<string> properties, string key, out T? value)
{
value = default;
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
if (@object is null || properties is null || key is null) return default;
if (properties.Contains(key, StringComparer.OrdinalIgnoreCase) is false) return false;
2023-09-21 18:58:32 +02:00
2023-09-22 22:16:56 +02:00
if (@object[key] is not T obj)
{
return false;
2023-09-21 18:58:32 +02:00
}
2023-09-22 22:16:56 +02:00
value = obj;
return true;
2023-09-21 18:58:32 +02:00
}
}