Hello Word Outlook Add-In using C#


One thing I’d like to play with is extending Outlook through add-ins with C#. It’ll be a good opportunity to learn more about .NET development and the Windows tools. Plus, I can “fix” some of the things that annoy me about Outlook. I’ve been talking to Omar about this too, and hopefully we can collaborate on a few projects. We’ve been sharing a few links back and forth on getting started. It’s a bit hard to find the right information to get started, but it’s out there. I’ve compiled steps below for a “hello world” type Outlook project that I’ll be building off in the future. I hope this will be useful to others trying to get started on developing Outlook add-ins using managed code. Please let me know if I’m missing anything or have errors.


 


Install Primary Interop Assemblies


.NET can interface with COM code using interop assemblies. You can create these as needed by adding a reference to a COM type library. However, if you do this for the Outlook/Office type libraries, this will lead to strange problems like this. This doesn’t sound like the thing I want to find out about the hard way. The solution is to install “primary interop assemblies” that live in the GAC and will be used instead of custom generated ones. You can download PIAs for Outlook XP here. For Outlook 2003, you can go to Control Panels->Add/Remove programs and customize your installation to add them. Just choose “.NET Programmability” under the various components. They are initially set to install on first use – I don’t know what would actually trigger this. Once these are installed, adding a reference to the COM type libraries will add these “magic” versions instead of generating new versions with strange issues.


 


Create a Visual Studio.NET project


Create a new Visual Studio.Net project. For the project type, select Other Projects->Extensibility Projects->Shared Add-ins (who would think to look here?). This brings you through a wizard where you can select the language (C#, of course!) and which hosts to support. One cool thing you can do with the Office COM-plugins is support multiple apps with the same plugin, but I’m only interested in Outlook for now. Then, you have the chance to fill in some other random info, and your project is created. The project will have template code that implements the IDTExtensibility2 interface required to create an add-in.


 


Add references


We need to add references to a couple of things we’ll be using. Right-click References under the add-in project, select “Add Reference”, go to the COM tab, and select Microsoft Outlook 11.0 Object Library (or Outlook 10.0 if you are using Outlook XP). If the PIA stuff worked right, when you select it in the solution explorer, the path in the properties tab should be pointing into the GAC, not into the office folder. Next, select


“Add Reference” again, and add “System.Windows.Forms” from the .NET tab. This will let us do our “Hello World” dialog.


 


Flesh out code


First, we need to add a member variable. We’ll also change the type of the application object to be the Outlook type (since we’ll only support Outlook):


 


private Microsoft.Office.Interop.Outlook.Application applicationObject;


private object addInInstance;


private CommandBarButton toolbarButton;


 


Next, we’ll update OnConnection to cast to the Outlook object type, and add some logic from kb 302901 (why isn’t this in the template if it’s the right thing to do?):


 


public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)


{    


    applicationObject = (Microsoft.Office.Interop.Outlook.Application)application;


    addInInstance = addInInst;


 


    if(connectMode != Extensibility.ext_ConnectMode.ext_cm_Startup)


    {


        OnStartupComplete(ref custom);


    }


}


 


Likewise, we’ll update OnDisconnection according to kb 302901:


 


public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)


{


    if(disconnectMode != Extensibility.ext_DisconnectMode.ext_dm_HostShutdown)


    {


        OnBeginShutdown(ref custom);


    }


    applicationObject = null;


}


 


Next, when we’re done loading, we will create a toolbar button. The version in kb 302901 is more complex because it’s generalize to work in apps other than Outlook:


 


public void OnStartupComplete(ref System.Array custom)


{


    CommandBars commandBars = applicationObject.ActiveExplorer().CommandBars;


 


    // Create a toolbar button on the standard toolbar that calls ToolbarButton_Click when clicked


    try


    {


         // See if it already exists


         this.toolbarButton = (CommandBarButton)commandBars[“Standard”].Controls[“Hello”];


    }


    catch(Exception)


    {


        // Create it


        this.toolbarButton = (CommandBarButton)commandBars[“Standard”].Controls.Add(1, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);


        this.toolbarButton.Caption = “Hello”;


        this.toolbarButton.Style = MsoButtonStyle.msoButtonCaption;


    }


    this.toolbarButton.Tag = “Hello Button”;


    this.toolbarButton.OnAction = “!<MyAddin1.Connect>”;


    this.toolbarButton.Visible = true;


    this.toolbarButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.OnToolbarButtonClick);


}


 


