How To : Create SQL Server Management Studio Addin

原文 How To : Create SQL Server Management Studio Addin

Read the full and original article from Jon Sayce Here

In the last post I talked about How To: Create Windows Live Messenger Addin

Now let’s create SQL Server Management Studio Addin.

Start:

Let’s open Visual Studio and create a new Visual Studio Add-in project.

Check the right options for your Addin.

After you finish the wizard please add new Setup project.

Add Project output  -> Primary output and change the output group registration to vsdrpCOM

Enter to Registry Editor and add your Addin to SSMS startup.

References

There’s extensive documentation on MSDN regarding Visual Studio’s EnvDTE object model, which is at the heart of Visual Studio add-in development, and most of this applies to SSMS. Most UI elements are the same for both environments but if your add-in relates to anything SQL-specific then you’re going to need references to SSMS assemblies and the documentation on these is non-existent.

IDTExtensibility2 Events

Once you’ve got the references sorted out, you’re ready to start coding.

The template class that Visual Studio has created implements the IDTExtensibility2 interface, but only one of the methods has any code in it so far: OnConnection.

OnConnection “occurs whenever an add-in is loaded into Visual Studio” according to MSDN – in our case the event will fire whenever you start SSMS, once the add-in is installed.

OnConnection will probably be the most important method of the interface for your add-in, but the others can be useful if you need to save settings as the add-in is unloaded or something similar.

SSMS Events

Handling SSMS events is one of the trickier aspects of writing the add-in, the problem being that you don’t know what events there are to handle. I suspect Reflector could help here, but the method I used was suggested by Sean.

To add a handler to an event we need to know the command to which that event belongs. The easiest way to find this is to loop through the commands and look for the name which sounds most like what you’re after.

For Each com As Command In _DTE.Commands
   Debug.WriteLine(String.Format("Name={0} | GUID={1} | ID={2}", com.Name, com.Guid, com.ID))
Next

Now we complete our Addin infrastructure we can start writing some code!!!

Edit Connect.vb and add a MessageBox inside OnStartupComplete method.

Build the project and install the Addin, open SSMS and this is what you should see.

Add New Menu Item

Under Connect Class change to :
Implements the constructor for the Add-in object

Implements IDTExtensibility2
Implements IDTCommandTarget
 
Private _DTE2 As DTE2
Private _DTE As DTE
Private _addInInstance As AddIn
 
Private _CommandEvents As CommandEvents
 
Private _CommandBarControl As CommandBarControl
 
Private Const COMMAND_NAME As String = "MySSMSAddinCommand"

OnConnection Method:
get the events for the command we’re interested in (the GUID comes from the output of the previous debug command)
 NOTE: if the _CommandEvents object goes out of scope then the handler will not longer be attached to the event, so it must be a private class-level declaration rather than a local one.

Public Sub OnConnection(ByVal application As Object, ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, ByRef custom As Array) Implements IDTExtensibility2.OnConnection
       _DTE2 = CType(application, DTE2)
       _DTE = CType(application, DTE)
       _addInInstance = CType(addInInst, AddIn)
 
       _CommandEvents = _DTE.Events.CommandEvents("{84125960-B63C-3794-B5D3-9BC47A513E8D}", 1)
   End Sub

OnDisconnection Method: - 
Checks whether the control in the tools menu is there if so delete the menu item.

Public Sub OnDisconnection(ByVal disconnectMode As ext_DisconnectMode, ByRef custom As Array) Implements IDTExtensibility2.OnDisconnection
        Try
            If Not (_CommandBarControl Is Nothing) Then
                _CommandBarControl.Delete()
            End If
        Catch
        End Try
    End Sub

QueryStatus Method:
called when the command’s availability is updated

Public Sub QueryStatus(ByVal commandName As String, ByVal neededText As vsCommandStatusTextWanted, ByRef status As vsCommandStatus, ByRef commandText As Object) Implements IDTCommandTarget.QueryStatus
       If neededText = vsCommandStatusTextWanted.vsCommandStatusTextWantedNone Then
           If commandName = _addInInstance.ProgID & "." & COMMAND_NAME Then
               status = CType(vsCommandStatus.vsCommandStatusEnabled + vsCommandStatus.vsCommandStatusSupported, vsCommandStatus)
           Else
               status = vsCommandStatus.vsCommandStatusUnsupported
           End If
       End If
   End Sub

OnStartupComplete Method:

