A Developer's Diary

Apr 5, 2009

Visual Studio - Writing a Add-In (plugin) with context menus

The following example demonstrates how to write a plug-in, clicking on which pops up a context menus with menu items as show in the figure




Follow the steps mentioned in the post to write a simple plugin 'Demo'. Create a new file 'MyMenuItem.cs' with the following content.


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace MyAddin1
{
internal class MyMenuItem : MenuItem
{
public MyMenuItem(String name)
: this(name, name, null, 0)
{
}

public MyMenuItem(String name, String text, EventHandler eh, int id)
: base(text, eh)
{
m_name = name;
m_id = id;
}

public String MenuName
{
get { return m_name; }
set { m_name = value; }
}

public int MyMenuID
{
get{ return m_id; }
}

private String m_name;
private int m_id;
}
}



Add another file 'MyMenu.cs'

using System;
using System.Collections.Generic;
using System.Text;

using System.Windows.Forms;
using System.Collections;

namespace MyAddin1
{
internal class MyMenu : ContextMenu
{
public MyMenu()
{
m_stackMenu = new Stack();
m_stackMenu.Push(MenuItems);
}

public Menu.MenuItemCollection CurrentMenu
{
get { return (Menu.MenuItemCollection)m_stackMenu.Peek(); }
}

public void Add(String name, String text, int id)
{
CurrentMenu.Add(new MyMenuItem(name, text, m_eh, id));
}

public void PopAll()
{
m_stackMenu.Clear();
m_stackMenu.Push(MenuItems);
}

public void PopMenu()
{
m_stackMenu.Pop();
}

public MyMenuItem PushMenu(String name, EventHandler eh)
{
m_menuitem = new MyMenuItem(name, name, eh, 0);
CurrentMenu.Add(m_menuitem);
m_stackMenu.Push(m_menuitem.MenuItems);
return m_menuitem;
}

public EventHandler EventHandler
{
get { return m_eh; }
set { m_eh = value; }
}

private Stack m_stackMenu;
private EventHandler m_eh;
private MyMenuItem m_menuitem;
}
}



Modify the OnConnection method in the file Connect.cs to make the add-in visible in the 'MenuBar' at the position 1

public void OnConnection(object application, ext_ConnectMode connectMode,
object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
if(connectMode == ext_ConnectMode.ext_cm_UISetup)
{
object[] contextGUIDS = new object[] { };
Commands2 commands = (Commands2)_applicationObject.Commands;
CommandBar bar = ((CommandBars)_applicationObject.CommandBars)["MenuBar"];

try

{
Command command = commands.AddNamedCommand2(
_addInInstance, "MyAddin1", "Demo", "Do Something", true, 59,
ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported +
(int)vsCommandStatus.vsCommandStatusEnabled,
(int)vsCommandStyle.vsCommandStylePictAndText,
vsCommandControlType.vsCommandControlTypeButton);

//Add a control for the command to the tools menu:

if(command != null)
{
command.AddControl(bar, 1);
}
}
catch(System.ArgumentException){
}
}
}



Modify Exec() method which executes whenever the command is invoked

public void Exec(string commandName, vsCommandExecOption executeOption,
ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "MyAddin1.Connect.MyAddin1")
{
ShowMenu();
handled = true;
return;
}
}
}





The ShowMenu() lists the down how the context menu structure should look like

private void ShowMenu()
{
Point pt;

try
{
CommandBar bar = ((CommandBars)_applicationObject.CommandBars)["Demo"];
CommandBarControl control = bar.Controls[1];
pt = new Point(control.Left, control.Top);
}
catch(Exception){
pt = Control.MousePosition;
}

Control window = new Control();
window.CreateControl();

MyMenu menu = new MyMenu();
// Register event handler with MyMenu

menu.EventHandler = new EventHandler(this.OnClick);

menu.PushMenu("GroupOne", menu.EventHandler);
menu.PushMenu("GroupOneMenu", menu.EventHandler);
menu.PopMenu();
menu.PopMenu();

menu.PushMenu("GroupTwo", menu.EventHandler);
menu.PushMenu("GroupTwoMenu", menu.EventHandler);
menu.PopMenu();
menu.PopMenu();

menu.PushMenu("GroupThree", menu.EventHandler);
menu.PushMenu("GroupThreeMenu1", menu.EventHandler);
menu.PushMenu("GroupThreeMenu2", menu.EventHandler);
menu.PushMenu("GroupThreeMenu3", menu.EventHandler);
menu.PopAll(); // either call PopMenu() 4 times or PopAll()

menu.Add("MenuItem1", "MenuItem1", -1);
menu.Add("MenuItem2", "MenuItem2", -2);
menu.Add("AboutDemo", "AboutMenu", -3);

menu.Show(window, pt); //displays context menu

}




Handling Click events on MenuItems

private void OnClick(Object sender, EventArgs e)
{
try
{
MyMenuItem mi = (MyMenuItem)sender;
MessageBox.Show("Hello from " + mi.MenuName);
}
catch(Exception ex){
MessageBox.Show(ex.Message, ex.Source);
}
}




Now select the Menu Item from the GroupThree




You see a message box with the message 'Hello from GroupThreeMenu3'



Your plugin is working as expected. Cheers !! :)

Read more ...

Apr 3, 2009

Visual Studio - Writing a simple Add-In (plugin)

An add-in is an extension which integrates with the Visual Studio environment and provides new functionality to it. An add-in has full access to Visual Studio (IDE) tools and APIs and can interact with them. An add-in is a compiled DLL file which can be loaded by Visual Studio when it starts.





