How do you set the connection for the activewindow (EnvDTE.Window) in a VSIX extension?

29 views Asked by At

I have been racking my brain trying to figure out how to set the SQLConnection for a VSIX designed for SSMS. The closest I have come is to cast the active window to a SqlScriptEditorControl which has a SetConnection method. The problem is this only seems to assign the SqlScriptEditorControl in SSMS19 and the changes that are applied don't actually change the connection in SSMS.

Window activeWindow = activeDocument.ActiveWindow;
SqlScriptEditorControl editorControl = activeWindow.Object as SqlScriptEditorControl;
UIConnectionInfo newInfo = getUIConnectionfromRegisteredServer(newConnection);
editorControl.SetConnection(newInfo);

Does anyone know how you can change the connection in VSIX and have it apply to the activewindow in SSMS?

What I'm expecting is to be able to assign the UICOnnectionInfo for the currently active window / active document in SSMS.

1

There are 1 answers

1
Raky On

Please try this c# code and tell me if it works for. I couldn't test because I am not having the IDE

// Get the DTE object from the Package class
EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetService(typeof(EnvDTE.DTE));

// Subscribe to the ActiveDocumentChanged event
dte.Events.DocumentEvents.ActiveDocumentChanged += OnActiveDocumentChanged;

// Method called when the active document changes
private void OnActiveDocumentChanged(Document document)
{
    if (document is EnvDTE.Window window)
    {
        try
        {
            // Try to access the SqlScriptEditorControl
            SqlScriptEditorControl editorControl = window.Object as SqlScriptEditorControl;
            if (editorControl != null)
            {
                // Get the UIConnectionInfo for your new connection
                UIConnectionInfo newInfo = getUIConnectionfromRegisteredServer(newConnection);

                // Use the appropriate method to set the connection based on SSMS version
                if (IsNewerVersionOfSSMS())
                {
                    ((EnvDTE.SqlWindow)window).CurrentServer = newInfo.ServerName;
                }
                else
                {
                    editorControl.SetConnection(newInfo);
                }
            }
        }
        catch (Exception ex)
        {
            // Handle any exceptions gracefully
            // Log or display an error message
        }
    }
}