Public Sub OnStartupComplete(ByRef custom As Array) Implements IDTExtensibility2.OnStartupComplete
        Dim myCommand As Command = Nothing
 
        ‘ -----------------------------------
        ‘ 1. Check whether the command exists
        ‘ -----------------------------------
 
        ‘ try to retrieve the command, in case it was already created
        Try
            myCommand = _DTE.Commands.Item(_addInInstance.ProgID & "." & COMMAND_NAME)
        Catch
            ‘ this just means the command wasn‘t found
        End Try
 
        ‘ ----------------------------------
        ‘ 2. Create the command if necessary
        ‘ ----------------------------------
 
        If myCommand Is Nothing Then
            myCommand = _DTE.Commands.AddNamedCommand(_addInInstance, COMMAND_NAME, "MySSMSAddin MenuItem", "Tooltip for your command", True, 0, Nothing, vsCommandStatus.vsCommandStatusSupported Or vsCommandStatus.vsCommandStatusEnabled)
        End If
 
        ‘ ------------------------------------------------------------------------------------
        ‘ 3. Get the name of the tools menu (may not be called "Tools" if we‘re not in English
        ‘ ------------------------------------------------------------------------------------
 
        Dim toolsMenuName As String
        Try
 
            ‘ If you would like to move the command to a different menu, change the word "Tools" to the 
            ‘ English version of the menu. This code will take the culture, append on the name of the menu
            ‘ then add the command to that menu. You can find a list of all the top-level menus in the file
            ‘ CommandBar.resx.
            Dim resourceManager As System.Resources.ResourceManager = New System.Resources.ResourceManager("MySSMSAddin.CommandBar", System.Reflection.Assembly.GetExecutingAssembly())
 
            Dim cultureInfo As System.Globalization.CultureInfo = New System.Globalization.CultureInfo(_DTE2.LocaleID)
            toolsMenuName = resourceManager.GetString(String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools"))
 
        Catch e As Exception
            ‘We tried to find a localized version of the word Tools, but one was not found.
            ‘  Default to the en-US word, which may work for the current culture.
            toolsMenuName = "Tools"
        End Try
 
        ‘ ---------------------
        ‘ 4. Get the Tools menu
        ‘ ---------------------
 
        Dim commandBars As CommandBars = DirectCast(_DTE.CommandBars, CommandBars)
        Dim toolsCommandBar As CommandBar = commandBars.Item(toolsMenuName)
 
        ‘ -------------------------------------------------
        ‘ 5. Create the command bar control for the command
        ‘ -------------------------------------------------
 
        Try
            ‘Find the appropriate command bar on the MenuBar command bar:
            _CommandBarControl = DirectCast(myCommand.AddControl(toolsCommandBar, toolsCommandBar.Controls.Count + 1), CommandBarControl)
            _CommandBarControl.Caption = "MySSMSAddin"
        Catch argumentException As System.ArgumentException
            ‘If we are here, then the exception is probably because a command with that name
            ‘  already exists. If so there is no need to recreate the command and we can 
            ‘  safely ignore the exception.
        End Try
    End Sub

Build and Install

Add New Window

Let’s make our menu item a functioning menu item. 
First add new UserControl to the project

Modify the UserControl to your needs.

Add this code into Exec Method in Connect.vb
Define a new window as container for the UserControl.

Public Sub Exec(ByVal commandName As String, ByVal executeOption As vsCommandExecOption, ByRef varIn As Object, ByRef varOut As Object, ByRef handled As Boolean) Implements IDTCommandTarget.Exec
    handled = False
    If executeOption = vsCommandExecOption.vsCommandExecOptionDoDefault Then
        If commandName = _addInInstance.ProgID & "." & COMMAND_NAME Then
 
            ‘ get windows2 interface
            Dim MyWindow As Windows2 = CType(_DTE2.Windows, Windows2)
 
            ‘ get current assembly
            Dim asm As Assembly = System.Reflection.Assembly.GetExecutingAssembly
 
            ‘ create the window
            Dim MyControl As Object = Nothing
            Dim toolWindow As Window = MyWindow.CreateToolWindow2(_addInInstance, asm.Location, "MySSMSAddin.MyAddinWindow", "MySMSAddin Window", "{5B7F8C1C-65B9-2aca-1Ac3-12AcBbAF21d5}", MyControl)
            toolWindow.Visible = True
 
            handled = True
 
        End If
    End If
End Sub

Download MySSMSAddin Project

时间: 2024-10-09 13:45:12

How To : Create SQL Server Management Studio Addin的相关文章

Sql Server系列:Microsoft SQL Server Management Studio模板资源管理器

模板资源管理器是Microsoft SQL Server Management Studio的一个组件,可以用来SQL代码模板,使用模板提供的代码,省去每次都要输入基本代码的工作. 使用模板资源管理器的步骤: 1>. 打开Microsoft SQL Server Management Studio主界面之后,选择[视图]->[模板资源管理器],打开[模板浏览器]窗口. 2>. 模板资源管理器按代码类型进行分组,可以双击打开Database目录下的Create Database模板,查看如

教程:SQL Server Management Studio

此工具由 Microsoft Visual Studio, Management Studio 内部承载,它提供了用于数据库管理的图形工具和功能丰富的开发环境.通过 Management Studio,您可以在同一个工具中访问和管理数据库引擎.Analysis Manager 和 SQL 查询分析器,并且能够编写 Transact-SQL.MDX.XMLA 和 XML 语句.  学习内容 熟悉 Management Studio 的最好方式是进行实践演练.本教程将讲述如何管理 Managemen

SQL Server Management Studio中:黑SQLCMD模式

注意: 这篇文章是专门针对人们已经熟悉了SQLCMD模式在SQL Server Management Studio中.虽然不是非常新颖的,读者应该明白SQLCMD文档中的基本功能. 若对DOS命令Shell有一个基本的了解,也将让你更好的理解下面这些例子. 步骤概述: 本文用于处理动态生成文件,虽然我们在同一个脚本中创建和运行文件,但是随着复杂度的提升结果将会难以预测.所以,公在允许意外丢失的情况下运行该例子. 不,SQLCMD我已经试过了... 如果你像我一样,你可能花了数年进出SQL Ser

SQL Server 2014 日志传送部署(4):SQL Server Management Studio部署日志传送

13.2.4 使用Management Studio部署日志传送 使用SQL Server Management Studio来部署日志传送步骤如下: (1)打开主服务器SQLSVR1中作为日志传送的主数据库DB01的属性页面,,然后选择"事务日志传送".选中"将此数据库启用为日志传送配置中的主数据库(E)"复选框. (2)点击"备份设置": 1.填写"备份文件夹网络路径"为\\192.168.1.20\backlog; 2.

[转]删除SQL Server Management Studio中保存的帐户信息

http://www.2cto.com/database/201208/149850.html 删除SQL Server Management Studio中保存的帐户信息 SQL Server 2005 Management Studio 删除以下路径中的mru.dat文件 2003/XP C:\Documents and Settings\Administrator\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\

使用SQL Server Management Studio 创建数据库备份作业

SQL Server 作业无非就是按照规定的时间执行指定的脚本,这里介绍如何用SSMS(SQL Sever 2008)创建作业备份数据库. (0)假设在创建作业之前你所要备份的数据库已经存在:其次,你已经会启动SQL Sever 代理(一般是关闭的) (1)创建SQL Server代理作业 (1.1)新建作业,输出常规信息 如上图:输入作业名称(如:BackupJobTest),这里所有者和类别都是默认的,输入说明(就跟写代码要写注释一样,利人利己) (1.2)设置作业执行步骤 点击左边“选择页

SQL Server Management Studio Keyboard shortcuts

一些平时在SQL Server Management Studio 使用到的快捷键 F5 (Ctrl+x)执行选中部分的语句,没有选中则全文执行 Ctrl+L 现实执行计划(估计) Ctrl+M 在运行后后显示执行计划(实际) Shift+Alt+S 现实统计信息(实际) Ctrl+J 手动智能提示 Tab,Shift+Tab 选中语句进行增加或者减少缩进 CTRL+SHIFT+U,CTRL+SHIFT+L 进行语句的大小写调整.注意WHERE字句中的条件字符也会被改写 By MSDN:SQL

SQL Server R2 2008中的SQL Server Management Studio 阻止保存要求重新创建表的更改问题的设置方法

在2008中会加入阻止保存要求重新创建表的更改这个选项.症状表现为修改表结构的时候会"阻止"你. SQL Server 2008“阻止保存要求重新创建表的更改”的错误的解决方案是本文我们主要要介绍的内容,情况是这样的:我们在用SQL Server 2008 建完表后,插入或修改任意列时,提示:当用户在在SQL Server 2008企业管理器中更改表结构时,必须要先删除原来的表,然后重新创建新表,才能完成表的更改. 如果强行更改会出现以下提示:不允许保存更改.您所做的更改要求删除并重新

MS SQL Server Management Studio中提示不允许保长度出现不允许保存更改。您所做的更改要求删除并重新创建以下表

在SQL Server Management Studio中直接修改正在连接的表结构会出现改不了的情况,如下图 解决方法:工具-选项-设计器--阻止保存要求重新创建表的更改,去掉对勾--确定即可