About Me

My photo
I'm currently the CTO for Hedgehog Technology a business dedicated to delivering Cloud based productivity solutions in Logistics

Friday, March 07, 2008

LINQ 2 Outlook - Part 2

Last night after looking at what's available on LINQ and Outlook and after trying to find some info on the web on what MS might have in mind I decided to experiment with a bit of code myself.

I noticed that most samples use the Outlook collections, which are known for their not so optimum performance when they get bigger and you need to filter out a few items (basically you have to iterate through all of the items).

In Outlook 2007 there's a new class; Outlook.Table (and Row) which allows you to get to the items in a folder and apply an SQL-like filter. This is a very clean and fast way of accessing your items. Combined with LINQ here's some code I came up with, I'm looking to further optimise that using types etc. but wanted to share this simple example anyway.


static void TableTestUsingLinqAndExtensionMethod()
{
Outlook.Application outlook = new Microsoft.Office.Interop.Outlook.Application();
Outlook.MAPIFolder folder = outlook.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

string filter = @"@SQL=""urn:schemas:httpmail:subject"" like '%devcon%'";
Outlook.Table table = folder.GetTable(filter, null);

var mailitems = from mitem in table.mailitem() select mitem;
foreach (var item in mailitems)
{
if (item[2]!=null)
Console.WriteLine("{0}", item[2].ToString());
}
.....


public static class OutlookTableExtension
{
public static IEnumerable mailitem(this Outlook.Table source)
{
if (source == null)
throw new ArgumentNullException("source");
while (source.GetNextRow()!=null)
{
yield return source.GetNextRow();
}
}
}

Try it out on some large collections and you'll see it is surprisingly fast!

3 comments:

Bogdan Chernyachuk said...

really helpfull post.
thank you!

Ed Richard said...

;-) Bogdan, if you are interested in Linq and Outlook make sure to check out the VSTO Powertools ( http://www.microsoft.com/downloads/details.aspx?FamilyId=46B6BF86-E35D-4870-B214-4D7B72B02BF9&displaylang=en ).

Some interesting blog posts here:
http://blogs.msdn.com/philliphoff/

Cheers,
Ed

Alexis said...

My friends said a lot of good words about-fixing outlook express.But some time ago I said too)).Because tool recovered all my mails in OE and composed this free of charge.Moreover it showed me how helps to solve email corruption issues.