Monday, September 15, 2008

Creating a VS.Net 2008 Addin

In trying to take the RTF Converter to a new level, I decided to create it as an Addin. As this is my first time creating an add in, I decided to share what I have learned.

VS 2008 has a Project wizard that is used to create the project that works quite well when trying to debug your add in, but when trying to actually run it, doesn't work at all. Some of the Enumerations that happen when running the addin in debug mode, never happen when trying to run it for real.

Some other issues that I ran into was a complete lack of examples for creating a link on the right click menu of the code. I did find a website and was able to add mix and match it with the auto generated code from the wizard to come up with a workable solution.

The first step in creating an Add in, is to Implement the Extensibility.IDTExtensibility2 interface and IDTCommand Target. There are three main functions that you need to be concerned about

1. OnConnection()
- This function gets called either when VS starts, or when the app is loaded. This is where code that is needed to either add your add int to the tool bar, or (as in my case) add it as a CommandBarPopup( Basically a menu that has children commands that pop out to the side). You have to find the "Code Window" Command bar, then add a CommandBarPopup, then add any commands that you want to have displayed.
I refactored a new AddContextMenuChildItem method to handle adding the new commands that I wanted to implement to my context menu. On of the most confusing parts was trying to determine what I call the IconId to use. I ended up having to create a tempory project that created every single icon that was possible, to go through and select the ones that made the most sense. I know you can add your own personal icons, but I didn't have the time or the patience.
I also ran into an issu with the command already existing if I opened up another version of VS, but not being added to the PopupBar. So I had to add extra logic if it already exists, to just add it. I guess I should probably change this even further to check to see if it exists first, not the other way around.

2. QueryStatus()
- This function is used to hide or show items. I wanted to show the Convert Selected option, only if something was selected, so I had to add logic for this. If you always wanted them to be displayed, I think you could always just return true.

3. Exec()
- This is the function that gets fired when the command gets clicked. It takes some simple logic to determine what got clicked, and then I'm on my way.

The source code is listed below. Hopefully this will be helpful for others.


using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.CommandBars;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Windows.Forms;
namespace CodeToHtml

/// <summary>The object for implementing an Add-in.</summary>
/// <seealso class='IDTExtensibility2' />
public class Connect : IDTExtensibility2, IDTCommandTarget

private const string ConvertSelection = "ConvertSelectionToHtml";
private const string OpenWindowForConvert = "OpenConversionWindow";
private bool hasBeenLoaded = false;

/// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
public Connect()



/// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
/// <param term='application'>Root object of the host application.</param>
/// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
/// <param term='addInInst'>Object representing this Add-in.</param>
/// <seealso class='IDTExtensibility2' />
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)

try {
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
//if (connectMode == ext_ConnectMode.ext_cm_UISetup) { //For some Reason, this never gets called, so I've changed it
if (connectMode != ext_ConnectMode.ext_cm_CommandLine) {
object[] contextGUIDS = new object[] { };
Commands2 commands = (Commands2)_applicationObject.Commands;

string toolsMenuName;

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.
string resourceName;
ResourceManager resourceManager = new ResourceManager("CodeToHtml.CommandBar", Assembly.GetExecutingAssembly());
CultureInfo cultureInfo = new CultureInfo(_applicationObject.LocaleID);

if (cultureInfo.TwoLetterISOLanguageName == "zh") {
System.Globalization.CultureInfo parentCultureInfo = cultureInfo.Parent;
resourceName = String.Concat(parentCultureInfo.Name, "Tools");
}
else {
resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools");
}
toolsMenuName = resourceManager.GetString(resourceName);
}
catch {
//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";
}

//Place the command on the tools menu.
//Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:
Microsoft.VisualStudio.CommandBars.CommandBar codeWindowContextCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["Code Window"];

CommandBarPopup toolsPopup = (CommandBarPopup)codeWindowContextCommandBar.Controls.Add(MsoControlType.msoControlPopup, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
toolsPopup.Caption = "Code To Html";
//This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,
// just make sure you also update the QueryStatus/Exec method to include the new command names.
AddContextMenuChildItem(ref contextGUIDS, commands, toolsPopup, ConvertSelection, 223, "Convert Selection To HTML", "Converts the selected code to html");
AddContextMenuChildItem(ref contextGUIDS, commands, toolsPopup, OpenWindowForConvert, 178, "Open HTML Convert Window", "Opens a window to paste text in to convert");
hasBeenLoaded = true;
}

}
catch(Exception ex) {
MessageBox.Show(ex.ToString(), "Code To HTML");
}


