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

69 lines
2 KiB
C#
Raw Normal View History

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