namespace RadeonResetBugFixService.Devices { using System; using System.Collections.Generic; using System.Management; using System.Threading; using System.Threading.Tasks; using Contracts; class DeviceHelper { private static T GetProperty(PropertyDataCollection properties, string key) { try { return (T)properties[key].Value; } catch (Exception) { return default; } } private static Guid GuidTryParse(string input) { Guid.TryParse(input, out var result); return result; } private static DeviceInfo ConvertDeviceInfo(PropertyDataCollection deviceProperties) { return new DeviceInfo { ClassGuid = GuidTryParse(GetProperty(deviceProperties, "ClassGuid")), ClassName = GetProperty(deviceProperties, "PNPClass") ?? string.Empty, DeviceId = GetProperty(deviceProperties, "PNPDeviceId") ?? string.Empty, ErrorCode = GetProperty(deviceProperties, "ConfigManagerErrorCode"), IsPresent = GetProperty(deviceProperties, "Present"), Manufacturer = GetProperty(deviceProperties, "Manufacturer") ?? string.Empty, Name = GetProperty(deviceProperties, "Name") ?? string.Empty, Service = GetProperty(deviceProperties, "Service") ?? string.Empty, }; } public static IEnumerable GetDevices() { ManagementPath path = new ManagementPath { Server = ".", NamespacePath = @"root\CIMV2", RelativePath = @"Win32_PnPentity", }; using (var devs = new ManagementClass(new ManagementScope(path), path, new ObjectGetOptions(null, TimeSpan.FromMinutes(1), false))) { ManagementObjectCollection moc = devs.GetInstances(); foreach (ManagementObject mo in moc) { /*Console.WriteLine("==================================="); Console.WriteLine("New device: " + mo.Path.Path); PropertyDataCollection devsProperties = mo.Properties; foreach (PropertyData devProperty in devsProperties) { if (devProperty.Type != CimType.DateTime) { Console.WriteLine("Property = {0}\tValue = {1}\tType={2}", devProperty.Name, devProperty.Value, devProperty.Value?.GetType()?.Name); } }*/ yield return ConvertDeviceInfo(mo.Properties); } } } public static void DisableDevice(DeviceInfo deviceInfo) { RunWithTimeout( () => ThirdParty.DisableDevice.DeviceHelper.SetDeviceEnabled(deviceInfo.ClassGuid, deviceInfo.DeviceId, false), TimeSpan.FromSeconds(50)); } public static void EnableDevice(DeviceInfo deviceInfo) { RunWithTimeout( () => ThirdParty.DisableDevice.DeviceHelper.SetDeviceEnabled(deviceInfo.ClassGuid, deviceInfo.DeviceId, true), TimeSpan.FromSeconds(50)); } public static bool? IsDeviceCurrentlyDisabled(DeviceInfo deviceInfo) { return ThirdParty.DisableDevice.DeviceHelper.IsDeviceDisabled(deviceInfo.ClassGuid, deviceInfo.DeviceId); } private static void RunWithTimeout(Action action, TimeSpan timeout) { Exception localException = null; Task.WaitAny( Task.Run(() => { try { action(); } catch (Exception e) { localException = new Exception("Exception from action", e); } }), Task.Delay(timeout)); if (localException != null) { throw localException; } } } }