On shutdown, we’ll delete our toolbar button:


public void OnBeginShutdown(ref System.Array custom)


{


    this.toolbarButton.Delete(System.Reflection.Missing.Value);


    this.toolbarButton = null;


}


 


And, we’ll define the action when clicking the button:


private void OnToolbarButtonClick(CommandBarButton cmdBarbutton,ref bool cancel)


{


    System.Windows.Forms.MessageBox.Show(“Hello World”,”My Addin”);


}


 


To test it out, you build the addin project, and then the setup project. Quit Outlook, then right-click the setup project and select “Install”.  When you launch Outlook, a button named “Hello” will show up in the main toolbar. Selecting it will say “Hello World”. You can manage this add-in by going to the COM add-in dialog at Tools->Options->Other->Advanced Options->COM Add-Ins.


 


What’s missing


There are some steps that need to be taken to install the PIA when installing your add-in. See the steps here. That sample also has a lot of information about signing your plugin, which I’ve ignored so far.


 


What’s next


Next, I have to learn more about the Outlook object model and how to actually do interesting things. I also need to learn how to debug the add-ins.


 


Reference


General description of COM Add-Ins: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/modcore/html/deovrWhatIsCOMAddin.asp


A sample Visual Basic.NET plugin (describes the PIA stuff): http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnout2k2/html/odc_oladdinvbnet.asp


