From 6dae80550ef1bb7039ef69aa059f03dfd107e2dc Mon Sep 17 00:00:00 2001 From: PrimeBuild Date: Sun, 15 Nov 2026 15:10:41 +0100 Subject: [PATCH 1/2] Add Remove Ghost Devices action Lists non-present devices (CfgMgr32, CM_Get_DevNode_Status returning CR_NO_SUCH_DEVNODE) in a checkbox dialog and uninstalls the selected ones with CM_Uninstall_DevNode. Presence is checked again right before removal, software-enumerated devices (ROOT, SWD, HTREE, SW, UMB, GUID buses) are not pre-selected, and the action is disabled for offline driver stores. The driver list is refreshed afterwards so packages left unused show up. Refs #345 --- Rapr/DSEForm.cs | 100 ++++++++++++++++++++++++++++ Rapr/GhostDevicesForm.cs | 99 +++++++++++++++++++++++++++ Rapr/Lang/Language.resx | 39 +++++++++++ Rapr/Utils/ConfigManager.cs | 87 +++++++++++++++++++++--- Rapr/Utils/GhostDevice.cs | 41 ++++++++++++ RaprTests/Utils/GhostDeviceTests.cs | 47 +++++++++++++ 6 files changed, 402 insertions(+), 11 deletions(-) create mode 100644 Rapr/GhostDevicesForm.cs create mode 100644 Rapr/Utils/GhostDevice.cs create mode 100644 RaprTests/Utils/GhostDeviceTests.cs diff --git a/Rapr/DSEForm.cs b/Rapr/DSEForm.cs index 9412be6c..d437ddc3 100644 --- a/Rapr/DSEForm.cs +++ b/Rapr/DSEForm.cs @@ -49,6 +49,7 @@ public partial class DSEForm : Form private Status currentStatus = Status.Normal; private bool statusRequiresReview; private ToolStripMenuItem themeMenu; + private ToolStripMenuItem removeGhostDevicesToolStripMenuItem; private static readonly IUpdateManager UpdateManager = CreateUpdateManager(); @@ -243,6 +244,7 @@ private void UpdateDriverStore(IDriverStore driverStore) this.buttonSelectUnusedDrivers.Enabled = driverStore.SupportDeviceNameColumn; this.ctxMenuSelectOldDrivers.Enabled = driverStore.SupportDeviceNameColumn; this.ctxMenuSelectUnusedDrivers.Enabled = driverStore.SupportDeviceNameColumn; + this.removeGhostDevicesToolStripMenuItem.Enabled = driverStore.Type == DriverStoreType.Online; switch (driverStore.Type) { @@ -415,6 +417,12 @@ private void SetupOptionsMenu() } this.optionsStripMenuItem.DropDownItems.Add(this.themeMenu); + + this.removeGhostDevicesToolStripMenuItem = new ToolStripMenuItem(Language.ResourceManager.GetString("Menu_File_Remove_Ghost_Devices", Language.Culture)); + this.removeGhostDevicesToolStripMenuItem.Click += this.RemoveGhostDevicesToolStripMenuItem_Click; + this.fileToolStripMenuItem.DropDownItems.Insert( + this.fileToolStripMenuItem.DropDownItems.IndexOf(this.toolStripSeparator4), + this.removeGhostDevicesToolStripMenuItem); } private void ApplyTheme(IThemeColors palette) @@ -1404,6 +1412,96 @@ private void ExportAllDriverListToolStripMenuItem_Click(object sender, EventArgs ExportDriverList(this.lstDriverStoreEntries.Objects); } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Any failure is logged and shown to the user instead of ending the app.")] + private async void RemoveGhostDevicesToolStripMenuItem_Click(object sender, EventArgs e) + { + if (this.driverStore.Type != DriverStoreType.Online) + { + return; + } + + List ghostDevices; + try + { + this.StartOperation(); + this.ShowStatus(Status.Normal, Language.ResourceManager.GetString("Status_Scanning_Ghost_Devices", Language.Culture)); + ghostDevices = await Task.Run(() => ConfigManager.GetGhostDevices()).ConfigureAwait(true); + } + catch (Exception ex) + { + this.ShowStatus(Status.Error, ex.Message, ex.ToString(), true); + return; + } + finally + { + this.EndOperation(); + } + + if (ghostDevices.Count == 0) + { + this.ShowStatus(Status.Normal, Language.ResourceManager.GetString("Message_No_Ghost_Devices", Language.Culture), usePopup: true); + return; + } + + List selected; + using (var form = new GhostDevicesForm(ghostDevices) { RightToLeft = this.RightToLeft, RightToLeftLayout = this.RightToLeftLayout }) + { + if (form.ShowDialog(this) != DialogResult.OK) + { + this.UpdateCheckedItemSize(); + return; + } + + selected = form.SelectedDevices; + } + + if (selected.Count == 0 + || DialogResult.OK != this.ShowMessageBox( + string.Format(Language.ResourceManager.GetString("Message_Confirm_Remove_Ghost_Devices", Language.Culture), selected.Count), + Language.Message_Title_Warning, + MessageBoxButtons.OKCancel, + MessageBoxIcon.Warning, + MessageBoxDefaultButton.Button2)) + { + this.UpdateCheckedItemSize(); + return; + } + + try + { + this.StartOperation(); + this.ShowStatus(Status.Normal, Language.ResourceManager.GetString("Status_Removing_Ghost_Devices", Language.Culture)); + var failed = await Task.Run(() => selected.Where(device => !ConfigManager.TryRemoveGhostDevice(device.InstanceId)).ToList()).ConfigureAwait(true); + + if (failed.Count == 0) + { + this.ShowStatus( + Status.Success, + string.Format(Language.ResourceManager.GetString("Message_Remove_Ghost_Devices_Success", Language.Culture), selected.Count), + usePopup: true); + } + else + { + string message = string.Format(Language.ResourceManager.GetString("Message_Remove_Ghost_Devices_Error", Language.Culture), failed.Count, selected.Count); + this.ShowStatus( + Status.Error, + $"{message}{Environment.NewLine}{string.Join(Environment.NewLine, failed)}", + usePopup: true); + } + } + catch (Exception ex) + { + this.ShowStatus(Status.Error, ex.Message, ex.ToString(), true); + } + finally + { + this.EndOperation(); + } + + // Packages that only served the removed devices now show up as unused. + await this.PopulateUIWithDriverStoreEntries().ConfigureAwait(true); + } + private void RunAsAdminToolStripMenuItem_Click(object sender, EventArgs e) { DSEFormHelper.RunAsAdministrator(); @@ -1691,6 +1789,7 @@ private void StartOperation() this.buttonSelectUnusedDrivers.Enabled = false; this.buttonExportAllDrivers.Enabled = false; this.chooseDriverStoreToolStripMenuItem.Enabled = false; + this.removeGhostDevicesToolStripMenuItem.Enabled = false; this.exportAllDriverListToolStripMenuItem.Enabled = false; this.languageToolStripMenuItem.Enabled = false; this.optionsStripMenuItem.Enabled = false; @@ -1713,6 +1812,7 @@ private void EndOperation() this.buttonSelectUnusedDrivers.Enabled = this.driverStore.SupportDeviceNameColumn; this.buttonExportAllDrivers.Enabled = this.driverStore.SupportExportAllDrivers && this.lstDriverStoreEntries.Objects != null; this.chooseDriverStoreToolStripMenuItem.Enabled = true; + this.removeGhostDevicesToolStripMenuItem.Enabled = this.driverStore.Type == DriverStoreType.Online; this.exportAllDriverListToolStripMenuItem.Enabled = this.lstDriverStoreEntries.Objects != null; this.languageToolStripMenuItem.Enabled = true; this.optionsStripMenuItem.Enabled = true; diff --git a/Rapr/GhostDevicesForm.cs b/Rapr/GhostDevicesForm.cs new file mode 100644 index 00000000..30aaf136 --- /dev/null +++ b/Rapr/GhostDevicesForm.cs @@ -0,0 +1,99 @@ +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; + +using Rapr.Lang; +using Rapr.Utils; + +namespace Rapr +{ + /// + /// Lists ghost devices with checkboxes so the user picks which ones to remove. + /// Built in code because its texts have no generated Language properties yet. + /// + public class GhostDevicesForm : Form + { + private readonly ListView listView; + private readonly Button buttonRemove; + + public GhostDevicesForm(IEnumerable devices) + { + this.Text = GetString("GhostDevices_Title"); + this.Font = SystemFonts.MessageBoxFont; + this.ClientSize = new Size(760, 440); + this.MinimumSize = new Size(480, 300); + this.StartPosition = FormStartPosition.CenterParent; + this.MinimizeBox = false; + this.ShowInTaskbar = false; + this.ShowIcon = false; + + var layout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 1, RowCount = 3, Padding = new Padding(8) }; + // A fixed-width column lets the description wrap and keeps the buttons inside the window. + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + layout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + layout.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + layout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + + var description = new Label + { + AutoSize = true, + Anchor = AnchorStyles.Left | AnchorStyles.Right, + Margin = new Padding(3, 3, 3, 8), + Text = GetString("GhostDevices_Description"), + }; + + this.listView = new ListView + { + Dock = DockStyle.Fill, + View = View.Details, + CheckBoxes = true, + FullRowSelect = true, + HideSelection = false, + }; + this.listView.Columns.Add(GetString("GhostDevices_Column_Name")); + this.listView.Columns.Add(GetString("GhostDevices_Column_Class")); + this.listView.Columns.Add(GetString("GhostDevices_Column_InstanceId")); + + foreach (var device in devices.OrderBy(d => d.ClassName).ThenBy(d => d.Name)) + { + this.listView.Items.Add(new ListViewItem(new[] { device.Name ?? device.InstanceId, device.ClassName, device.InstanceId }) + { + Tag = device, + Checked = device.SelectedByDefault, + }); + } + + // Column widths need the window handle, so size them once the form is loaded. + this.Load += (sender, e) => this.listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); + this.listView.ItemChecked += (sender, e) => this.buttonRemove.Enabled = this.listView.CheckedItems.Count > 0; + + this.buttonRemove = new Button + { + AutoSize = true, + DialogResult = DialogResult.OK, + Text = GetString("GhostDevices_Remove"), + Enabled = this.listView.CheckedItems.Count > 0, + }; + var buttonCancel = new Button { AutoSize = true, DialogResult = DialogResult.Cancel, Text = Language.Button_Cancel }; + + var buttons = new FlowLayoutPanel { AutoSize = true, Anchor = AnchorStyles.Right, FlowDirection = FlowDirection.LeftToRight }; + buttons.Controls.Add(this.buttonRemove); + buttons.Controls.Add(buttonCancel); + + layout.Controls.Add(description, 0, 0); + layout.Controls.Add(this.listView, 0, 1); + layout.Controls.Add(buttons, 0, 2); + this.Controls.Add(layout); + + this.AcceptButton = this.buttonRemove; + this.CancelButton = buttonCancel; + DriverStoreTheme.Attach(this); + } + + public List SelectedDevices => + this.listView.CheckedItems.Cast().Select(item => (GhostDevice)item.Tag).ToList(); + + private static string GetString(string name) => Language.ResourceManager.GetString(name, Language.Culture) ?? name; + } +} diff --git a/Rapr/Lang/Language.resx b/Rapr/Lang/Language.resx index 9f0dfc63..032e9e2b 100644 --- a/Rapr/Lang/Language.resx +++ b/Rapr/Lang/Language.resx @@ -621,4 +621,43 @@ Continue selecting drivers? Dark + + Remove &Ghost Devices... + + + Remove Ghost Devices + + + These devices are installed but not connected. Removing one deletes its device entry; Windows installs it again if the device is connected later. Software-created devices (ROOT, SWD, HTREE, ...) are not selected by default because some of them are needed even while hidden. + + + Device + + + Class + + + Instance ID + + + &Remove + + + Scanning for ghost devices... + + + Removing ghost devices... + + + No ghost devices found. + + + Remove {0} ghost device(s)? This cannot be undone. + + + {0} ghost device(s) removed. + + + {0} of {1} ghost device(s) could not be removed: + diff --git a/Rapr/Utils/ConfigManager.cs b/Rapr/Utils/ConfigManager.cs index fa3be488..551b92bd 100644 --- a/Rapr/Utils/ConfigManager.cs +++ b/Rapr/Utils/ConfigManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; @@ -36,16 +37,7 @@ public static List GetDeviceDriverInfo() { List deviceDriverInfos = new List(); - var deviceIds = GetDeviceIds( - () => - { - int length = 0; - var result = NativeMethods.CM_Get_Device_ID_List_Size(ref length, null, CM_GETIDLIST_FILTER.NONE); - return (result, length); - }, - buffer => NativeMethods.CM_Get_Device_ID_List(null, buffer, buffer.Length / sizeof(char), CM_GETIDLIST_FILTER.NONE)); - - foreach (var deviceId in deviceIds) + foreach (var deviceId in GetAllDeviceIds()) { uint devInst = 0; var locateResult = NativeMethods.CM_Locate_DevNode( @@ -76,6 +68,73 @@ public static List GetDeviceDriverInfo() return deviceDriverInfos; } + /// + /// Lists devices that are installed but not connected (non-present devnodes). + /// + public static List GetGhostDevices() + { + var ghostDevices = new List(); + + foreach (var deviceId in GetAllDeviceIds()) + { + uint devInst = 0; + if (NativeMethods.CM_Locate_DevNode(ref devInst, deviceId, CM_LOCATE_DEVNODE_FLAG.CM_LOCATE_DEVNODE_PHANTOM) != ConfigManagerResult.Success + || !GhostDevice.IsGhost(IsDevicePresent(devInst))) + { + continue; + } + + ghostDevices.Add(new GhostDevice( + deviceId, + GetDevNodeProperty(devInst, DeviceHelper.DEVPKEY_Device_FriendlyName) + ?? GetDevNodeProperty(devInst, DeviceHelper.DEVPKEY_Device_DeviceDesc), + GetDevNodeProperty(devInst, DeviceHelper.DEVPKEY_Device_Class))); + } + + return ghostDevices; + } + + /// + /// Uninstalls a non-present device. Present devices are never touched. Failures are logged and reported as false. + /// + public static bool TryRemoveGhostDevice(string deviceId) + { + uint devInst = 0; + var result = NativeMethods.CM_Locate_DevNode(ref devInst, deviceId, CM_LOCATE_DEVNODE_FLAG.CM_LOCATE_DEVNODE_PHANTOM); + if (result == ConfigManagerResult.Success) + { + // Check again: the device may have been connected since the scan. + if (!GhostDevice.IsGhost(IsDevicePresent(devInst))) + { + Trace.TraceWarning($"Skipped ghost device {deviceId}: it is present now."); + return false; + } + + result = NativeMethods.CM_Uninstall_DevNode(devInst, 0); + } + + if (result != ConfigManagerResult.Success) + { + Trace.TraceError($"Failed to remove ghost device {deviceId}: {result}"); + return false; + } + + Trace.TraceInformation($"Removed ghost device {deviceId}"); + return true; + } + + private static string[] GetAllDeviceIds() + { + return GetDeviceIds( + () => + { + int length = 0; + var result = NativeMethods.CM_Get_Device_ID_List_Size(ref length, null, CM_GETIDLIST_FILTER.NONE); + return (result, length); + }, + buffer => NativeMethods.CM_Get_Device_ID_List(null, buffer, buffer.Length / sizeof(char), CM_GETIDLIST_FILTER.NONE)); + } + private static string[] GetDeviceIds( Func<(ConfigManagerResult Result, int Length)> getSize, Func getList) @@ -110,8 +169,11 @@ private static string[] GetDeviceIds( private static bool? IsDevicePresent(uint devInst) { - ConfigManagerResult result = NativeMethods.CM_Get_DevNode_Status(out _, out _, devInst, 0); + return PresenceFromStatus(NativeMethods.CM_Get_DevNode_Status(out _, out _, devInst, 0)); + } + private static bool? PresenceFromStatus(ConfigManagerResult result) + { if (result == ConfigManagerResult.Success) { return true; @@ -348,6 +410,9 @@ internal static extern ConfigManagerResult CM_Get_DevNode_Status( out uint problemNumber, uint devInst, uint ulFlags); + + [DllImport("CfgMgr32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern ConfigManagerResult CM_Uninstall_DevNode(uint devInst, uint ulFlags); } } } diff --git a/Rapr/Utils/GhostDevice.cs b/Rapr/Utils/GhostDevice.cs new file mode 100644 index 00000000..d42a41f4 --- /dev/null +++ b/Rapr/Utils/GhostDevice.cs @@ -0,0 +1,41 @@ +using System; +using System.Linq; + +namespace Rapr.Utils +{ + /// + /// A device that is installed but not connected (a non-present devnode). + /// + public class GhostDevice + { + // Devices created by software rather than detected on a bus. Some are hidden on purpose + // and still needed (virtual adapters, app-created devices), so they are never pre-selected. + private static readonly string[] SoftwareEnumeratorPrefixes = { @"ROOT\", @"SWD\", @"HTREE\", @"SW\", @"UMB\", "{" }; + + public string InstanceId { get; } + + public string Name { get; } + + public string ClassName { get; } + + public bool SelectedByDefault => IsSelectedByDefault(this.InstanceId); + + public GhostDevice(string instanceId, string name, string className) + { + this.InstanceId = instanceId; + this.Name = name; + this.ClassName = className; + } + + /// + /// Only a devnode known to be absent is a ghost; an unknown status is treated as present. + /// + public static bool IsGhost(bool? isPresent) => isPresent == false; + + public static bool IsSelectedByDefault(string instanceId) => + !string.IsNullOrEmpty(instanceId) + && !SoftwareEnumeratorPrefixes.Any(prefix => instanceId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); + + public override string ToString() => $"{this.Name} ({this.ClassName}) - {this.InstanceId}"; + } +} diff --git a/RaprTests/Utils/GhostDeviceTests.cs b/RaprTests/Utils/GhostDeviceTests.cs new file mode 100644 index 00000000..abe30afd --- /dev/null +++ b/RaprTests/Utils/GhostDeviceTests.cs @@ -0,0 +1,47 @@ +using System; +using System.Reflection; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Rapr.Utils; + +namespace Rapr.Tests.Utils +{ + [TestClass] + public class GhostDeviceTests + { + private static readonly Func PresenceFromStatus = + (Func)typeof(ConfigManager) + .GetMethod("PresenceFromStatus", BindingFlags.Static | BindingFlags.NonPublic) + .CreateDelegate(typeof(Func)); + + [TestMethod] + [DataRow(ConfigManager.ConfigManagerResult.NoSuchDevnode, true)] + [DataRow(ConfigManager.ConfigManagerResult.Success, false)] + [DataRow(ConfigManager.ConfigManagerResult.AccessDenied, false)] + [DataRow(ConfigManager.ConfigManagerResult.Failure, false)] + public void OnlyDevnodesKnownToBeAbsentAreGhosts(ConfigManager.ConfigManagerResult statusResult, bool expected) + { + Assert.AreEqual(expected, GhostDevice.IsGhost(PresenceFromStatus(statusResult))); + } + + [TestMethod] + [DataRow(@"USB\VID_046D&PID_C52B\5&2B7E0C4&0&2", true)] + [DataRow(@"PCI\VEN_8086&DEV_15F3&SUBSYS_00008086&REV_03\3&11583659&0&E8", true)] + [DataRow(@"HID\VID_046D&PID_C52B&MI_00\7&1A2B3C4D&0&0000", true)] + [DataRow(@"BTHENUM\{0000110B-0000-1000-8000-00805F9B34FB}_LOCALMFG&0002\8&1&0", true)] + [DataRow(@"ROOT\NET\0000", false)] + [DataRow(@"root\SYSTEM\0001", false)] + [DataRow(@"SWD\MMDEVAPI\{0.0.0.00000000}.{8D4B4E2C}", false)] + [DataRow(@"HTREE\ROOT\0", false)] + [DataRow(@"SW\{EEAB7790-C514-11D1-B42B-00805FC1270E}\ASYNCMAC", false)] + [DataRow(@"UMB\UMB\1&841921D&0&PRINTQUEUE", false)] + [DataRow(@"{5D624F94-8850-40C3-A3FA-A4FD2080BAF3}\VWIFIMP_WFD\5&1&0", false)] + [DataRow("", false)] + [DataRow(null, false)] + public void SoftwareEnumeratedDevicesAreNotSelectedByDefault(string instanceId, bool expected) + { + Assert.AreEqual(expected, GhostDevice.IsSelectedByDefault(instanceId)); + } + } +} From 8873bbb5ae63bf439c6f662aa4e298afa9113374 Mon Sep 17 00:00:00 2001 From: PrimeBuild Date: Mon, 16 Nov 2026 11:50:01 +0100 Subject: [PATCH 2/2] Test the ghost device removal workflow TryRemoveGhostDevice now takes the locate, status and uninstall calls as delegates, like GetDeviceIds and ReadDevNodeProperty, so tests can check that present, unknown or unlocatable devices are never uninstalled and that uninstall failures are reported. --- Rapr/Utils/ConfigManager.cs | 25 +++++++++++--- RaprTests/Utils/GhostDeviceTests.cs | 53 +++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) diff --git a/Rapr/Utils/ConfigManager.cs b/Rapr/Utils/ConfigManager.cs index 551b92bd..e097e312 100644 --- a/Rapr/Utils/ConfigManager.cs +++ b/Rapr/Utils/ConfigManager.cs @@ -99,18 +99,35 @@ public static List GetGhostDevices() /// public static bool TryRemoveGhostDevice(string deviceId) { - uint devInst = 0; - var result = NativeMethods.CM_Locate_DevNode(ref devInst, deviceId, CM_LOCATE_DEVNODE_FLAG.CM_LOCATE_DEVNODE_PHANTOM); + return TryRemoveGhostDevice( + deviceId, + id => + { + uint devInst = 0; + var result = NativeMethods.CM_Locate_DevNode(ref devInst, id, CM_LOCATE_DEVNODE_FLAG.CM_LOCATE_DEVNODE_PHANTOM); + return (result, devInst); + }, + devInst => NativeMethods.CM_Get_DevNode_Status(out _, out _, devInst, 0), + devInst => NativeMethods.CM_Uninstall_DevNode(devInst, 0)); + } + + private static bool TryRemoveGhostDevice( + string deviceId, + Func locate, + Func getStatus, + Func uninstall) + { + var (result, devInst) = locate(deviceId); if (result == ConfigManagerResult.Success) { // Check again: the device may have been connected since the scan. - if (!GhostDevice.IsGhost(IsDevicePresent(devInst))) + if (!GhostDevice.IsGhost(PresenceFromStatus(getStatus(devInst)))) { Trace.TraceWarning($"Skipped ghost device {deviceId}: it is present now."); return false; } - result = NativeMethods.CM_Uninstall_DevNode(devInst, 0); + result = uninstall(devInst); } if (result != ConfigManagerResult.Success) diff --git a/RaprTests/Utils/GhostDeviceTests.cs b/RaprTests/Utils/GhostDeviceTests.cs index abe30afd..af96888c 100644 --- a/RaprTests/Utils/GhostDeviceTests.cs +++ b/RaprTests/Utils/GhostDeviceTests.cs @@ -15,6 +15,59 @@ public class GhostDeviceTests .GetMethod("PresenceFromStatus", BindingFlags.Static | BindingFlags.NonPublic) .CreateDelegate(typeof(Func)); + private delegate bool RemoveGhostDevice( + string deviceId, + Func locate, + Func getStatus, + Func uninstall); + + private static readonly RemoveGhostDevice TryRemove = + (RemoveGhostDevice)typeof(ConfigManager) + .GetMethod( + "TryRemoveGhostDevice", + BindingFlags.Static | BindingFlags.NonPublic, + null, + new[] + { + typeof(string), + typeof(Func), + typeof(Func), + typeof(Func), + }, + null) + .CreateDelegate(typeof(RemoveGhostDevice)); + + [TestMethod] + [DataRow(ConfigManager.ConfigManagerResult.Success, ConfigManager.ConfigManagerResult.NoSuchDevnode, ConfigManager.ConfigManagerResult.Success, true, true)] + [DataRow(ConfigManager.ConfigManagerResult.Success, ConfigManager.ConfigManagerResult.NoSuchDevnode, ConfigManager.ConfigManagerResult.RemoveVetoed, true, false)] + [DataRow(ConfigManager.ConfigManagerResult.Success, ConfigManager.ConfigManagerResult.Success, ConfigManager.ConfigManagerResult.Success, false, false)] + [DataRow(ConfigManager.ConfigManagerResult.Success, ConfigManager.ConfigManagerResult.AccessDenied, ConfigManager.ConfigManagerResult.Success, false, false)] + [DataRow(ConfigManager.ConfigManagerResult.NoSuchDevnode, ConfigManager.ConfigManagerResult.NoSuchDevnode, ConfigManager.ConfigManagerResult.Success, false, false)] + [DataRow(ConfigManager.ConfigManagerResult.InvalidDeviceId, ConfigManager.ConfigManagerResult.NoSuchDevnode, ConfigManager.ConfigManagerResult.Success, false, false)] + public void OnlyDevicesStillAbsentAreUninstalled( + ConfigManager.ConfigManagerResult locateResult, + ConfigManager.ConfigManagerResult statusResult, + ConfigManager.ConfigManagerResult uninstallResult, + bool expectUninstall, + bool expectedResult) + { + const uint devInst = 42; + uint? uninstalled = null; + + bool result = TryRemove( + @"USB\VID_0781&PID_5581\1", + id => (locateResult, devInst), + inst => statusResult, + inst => + { + uninstalled = inst; + return uninstallResult; + }); + + Assert.AreEqual(expectedResult, result); + Assert.AreEqual(expectUninstall ? devInst : (uint?)null, uninstalled); + } + [TestMethod] [DataRow(ConfigManager.ConfigManagerResult.NoSuchDevnode, true)] [DataRow(ConfigManager.ConfigManagerResult.Success, false)]