boert03
boert03

Reputation: 195

Add-in for SQL Server 2012 Management Studio creates duplicate context menu buttons

I am creating an add-in for SQL Server 2012 Management Studio that adds custom buttons to the context menu of a table.

I've used the source code of the following project on codeplex as guidance:

SSMSAddinDenali on Codeplex

The code is the following:

void ObjectExplorerContext_CurrentContextChanged(object sender, NodesChangedEventArgs args)
{
        debug_message("ObjectExplorerContext_CurrentContextChanged::");

        try
        {
            // Getting current node context
            Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.INavigationContextProvider navigationContextProvider = (INavigationContextProvider)sender;
            INavigationContext navigationContext = (INavigationContext)navigationContextProvider.CurrentContext;

            // Find selected node node
            ObjectExplorerService objectExplorer = (ObjectExplorerService)ServiceCache.ServiceProvider.GetService(typeof(IObjectExplorerService));
            INodeInformation node = objectExplorer.FindNode(navigationContext.Context);

            debug_message(string.Format("ObjectExplorerContext_CurrentContextChanged::Selected Node {0}",navigationContext.Context));

            // Code to add extra items to the menu
            if (_tableMenu == null && _tableRegex.IsMatch(node.Context))
            {
                _tableMenu = (HierarchyObject)node.GetService(typeof(IMenuHandler));

                tableMenuItem item = new tableMenuItem();
                _tableMenu.AddChild(string.Empty, item);
            }
        }
        catch (Exception ObjectExplorerContextException)
        {
            debug_message(String.Format("ObjectExplorerContext_CurrentContextChanged::ERROR:{0}", ObjectExplorerContextException.Message));
        }
    }

If I click right on a table once there are no extra buttons. If I click a second time the buttons are added but twice. While debugging I found that the code is executed twice. (I think the method is called asynchronously.)

Unfortunately there are not many articles on creating SSMS-addins which is why I have not been able to find a solution by googling.

Can someone please help me fix this problem?

Upvotes: 1

Views: 444

Answers (1)

boert03
boert03

Reputation: 195

I've found a way to stop this from happening.

I'm using reflection to find out how many items there are in the context menu and if there is a certain amount (in my case it's 20) I will add my items. When the event is raised a second time there are more than 20 items so they won't be added.

The code I used is this:

ArrayList menuItems = PropertyHelper.GetPrivateFieldValue<ArrayList>(_tableMenu, "menuItemsInOrder");
if (menuItems.Count == 20)
{
    tableMenuItem tmi = new tableMenuItem();
    _tableMenu.AddChild(string.Empty, tmi);
}

The PropertyHelper-Class can be found here.

Upvotes: 1

Related Questions