KB 302901 (building an Office COM plugin using Visual C#.NET): http://support.microsoft.com/?kbid=302901


Niobe, a library for Outlook managed plug-ins (I’m not sure what you get above doing it from scratch, there isn’t much documentation): http://www.gotdotnet.com/community/workspaces/workspace.aspx?ID=E7071B93-7970-4962-A4C2-D72AA2CFBCFF



Comments (33)

  1. So… uh… how much longer is it before you can write an "Make Outlook work like Entourage for the love of God" Add-in?

  2. [.NET]Outlook Addin – using C#

  3. milbertus says:

    Can’t you just debug your add in by attaching to Outlook.exe? I’ve done similar things when playing around with a Word add in, and it worked very well. When I stopped debugging (Shift+F5), VS only unloaded my add in, and didn’t kill Word (which is a big plus, especially in your case with an Outlook add in).

  4. Dan Crevier says:

    Just setting a breakpoint on the hello world dialog and attaching to Outlook didn’t seem to do it, but I haven’t tried much yet.

  5. Omar Shahine says:

    To debug you do this:

    1) Right click on your project and select properties

    2) Select Configuration Properties -> Debugging

    3) Set Debug Mode to Program

    4) Click Apply

    5) Set start application to path to Outlook.

    Make sure Outlook isn’t running. Now hit F5 to build and debug. Now your break points will get hit etc.

  6. Ron Cicotte says:

    I’ve been working on an Outlook Add-in to process payments and all was going well for a few days. I wish I had come across this page sooner though because you discuss the issues succinctly what took me several days to uncover. The problem is that suddenly I cannot debug my add-in. It simply ignores the breakpoints. I have rebuilt; re-installed; re-registered everything I can think of and still cannot get it to recognize my code. It seems as though my symbols are not being loaded though I can’t for the life of me figure out what changed.

    My addin is really quite sweet and will be a great app if I can only get my debug environment working again. Any and all suggestions are welcome.

    Thanks,

    -ron

  7. Dan Crevier says:

    Glad you found it useful. I don’t have any great suggestions for your debugging problems. If you figure it out, please post here so we can all learn from it. Also, let us know when your blog is up and your product is out! 🙂

  8. Ron Cicotte says:

    I have successfully created your version of C# "Hello World" and am able to debug it and have the following observations:

    1. I am using a new installation of .NET and Office Pro with latest updates on a new machine.

    2. When I created the demo app and added the reference to Outlook 11 library I got a second instance of the Office.dll which caused ambiguous results. This is because the template generated by VS.NET uses the Office.dll in the Frameworks 1.1 directory while the PIA Outlook.dll is in the GAC. I removed the "Office" reference installed by the .NET template.

    3. The reference to "Microsoft.Office.Interop.Outlook.Application" is incorrect in the version of Outlook.dll I used in the new installation. Instead it is called "interop.Outlook" in the Outlook 11 object library. I used the object browser to verify this. I simply replaced "Microsoft.Office.Interop.Outlook.Application" with "Outlook.Application" when declaring the applicationObject and casting the application in the OnConnection method. It appears that there is more than one version of the Outlook 11 library with the same version number (9.2). Both machines are running XP Pro and both installed Office 2003 from the MSDN DVD though one could have been from a different issue. I am going to re-install Office 2003 and see if I get a new version of the Outlook.dll

    4. When I compiled the app I got an error saying that "Exception" in the catch is ambiguous. There is an Outlook.Exception object so you need to specify "System.Exception" in the catch statements. I tried "Outlook.Exception" and got an error saying that the catch Exception must be derived from System.

    I still have no idea why the debugger failed but am now going to copy my files into the new project directory and see if the debugger still works. I will keep you posted.

  9. Dan Crevier says:

    Thanks for the info. When I first was setting things up, I ended up with multiple conflicting references too, but when I stepped through them a second time to test things out for my post, I didn’t. I wonder what the difference was.

  10. Ron Cicotte says:

    I’ve re-installed Office 2k3 and VS 2k3 on my old machine and still have the same problem even when I start totally from scratch. Something is seriously wrong here. Apparently there is something cached somewhere that is telling the VS debugger that my COM code is somewhere other than where it is.

    Evan after re-installing both When i run Outlook alone the button is created and functions correctly. When i quit Outlook and start it the button is there but does not function. If I start it using the debugger it doesn’t function and the breakpoints don’t get hit. The "?" is displayed at the breakpoint indicating that the code is not loaded. If I un-install the Add-in and restart with the debugger the button is not created and Outlook does not see my code at all.

    Do you have any idea where VS configuration parameters are stored? Clearly they are stored somewhere in the registry and not cleared during un-install because it remembered my projects after re-installing. I think I will need a full removal of VS.NET unless I can figure out why it cannot wire-up the interop and load my symbols. I could use my new computer but it is a portable and not intended for development.

  11. Ron Cicotte says:

    Another point. The outlook PIA installed on the old machine after the re-install is still the one named "Microsoft.Office.Interop.Outlook". I must have used an early version of Office 2k3 on that machine. The re-installed Office 2k3 on the new machine using the same DVD (April MSDN) now uses the same name for the Outlook.dll. The debugger still works on that machine after the re-install so it’s not related to the dll. I have verified that every debug parameter is identical on both machines. I think my only solution is to remove .NET entirely including any registry settings and re-install. Any advice on where I can look for instructions on how to safely accomplish this?

  12. Dan Crevier says:

    Unfortunately, I have no clue…

  13. Ron Cicotte says:

    Dan,

    I solved the problem but had to call Microsoft and use one of my MSDN support calls to do it.

    It turns out there is a bug in Outlook Add-in manager that prevents debugging of add-ins if any add-ins are currently in the "disabled" state. The following is a copy of my email to the MS rep that handled the case:

    Zach,

    Problem solved! Apparently the “Resiliency” key has an effect on the debugger for all add-ins not just the one affected by the Outlook request to be disabled. Deleting this key has solved the issue. Please tell me that this will be added as a bug and made available to other developers. My suggestion for a Problem Description would be:

    ”.NET debug fails with Office PIA after disabling Add-in COM dll.”

    Conditions: After receiving the following error message from Outlook :

    “Outlook experienced a serious error the last time the add-in ["your addin name"] was opened. Would you like to disable this

    add-in? To reactivate this add-in, click About Microsoft Office Outlook in the Help menu, then click Disabled Items”

    If you select yes to have Outlook disable this add-in you will be unable to debug any add-ins until this add-in is either enabled or the “Resiliency” key for this add-in is removed from the registry.

    Steps to recreate the Problem.

    Create a com add-in http://support.microsoft.com/?kbid=302901

    Open Outlook using the debug option

    After loading the addin exit outlook using the debugger to stop debugging

    Open outlook outside of Visual Studio IDE. The following error message appears:

    “Outlook experienced a serious error the last time the add-in ["MyAddin1"] was opened. Would you like to disable this add-in? To reactivate this add-in, click About Microsoft Office Outlook in the Help menu, then click Disabled Items”

    Select yes to disable the add-in

    Close Outlook and return to the IDE

    Uninstall the Addin.

    Create a second Add-in and install it.

    Attempting to debug the second add-in will result in the application starting but breakpoints will not be invoked.

    Actually attempting to debug the first add-in will also fail but this scenario more closely approximates the confusion I encountered.

    You may expect that since you “Uninstalled” the first add-in that there would be nothing remaining to prohibit installation and debugging of other add-ins even though the first add-in did cause an unexpected problem with debugging other add-ins. This is not the case. The first add-in must either be enabled using the Office Outlook Help menu as noted above or you must remove the addin entry at the following location in the registry:

    HKEY_CURRENT_USERSoftwareMicrosoftOffice11.0OutlookResiliencyDisabledItems.

    Any entry at this location will

    Even if the first add-in is uninstalled debugging will not work until the first add-in is either enabled using the Outlook Help menu or the entry in the Resiliency key is removed.

    Thank you for helping me resolve this issue. I spent 3 days trying to figure this out because I didn’t pay close enough attention to the notice at the time the add-in was first disabled. That’s my fault. But the fact that the debugger does not work for other add-ins if any add-in is in the disabled state is something I don’t think would be anticipated by most developers.

    ____________________________

    Ron Cicotte

    Data Architect/Application Developer

    Email: ron.cicotte@summerstreet.net

    Tel: (781) 820-1355

    Web: http://www.summerstreet.com

  14. B.J. says:

    I found your Blog while Googling. The example works great. Thanks for sharing. I am new to c# and I only have Office 2k on my pc. The one problem that I ran into was this error:

    Cannot implicitly convert type ‘Office.CommandBars’ to ‘Microsoft.Office.Core.CommandBars’

    It turns out that my references were to Office 10.0 and Outlook 9.0. I changed to Office 9.0 and replaced "Microsoft.Office.Core" with "Office" a few places in the code and it works super.

    Now I’m off to explore the Outlook object model to try to get this application to do some useful things…

  15. Shelly says:

    Your Artciles and Comments helped me finish my paper today, many thanks !

  16. Scott Allen says:

    I’ve found invoking System.Diagnostics.Debugger.Launch() during OnConnect is an easier way to have the debugger ready before any interesting code executes. I think programming an AddIn from .NET could be much easier than it is: http://odetocode.com/Blogs/scott/archive/2004/07/04/294.aspx.

  17. Rob says:

    Am I barking up the wrong tree with Outlook Add-ins? I need to present a custom set of folders and display my app records (i.e. DB records) in the same list-view area where e-mails are displayed. Essentially, use the Outlook UI for my data with some drag/drop interaction with Outlook. Are Outlook Add-ins the key? Or do I simulate a MAPI server?

  18. Dan Crevier says:

    To be honest, I’m not sure how to do it. I think the only way to do it through an add-in would be to create Outlook items corresponding to each of your database records. That probably wouldn’t be a good way to go.

  19. TristanK says:

    I think the comment above this one might be considered comment spam 🙂

    I was starting to pull tufts of hair out – for some reason, any Extensibility project for Office that I started on my Work machine would fail miserably as soon as it got near a CommandBar – catching the exception gave me "Object reference not set to an instance of the object".

    Based on random experimentation after reading the comments here, I removed the default "Office" reference (put there by the Wizard) from the project references (leaving just Outlook and Microsoft.Office.Core listed) , and *blammo*, it now works!

    So thanks for helping, I hope this helps someone!

  20. hughpyle says:

    Almost ready to write some code to call Groove Web Services now.

    My aim is to create an Outlook addin,…

  21. hughpyle says:

    Almost ready to write some code to call Groove Web Services now.

    My aim is to create an Outlook addin,…

  22. hughpyle says:

    Almost ready to write some code to call Groove Web Services now.

    My aim is to create an Outlook addin,…

  23. Mikel Berger says:

    Here’s a couple links to get started on an Outlook plugin for Google Calendar. Hello Word Outlook Add-In using C# Google Calendar Data API…

  24. Channel 9 says:

    I’ve blogged about this a bit. See