private void AddContextMenuChildItem(ref object[] contextGUIDS, Commands2 commands, CommandBarPopup toolsPopup, string name, int iconId, string buttonText, string helpText) {
try {
//Add a command to the Commands collection:
Command command = commands.AddNamedCommand2(_addInInstance, name, buttonText, helpText, true, iconId, 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) && (toolsPopup != null)) {
command.AddControl(toolsPopup.CommandBar, toolsPopup.CommandBar.accChildCount + 1);
}
else if(command == null){
MessageBox.Show("Command Was Null", "Code To HTML");
}
else
MessageBox.Show("Tools Popup Was Null", "Code To HTML");
}
}
catch (System.ArgumentException) {
if(!hasBeenLoaded){
// For some reason this was having issues adding the command, so if it already exists, I need to re-add it to the Command Bar.
foreach(Command command in commands){
if (command.Name == "CodeToHtml.Connect." + name) {
command.AddControl(toolsPopup.CommandBar, toolsPopup.CommandBar.accChildCount + 1);
return;
}
}

MessageBox.Show("Shows exists, when it hasn't been loaded", "Code To HTML");
}
}
}

/// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>
/// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)



/// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnAddInsUpdate(ref Array custom)



/// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnStartupComplete(ref Array custom)



/// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
public void OnBeginShutdown(ref Array custom)



/// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary>
/// <param term='commandName'>The name of the command to determine state for.</param>
/// <param term='neededText'>Text that is needed for the command.</param>
/// <param term='status'>The state of the command in the user interface.</param>
/// <param term='commandText'>Text requested by the neededText parameter.</param>
/// <seealso class='Exec' />
public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)

try {
//if (neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone) {
if (commandName == "CodeToHtml.Connect." + OpenWindowForConvert || commandName == "CodeToHtml.Connect." + ConvertSelection && UserHasTextSelected(false)) {
status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled;
return;
}
//}
//MessageBox.Show(commandName + " not supported\n" + neededText.ToString());
} catch (Exception ex) {
MessageBox.Show(ex.ToString(), "Code To HTML");
}


/// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
/// <param term='commandName'>The name of the command to execute.</param>
/// <param term='executeOption'>Describes how the command should be run.</param>
/// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
/// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
/// <param term='handled'>Informs the caller if the command was handled or not.</param>
/// <seealso class='Exec' />
public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)

handled = false;
if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)

switch (commandName.Substring(commandName.LastIndexOf('.') + 1))
{
case OpenWindowForConvert:
RTF2HTMLConverter.RTF2HTMLForm form = new RTF2HTMLConverter.RTF2HTMLForm();
form.Show();
handled = true;
break;
case ConvertSelection:
if(UserHasTextSelected(true)){
((
EnvDTE.TextSelection)_applicationObject.ActiveDocument.Selection).Copy();
string text = Clipboard.GetText(System.Windows.Forms.TextDataFormat.Rtf);
Clipboard.SetText(RTF2HTMLConverter.ConvertLogic.GetFormattedHtml(text));
}
break;
}



private bool UserHasTextSelected(bool assertError) {
string error = string.Empty;
if(_applicationObject.ActiveDocument == null){
error = "No Document Selected";
}
else if (_applicationObject.ActiveDocument.Selection == null) {
error = "Nothing Selected";
}
else {
try {
EnvDTE.TextSelection text = (EnvDTE.TextSelection)_applicationObject.ActiveDocument.Selection;
if (text.Text == string.Empty) {
error = "No Text Selected";
}
}
catch {
error = "No Text Selected";
}
}

if(error != string.Empty){
if(assertError){
MessageBox.Show(error, "CodeToHtml");
}
return false;
}
else
return true;
}
}
private DTE2 _applicationObject;
private AddIn _addInInstance;




3 comments:

Kevin Berridge said...

I've noticed that the templates that come with VS2008 do not use the IDTExtensibility2 interface anymore (like they used to in VS2003). Why did you use the Extensibility Interface?

Also, did you install your AddIn with a .NET setup project? If so, how did you set that up?

Daryl said...

Kevin,

I'm not sure what options you're selecting, but with the options I selected, the VS2008 template did use the IDTExtensibility2 interface by default.

I did not create a .net setup project since I don't think too many people would be interested in it. I just installed it manually. All you have to do is place a configuration file with the extension .AddIn, in one of the folders listed in the Tools/Options/"AddIn/Macros Security" file paths. VS puts one in there for testing when you create the project, you'll need to remove that one and put the real file that you want to use in its place.

Since you are the first person to ever comment on my blog, congratualtions! If you don't mind, how did you find it, and do you have any suggestions on what I can do to make it more user friendly/readable. Thanks.

Kevin Berridge said...

Daryl, I found your blog via a google search.

As for suggestions, the only thing I noticed was that in Firefox the content of this post isn't wrapping. But it works fine in IE. Other than that, I'm in the same situation with my blog, so I got nothing :)