Creating a Sample Add-In
1. Create a New → Project
2. Select Other Project Types → Extensibility → Visual Studio Add-in



3. An Add-In wizard pops up which will guide you through a series of 7 steps including the welcome page to configure your add-in









Select for creating a 'Tools' menu item. This will list the add-in in tools menu items







On clicking finish, three main files are generated for you
a) CommandBar.resx (Resource File)
b) Connect.cs (Main class file for Add-In logic)
c) WizardSample.AddIn (XML Configuration file for your add-in)


Build the solution and run the project. You will see a Visual Studio instance running within the visual studio. Click on 'Tools' and you can find your Add-In there.




Modify the function OnConnection() as below to add the plugin to 'MenuBar'


public void OnConnection(object application, ext_ConnectMode connectMode,
object addInInst, ref Array custom)
{

_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
if(connectMode == ext_ConnectMode.ext_cm_UISetup)
{
object []contextGUIDS = new object[] { };
Commands2 commands = (Commands2)_applicationObject.Commands;
CommandBar bar = ((CommandBars)_applicationObject.CommandBars)["MenuBar"];

try{
Command command = commands.AddNamedCommand2(
_addInInstance, "MyAddin1", "Demo", "Do Something", true, 59,
ref contextGUIDS,(int)vsCommandStatus.vsCommandStatusSupported+
(int)vsCommandStatus.vsCommandStatusEnabled,
(int)vsCommandStyle.vsCommandStylePictAndText,
vsCommandControlType.vsCommandControlTypeButton);

//Add a control for the command to the tools menu:

if(command != null) {
command.AddControl(bar, 1);
}
}
catch(System.ArgumentException){
}
}
}






Modify Exec() function to add some functionality to the plugin

public void Exec(string commandName, vsCommandExecOption executeOption,
ref object varIn, ref object varOut, ref bool handled)
{
handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
{
if(commandName == "MyAddin1.Connect.MyAddin1")
{
handled = true;
MessageBox.Show("Hello from Demo AddIn");

return;
}
}
}







Read more ...

Apr 1, 2009

Enjoy Your Coffee



Life is gift wrapped with beautiful cover. Most of the time we are stuck with the wrapper and forget to open the gift. We should open the cover and enjoy the gift.


A group of alumni, highly established in their careers got together to visit old university professor. Conversation soon turned into complaints about stress in work and life.

Offering his guest coffee, professor went to the kitchen and brought a large pot of coffee and assortment of cups- porcelain, plastic, glass, crystal. Some plain looking, some expensive and some exquisite, telling them to help themselves to hot coffee.

When all the student had a cup of coffee in hand professor said-
If you noticed, all the nice looking expensive cups were taken up leaving behind the plain and cheap ones. It is normal for you to want only the best for yourself But that is the source of your problem and stress.

What all of you wanted was coffee, not the cup, but you consciously want for the best cup and were eyeing each other's cup.

Now if life is coffee, than jobs, money and position in society are the cups. They are just tools to hold Life, but the quality of Life doesn’t change. Sometimes by concentrating only on the cup we fail to enjoy the coffee in it.

So don’t let the cups drive you….

Enjoy the coffee instead.


Read more ...

Glass Of Water Theory of Stress Management

A lecturer, when explaining stress management to an audience, raised a glass of water and asked, "How heavy is this glass of water?"

Answers called out ranged from 8 ounces to 20 ounces.


The lecturer replied, "The absolute weight doesn’t matter. It depends on how long you try to hold it. If I hold it for a minute, that’s not a problem. If I hold it for an hour, I’ll have an ache in my right arm. If I hold it for a day, you’ll have to call an ambulance.

In each case, it’s the same weight, but the longer I hold it, the heavier it becomes". He continued, "And that’s the way it is with stress management. If we carry our burdens all the time, sooner or later, as the burden becomes increasingly heavy, we won’t be able to carry on.

As with the glass of water, you have to put it down for a while and rest before holding it again. When we’re refreshed, we can carry on with the burden.

So, before you return home tonight, put the burden of work down. Don’t carry it home. You can pick it up tomorrow. Whatever burdens you’re carrying now, let them down for a moment if you can.

Relax, pick them up later after you’ve rested. Life is short. Enjoy it!

Read more ...

Mar 31, 2009

Advice to young programmers - Alex Stepenov (Principal Scientist, Adobe Systems)

Following is the summary of speech given by Alex Stepenov (Principal Scientist, Adobe Systems) at Adobe India on 30 Nov 2004.


Study , Study and Study
Never ever think that you have acquired all or most of the knowledge which exists in the world. Almost everybody in US at age of 14 and everybody in India at age of 24 starts thinking that he has acquired all the wisdom and knowledge that he needs. This should be strictly avoided.

You should be habituated to studies...exactly in the same way as you are habituated to brushing teeth and taking bath every morning. The habit of study must become a ‘part of your blood’. And the study should be from both the areas: CS, since it is your profession, and something from non-CS...Something which does not relate to your work. This would expand your knowledge in other field too. A regular study, everyday, is extremely essential. It does not matter whether you study of 20 minutes of 2 hours, but consistency is a must.

You should always study basics and fundamentals. There is no point in going for advanced topics. When I was at the age of 24, I wanted to do PhD in program verification, though I was not able to understand anything from that. The basic reason was that my fundamental concepts were not clear. Studying 'Algebraic Geometry’ is useless if you do not understand basics in Algebra and Geometry. Also, you should always go back and reread and re-iterate over the fundamental concepts.
What is the exact definition of ‘fundamental’? The stuff which is around for a while and which forms basic part of the concepts can be regarded as more fundamental. Of course, everybody understands what a fundamental means.


Read more ...