Sunday, February 14, 2010

Adding folders to a custom Outlook store

In continuation to my earlier post on creating an Outlook store, today I shall show you how to create custom folders for the store .
I started off by trying the MSDN way, and am providing the code below. The myStore refers to the Outlook.MAPIFolder which represents the custom store.

myStore.Folders.Add("First Folder", olFolderInbox);
myStore.Folders.Add("Second Folder", olFolderInbox);


While the first line created the folder for me , the second line greeted me with an execption "Invalid argument type" . I tried replacing the olFolderInbox parameter with the other permissible parameters of  OlDefaultFolders, but without success .It took me some time to solve this problem , but what I learnt was interesting.

If you look at the Folders.Add(Name,Type ) method you shall see that the Type is an optional parameter, and if you have not worked with Office Automation earlier in C#, you might be wondering how to populate the default parameter; and there was the problem .


The following code shall create two folders for you without any exceptio
n
private object missing = Type.Missing ;
myStore.Folders.Add("First Folder", missing );
myStore.Folders.Add("Second Folder", missing ); 
The interesting thing here is the missing object .  Default parameters are not supported in C# , there is a new way for optional parameters in C# 4.0 , but I think Type.Missing can be used for default parameters .
I have not tried this in other scenarios, so if it does not work for default parameters , let me know . On the other hand if you are keen into knowing why should you use it that way, you can look up in Eric's blog .