September 29, 2010

fun with outlook add-ins

Creating an Outlook 2007 add-in using a Visual Studio Tools for Office (VSTO) template was pretty straightforward for the most part. That is, until it came time for me to deploy it on another machine.

I encountered two halting problems with deploying the add-in, and after some extensive Googling for the answers I realized that there are dozens of potential solutions out there, and each and every solution is different. "Such is the problem with VSTO development," said a co-worker.

In the event that some other poor soul out there is trying to develop an Outlook add-in in C# (when 95% of the online code samples are in VB.NET) and is running into similar problems... I give you my solutions:

Problem 1: Actually getting Outlook to pick up the add-in in the first place. That's right, my first problem was that I could only debug it on my own machine, but when it came time to deploy my add-in, Outlook decided it wouldn't cooperate.

The reason: The add-in did not have sufficient permissions to run. Now, I think there is a complicated way to go about fixing this where you make a whole extra project in your add-in solution that automatically sets permissions... BUT, for my purposes I wanted something quick and to-the-point.

The solution:
  • In the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\Outlook\Addins\[your add-in name], the entry 'LoadBehavior' should be 3. If it's not, set it to 3
  • In the command line, execute
    CasPol.exe -m -ag My_Computer_Zone -url "[path to add-in]\*" FullTrust -n My_AddIn_URL_Policy(CasPol is located in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727)
  • Then, type this command to view any errors in a dialog box when Outlook starts up (very helpful if something should go wrong): set VSTO_SUPPRESSDISPLAYALERTS=0, then open OUTLOOK.EXE from the command line

Problem 2: The Items.ItemAdd event was not triggering. In the ThisAddIn_Startup() method, I locate the folder I want and then set the event handler like so:
myFolder.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);



And again, debugging on my own machine worked, but deploying on another machine did not work. What is the deal, VSTO?

The reason: The folder items (i.e. emails) that are being monitored by this event handler need to be stored as a global variable, or else the event handler gets garbage collected. This seems to be a 'known issue'.



The solution:
Create a global "Outlook.Items myFolderItems", then back in the ThisAddIn_Startup() method change the event handler assignment to deal with the global variable instead:
this.myFolderItems = this.myFolder.Items; this.myFolderItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);


Happy VSTO'ing.