diff --git a/docs/SSMS_INTEGRATION_NOTES.md b/docs/SSMS_INTEGRATION_NOTES.md index 2ac92e5..ba134b1 100644 --- a/docs/SSMS_INTEGRATION_NOTES.md +++ b/docs/SSMS_INTEGRATION_NOTES.md @@ -42,9 +42,26 @@ To get the real tree node, you must: `SynchronizeTree` walks down the tree expanding each level. If any level isn't yet cached, it triggers a new connection to load it. This can pop up the "Connect to Server" dialog. To avoid: ensure the user has already expanded the relevant database folder in OE before calling it. -### GetConnectedServerNames via GetSelectedNodes +### Enumerating connected servers -The most reliable way to get connected servers is `oeService.GetSelectedNodes(out count, out INodeInformation[] nodes)` — but this only returns nodes the user has currently selected. For a full enumeration without user interaction, walk `treeView.Nodes` directly. +Every connected server is a root node of the tree. Walk `treeView.Nodes` and ask each root for its `INodeInformation` — the node itself is the service provider: + +```csharp +var treeView = oeControl as TreeView; // see above: cast, don't search +var nodeInfoType = ReflectionTypeCache.FindType("...ObjectExplorer.INodeInformation"); +foreach (TreeNode root in treeView.Nodes) +{ + var nodeInfo = (root as IServiceProvider)?.GetService(nodeInfoType); + var conn = nodeInfo?.GetType().GetProperty("Connection")?.GetValue(nodeInfo); + // conn.ServerName, conn.UserName, conn.Password, conn.UseIntegratedSecurity ... +} +``` + +This is `ObjectExplorerBridge.GetConnectedServerNames`. Verified on SSMS 18, 20 and 22 with several servers connected, Windows and SQL authentication — for a SQL login the root's `Connection` carries the password, so indexing and query windows work without a prompt. + +`oeService.GetSelectedNodes(out count, out INodeInformation[] nodes)` is kept only as a last resort: it returns just the nodes the user has selected, so on its own it sees one server however many are connected. That was the "only the last server loaded is usable" bug (issue #9) — the tree lookup silently failed (see *Things We Tried That Don't Work*), everything fell through to `GetSelectedNodes`, and each refresh replaced the index with the selected server alone. + +A refresh rebuilds the whole index and starts by clearing it, so `RefreshIndexAsync` is single-flight: a request arriving mid-run is queued and served by one more run. `ConnectionWatcher` likewise raises one event per poll, not one per new server. The connection extracted from a node's `Connection` property is a `SqlConnectionInfoWithConnection` — it has a live, already-authenticated connection. Never try to construct a new connection from parts; reuse this one. @@ -351,6 +368,20 @@ Two differences that each cost a long debugging session: before trusting anything else. - **`-log` takes a filename** (`-log C:\path\ActivityLog.xml`). Bare `-log` consumes the next argument as the filename, so `-log -S server` silently eats `-S`. +- **`-S ` asks first.** SSMS 22 shows a *"Connect to the following server?"* Yes/No + prompt inside the main window before connecting; nothing is connected until it is answered. + SSMS 18/20 (`-S -E`) connect straight away. + +### Driving a multi-server test through UI Automation + +To get a second server into Object Explorer: `File > Connect Object Explorer...`. On SSMS 22 +that opens a WPF `Connect` window (`Server Name` / `Authentication` / `User Name` / `Password` +elements, button id `OkButton`); on 18/20 it is the WinForms `Connect to Server` dialog, whose +`Authentication:` combo is a drop-down list (focus it and type the first letter) and whose +user field is labelled `Login:` once SQL authentication is selected. Two LocalDB instances +(`sqllocaldb create `) make a cheap pair of servers, and LocalDB accepts SQL logins. +The pane itself exposes `IndexStatus`, `SearchTextBox`, `ResultsListBox`, `ScopeButton` and +`RefreshButton` as automation ids. ### Autoload: NoSolution is not enough on SSMS 22 @@ -399,6 +430,8 @@ For user-visible messages, use the SQL Pilot status bar (`IndexStatus.Text`). ## Things We Tried That Don't Work - **`Process.Modules` as a "did the extension load?" check** — managed assemblies loaded by a package don't reliably appear there; it reported "not loaded" for an extension that was demonstrably running. Drive the real UI instead: send Ctrl+D and look for the `SQL Pilot` pane through UI Automation — after first confirming the window you attached to is the IDE and not a dialog (see *SSMS 22's command line*). +- **`FindChildOfType(oeControl)` to locate the Object Explorer tree** — `Tree` *is* the `TreeView` and has no child controls, so the search returns null without any error. Server enumeration then quietly fell back to `GetSelectedNodes`, which looks fine with one server and breaks with two. Cast `Tree` directly. +- **`IObjectExplorerService.GetNodeInformation(treeNode)` via reflection** to get a root's connection — it sat behind the lookup above and never ran. Use `(root as IServiceProvider).GetService(INodeInformation)`. - **DTE commands** for Edit Top N Rows: `Query.EditTopNRows`, `ObjectExplorer.EditTopNRows`, etc. — none exist in SSMS - **`DesignTableOrView(DocumentType.OpenTable)`** — fails at `GetDsRef` on all three SSMS versions. Use `OpenTableHelperClass.EditTopNRows` instead - **ScheduleSqlScriptAsOneStep** — opens the SQL Agent Job Schedule dialog, not a query diff --git a/src/SqlPilot.Package/Integration/ObjectExplorerBridge.cs b/src/SqlPilot.Package/Integration/ObjectExplorerBridge.cs index 427c754..5f0b150 100644 --- a/src/SqlPilot.Package/Integration/ObjectExplorerBridge.cs +++ b/src/SqlPilot.Package/Integration/ObjectExplorerBridge.cs @@ -63,56 +63,50 @@ private object GetObjectExplorerControl() return treeProp?.GetValue(oes); } - private TreeView FindTreeView() - { - ThreadHelper.ThrowIfNotOnUIThread(); - - var oeControl = GetObjectExplorerControl(); - if (oeControl is Control control) - return FindChildOfType(control); - - return null; - } - - private static T FindChildOfType(Control parent) where T : Control - { - foreach (Control child in parent.Controls) - { - if (child is T match) return match; - var found = FindChildOfType(child); - if (found != null) return found; - } - return null; - } + private const string NodeInformationTypeName = + "Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.INodeInformation"; + /// + /// Every server connected in Object Explorer, whichever node is selected. + /// Also refreshes the cached connection for each one. + /// public IReadOnlyList GetConnectedServerNames() { ThreadHelper.ThrowIfNotOnUIThread(); var results = new List(); - // Try WinForms TreeView first - var treeView = FindTreeView(); - if (treeView != null) + // Tree IS the TreeView (ObjectExplorerControl derives from it) -- it has no + // child controls, so searching its Controls for one finds nothing. + if (GetObjectExplorerControl() is TreeView treeView) { - foreach (TreeNode node in treeView.Nodes) + var nodeInfoType = ReflectionTypeCache.FindType(NodeInformationTypeName); + + foreach (TreeNode root in treeView.Nodes) { - string serverName = TryGetServerFromNode(node); - if (string.IsNullOrEmpty(serverName)) - serverName = ParseServerNameFromText(node.Text); - if (!string.IsNullOrEmpty(serverName)) + // A root we can't read a connection from is skipped rather than + // listed by its node text: with no connection it could only be + // indexed as an empty server. + string serverName = TryGetServerFromRootNode(root, nodeInfoType); + if (!string.IsNullOrEmpty(serverName) && !ContainsServer(results, serverName)) results.Add(serverName); } } - else - { - // Fallback: use GetSelectedNodes API + + // Last resort: only sees the nodes the user has selected. + if (results.Count == 0) TryGetFromSelectedNodes(results); - } return results; } + private static bool ContainsServer(List servers, string serverName) + { + foreach (var s in servers) + if (string.Equals(s, serverName, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + public ConnectionDescriptor GetConnectionInfo(string serverName) { _connectionCache.TryGetValue(serverName, out var conn); @@ -137,7 +131,7 @@ public string ResolveUrnServerName(string logicalServerName) var oeControl = GetObjectExplorerControl(); if (!(oeControl is TreeView treeView)) return logicalServerName; - var inodeInfoType = ReflectionTypeCache.FindType("Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.INodeInformation"); + var inodeInfoType = ReflectionTypeCache.FindType(NodeInformationTypeName); if (inodeInfoType == null) return logicalServerName; foreach (TreeNode root in treeView.Nodes) @@ -182,7 +176,7 @@ public System.Collections.Generic.List GetCandidateUrnServerNames(string var oeControl = GetObjectExplorerControl(); if (!(oeControl is TreeView treeView)) { candidates.Add(logicalServerName); return candidates; } - var inodeInfoType = ReflectionTypeCache.FindType("Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.INodeInformation"); + var inodeInfoType = ReflectionTypeCache.FindType(NodeInformationTypeName); if (inodeInfoType == null) { candidates.Add(logicalServerName); return candidates; } string bestMatch = null; @@ -219,27 +213,19 @@ public System.Collections.Generic.List GetCandidateUrnServerNames(string return candidates; } - private string TryGetServerFromNode(TreeNode node) + private string TryGetServerFromRootNode(TreeNode root, Type nodeInfoType) { - ThreadHelper.ThrowIfNotOnUIThread(); - try { - var oes = GetObjectExplorerService(); - if (oes == null) return null; - - var getNodeInfoMethod = oes.GetType().GetMethod("GetNodeInformation", - BindingFlags.Public | BindingFlags.Instance); - if (getNodeInfoMethod == null) return null; - - var nodeInfo = getNodeInfoMethod.Invoke(oes, new object[] { node }); - if (nodeInfo == null) return null; + // OE tree nodes hand out their INodeInformation as a service. + if (nodeInfoType == null || !(root is IServiceProvider sp)) return null; - return ExtractConnectionFromNodeInfo(nodeInfo); + var nodeInfo = sp.GetService(nodeInfoType); + return nodeInfo == null ? null : ExtractConnectionFromNodeInfo(nodeInfo); } catch (Exception ex) { - Debug.WriteLine($"SqlPilot: GetNodeInformation error: {ex.Message}"); + Debug.WriteLine($"SqlPilot: root node connection error: {ex.Message}"); return null; } } @@ -303,13 +289,6 @@ private string ExtractConnectionFromNodeInfo(object nodeInfo) return serverName; } - private static string ParseServerNameFromText(string text) - { - if (string.IsNullOrEmpty(text)) return null; - int parenIdx = text.IndexOf(" (", StringComparison.Ordinal); - return parenIdx > 0 ? text.Substring(0, parenIdx).Trim() : text.Trim(); - } - public bool NavigateToObject(string serverName, string databaseName, string schemaName, string objectName, string objectType) { ThreadHelper.ThrowIfNotOnUIThread(); diff --git a/src/SqlPilot.Package/Services/ConnectionWatcher.cs b/src/SqlPilot.Package/Services/ConnectionWatcher.cs index 727e442..e56d25e 100644 --- a/src/SqlPilot.Package/Services/ConnectionWatcher.cs +++ b/src/SqlPilot.Package/Services/ConnectionWatcher.cs @@ -8,7 +8,7 @@ namespace SqlPilot.Package.Services { /// /// Polls Object Explorer every few seconds for new server connections. - /// When a new server is detected, fires the ServerConnected event. + /// Fires ServersConnected once per poll in which new servers turned up. /// public sealed class ConnectionWatcher : IDisposable { @@ -17,7 +17,7 @@ public sealed class ConnectionWatcher : IDisposable private readonly HashSet _knownServers = new HashSet(StringComparer.OrdinalIgnoreCase); private bool _disposed; - public event Action ServerConnected; + public event Action ServersConnected; public ConnectionWatcher(SqlPilotPackage package, int intervalMs = 3000) { @@ -38,14 +38,20 @@ private void OnTick(object state) var servers = _package.ObjectExplorerBridge.GetConnectedServerNames(); + bool anyNew = false; foreach (var server in servers) { if (_knownServers.Add(server)) { Debug.WriteLine($"SqlPilot: New server detected: {server}"); - ServerConnected?.Invoke(server); + anyNew = true; } } + + // One event however many servers appeared: a refresh re-indexes + // every connected server anyway. + if (anyNew) + ServersConnected?.Invoke(); }); } catch (Exception ex) diff --git a/src/SqlPilot.Package/SqlPilotPackage.cs b/src/SqlPilot.Package/SqlPilotPackage.cs index d5b59a9..683cea0 100644 --- a/src/SqlPilot.Package/SqlPilotPackage.cs +++ b/src/SqlPilot.Package/SqlPilotPackage.cs @@ -97,7 +97,7 @@ protected override async Task InitializeAsync( // Start polling for new server connections _connectionWatcher = new ConnectionWatcher(this); - _connectionWatcher.ServerConnected += OnServerConnected; + _connectionWatcher.ServersConnected += OnServersConnected; // Check for updates: fire-and-forget; all I/O runs off the UI thread. // Throttled to once per 24h via LastUpdateCheckUtc; timestamp is persisted @@ -130,7 +130,7 @@ protected override async Task InitializeAsync( }); } - private void OnServerConnected(string serverName) + private void OnServersConnected() { _ = JoinableTaskFactory.RunAsync(async () => { diff --git a/src/SqlPilot.Package/SqlPilotToolWindowControl.xaml.cs b/src/SqlPilot.Package/SqlPilotToolWindowControl.xaml.cs index b105c12..8f264cf 100644 --- a/src/SqlPilot.Package/SqlPilotToolWindowControl.xaml.cs +++ b/src/SqlPilot.Package/SqlPilotToolWindowControl.xaml.cs @@ -20,6 +20,8 @@ public partial class SqlPilotToolWindowControl : UserControl { private readonly SqlPilotPackage _package; private UpdateInfo _pendingUpdate; + private bool _refreshRunning; + private bool _refreshQueued; public SearchViewModel ViewModel { get; } @@ -57,7 +59,37 @@ private void ToggleScopePanel() SearchPanel.FocusSearchBox(); } + /// + /// Rebuild the whole index. Single-flight: a refresh starts by clearing the index, + /// so two overlapping runs would wipe each other's work. A request that arrives + /// mid-run (the watcher spotting another server, a second Refresh click) is + /// remembered and served by one more run afterwards. UI thread only. + /// public async Task RefreshIndexAsync() + { + if (_refreshRunning) + { + _refreshQueued = true; + return; + } + + _refreshRunning = true; + try + { + do + { + _refreshQueued = false; + await RefreshIndexCoreAsync(); + } + while (_refreshQueued); + } + finally + { + _refreshRunning = false; + } + } + + private async Task RefreshIndexCoreAsync() { try { @@ -68,7 +100,7 @@ public async Task RefreshIndexAsync() if (servers.Count == 0) { - IndexStatus.Text = "No servers connected. Select a server in Object Explorer and click Refresh."; + IndexStatus.Text = "No servers connected. Connect to a server in Object Explorer."; return; }