InfiniTec - Henning Krauses Blog

Don't adjust your mind - it's reality that is malfunctioning

Searching the Global Address List - C# Edition

A long time ago, I wrote an article on How to get the Global Address List programatically. The theory behind that article is still valid, but it only features a VBScript example. Since someone from the Microsoft Exchange Forum had trouble converting it to C#, I fired up Visual Studio and hacked something together. The result is somewhat more complete than the VBScript example, because it allows access to all address lists, not just the default global address list (GAL).

Here we go:

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;

namespace AddressListSample
    public class ActiveDirectoryConnection
        public DirectoryEntry GetLdapDirectoryEntry(string path)
            return GetDirectoryEntry(path, "LDAP");

        public DirectoryEntry GetGCDirectoryEntry(string path)
            return GetDirectoryEntry(path, "GC");

        private DirectoryEntry GetDirectoryEntry(string path, string protocol)
            var ldapPath = string.IsNullOrEmpty(path) ? string.Format("{0}:", protocol) : string.Format("{0}://{1}", protocol, path);
            return new DirectoryEntry(ldapPath);

    public class ExchangeAddressListService
        private readonly ActiveDirectoryConnection _Connection;

        public ExchangeAddressListService(ActiveDirectoryConnection connection)
            if (connection == null) throw new ArgumentNullException("connection");
            _Connection = connection;

        public IEnumerable<AddressList> GetGlobalAddressLists()
            return GetAddressLists("CN=All Global Address Lists");

        public IEnumerable<AddressList> GetAllAddressLists()
            return GetAddressLists("CN=All Address Lists");
        public IEnumerable<AddressList> GetSystemAddressLists()
            return GetAddressLists("CN=All System Address Lists");

        private IEnumerable<AddressList> GetAddressLists(string containerName)
            string exchangeRootPath;
            using (var root = _Connection.GetLdapDirectoryEntry("RootDSE"))
                exchangeRootPath = string.Format("CN=Microsoft Exchange, CN=Services, {0}", root.Properties["configurationNamingContext"].Value);
            string companyRoot;
            using (var exchangeRoot = _Connection.GetLdapDirectoryEntry(exchangeRootPath))
            using (var searcher = new DirectorySearcher(exchangeRoot, "(objectclass=msExchOrganizationContainer)"))
                companyRoot = (string) searcher.FindOne().Properties["distinguishedName"][0];

            var globalAddressListPath = string.Format(containerName + ",CN=Address Lists Container, {0}", companyRoot);
            var addressListContainer = _Connection.GetLdapDirectoryEntry(globalAddressListPath);

            using (var searcher = new DirectorySearcher(addressListContainer, "(objectClass=addressBookContainer)"))
                searcher.SearchScope = SearchScope.OneLevel;
                using (var searchResultCollection = searcher.FindAll())
                    foreach (SearchResult addressBook in searchResultCollection)
                        yield return
                            new AddressList((string) addressBook.Properties["distinguishedName"][0], _Connection);

    public class AddressList
        private readonly ActiveDirectoryConnection _Connection;
        private readonly string _Path;

        private DirectoryEntry _DirectoryEntry;

        internal AddressList(string path, ActiveDirectoryConnection connection)
            _Path = path;
            _Connection = connection;

        private DirectoryEntry DirectoryEntry
                if (_DirectoryEntry == null)
                    _DirectoryEntry = _Connection.GetLdapDirectoryEntry(_Path);
                return _DirectoryEntry;

        public string Name
            get { return (string) DirectoryEntry.Properties["name"].Value; }

        public IEnumerable<SearchResult> GetMembers(params string[] propertiesToLoad)
            var rootDse = _Connection.GetGCDirectoryEntry(string.Empty);
            var searchRoot = rootDse.Children.Cast<DirectoryEntry>().First();
            using (var searcher = new DirectorySearcher(searchRoot, string.Format("(showInAddressBook={0})", _Path)))
                if (propertiesToLoad != null)
                searcher.SearchScope = SearchScope.Subtree;
                searcher.PageSize = 512;
                    using (var result = searcher.FindAll())
                        foreach (SearchResult searchResult in result)
                            yield return searchResult;
                        if (result.Count < 512) break;
                } while (true);

    internal class Program
        private static void Main()
            var connection = new ActiveDirectoryConnection();
            var service = new ExchangeAddressListService(connection);
            foreach (var addressList in service.GetGlobalAddressLists())
                Console.Out.WriteLine("addressList.Name = {0}", addressList.Name);
                foreach (var searchResult in addressList.GetMembers())
                    Console.Out.WriteLine("\t{0}", searchResult.Properties["name"][0]);

            foreach (var addressList in service.GetAllAddressLists())
                Console.Out.WriteLine("addressList.Name = {0}", addressList.Name);
                foreach (var searchResult in addressList.GetMembers())
                    Console.Out.WriteLine("\t{0}", searchResult.Properties["name"][0]);

            foreach (var addressList in service.GetSystemAddressLists())
                Console.Out.WriteLine("addressList.Name = {0}", addressList.Name);
                foreach (var searchResult in addressList.GetMembers())
                    Console.Out.WriteLine("\t{0}", searchResult.Properties["name"][0]);

The sample wraps the whole logic up into two classes: ExchangeAddressListService and AddressList. The first serves as some kind of entry point and the latter allows access to the members of a list.

Hope this helps…

Posted by Henning Krause on Tuesday, October 25, 2011 8:22 PM, last modified on Tuesday, October 25, 2011 8:22 PM
Permalink | Post RSSRSS comment feed

Setting the Homepage of an Exchange folder using the EWS Managed API

A while ago, Glen posted an article on his blog on how to set homepage of a folder using ADO and later he posted a version of that script which uses the EWS managed API to do this in this MSDN forum thread. However, he wrote it for the first version of the API, and the EWS Managed API 1.1 has a slightly different object model. Since someone on the MSDN forums had difficulties to update the script to work with the EWS Managed API 1.1, I thought I just post an updated version here:

private static void SetFolderHomePage(IEnumerable<string> pathFragments, string url, ExchangeService service)
    var folderWebviewinfoProperty = new ExtendedPropertyDefinition(14047, MapiPropertyType.Binary);
    var root = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot);
    var targetFolder = root;
    foreach (var fragment in pathFragments)
        var result = service.FindFolders(targetFolder.Id, new SearchFilter.IsEqualTo(FolderSchema.DisplayName, fragment), new FolderView(1));
        if (result.TotalCount == 0)
            throw new InvalidOperationException(string.Format("Folder fragment {0} was not found.", fragment));
        targetFolder = result.Folders[0];

    targetFolder.SetExtendedProperty(folderWebviewinfoProperty, EncodeUrl(url));

private static byte[] EncodeUrl(string url)
    var writer = new StringWriter();
    var dataSize = ((ConvertToHex(url).Length / 2) + 2).ToString("X2");

    writer.Write("02"); // Version
    writer.Write("00000001"); // Type
    writer.Write("00000001"); // Flags
    writer.Write("00000000000000000000000000000000000000000000000000000000"); // unused
    var buffer = HexStringToByteArray(writer.ToString());
    return buffer;

private static string ConvertToHex(string input)
    return string.Join(string.Empty, input.Select(c => ((int) c).ToString("x2") + "00").ToArray());

private static byte[] HexStringToByteArray(string input)
    return Enumerable
        .Range(0, input.Length/2)
        .Select(index => byte.Parse(input.Substring(index*2, 2), NumberStyles.AllowHexSpecifier)).ToArray();

You can set the homepage of a folder by calling the SetFolderHomepage method:

SetFolderHomePage(service, new[] {"InfiniTec blog"},;

Posted by Henning Krause on Wednesday, October 5, 2011 7:30 PM, last modified on Wednesday, October 5, 2011 7:34 PM
Permalink | Post RSSRSS comment feed

FindItems Helper method for the Exchange Managed API

I’ve seen quite a few samples for using the FindItems method of the EWS Managed API, either on StackOverflow or in the Exchange development forum. One of the most common error I see is that people disable paging by specifying creating an ItemView like this:

var view = new ItemView(int.MaxValue);

Don’t do that! A query using this ItemView will put a severe burden on the Exchange server if the folder being queried contains many items. The pageSize parameter is there for a reason.

Instead of querying all items at once, one should do a proper paging: Query, say, 512 items and process them. Then, query the next 512 items. Thanks to iterators in C#, the process of retrieving the items can be completely separated away from the processing.

If you are not familiar with C# iterators, have a look at this article. In essence, the yield operator allows for deferred execution, something you might heard from with regards to LINQ.

Here is a helper method which uses this technique to iterate over the contents of an Exchange folder, requesting 512 items per batch and returning them to the caller. When used properly, this method uses very little resources on the Exchange server as well as on the client. Additionally, it allows for querying the body of an item. In this case, instead of executing a FindItems request, it executes a FindItems request and a LoadPropertiesForItems request per batch.

Due to the nature of the method, you should not put the items returned from the methods in a List, as this would consume a lot of memory on the client. Instead process the items one by one.

public static class ExchangeServiceExtension
    public static IEnumerable<Item> FindItems(this ExchangeService service, WellKnownFolderName folderName, PropertySet propertySet, SearchFilter searchFilter, ItemTraversal traversal = ItemTraversal.Shallow, params KeyValuePair<PropertyDefinition, SortDirection>[] orderBy)
        return FindItems(service, new FolderId(folderName), propertySet, searchFilter, traversal, orderBy);

    public static IEnumerable<Item> FindItems(this ExchangeService service, FolderId folderId, PropertySet propertySet, SearchFilter searchFilter = null, ItemTraversal traversal = ItemTraversal.Shallow, params KeyValuePair<PropertyDefinition, SortDirection>[] orderBy)
        if (service == null) throw new ArgumentNullException("service");
        if (folderId == null) throw new ArgumentNullException("folderId");
        if (propertySet == null) throw new ArgumentNullException("propertySet");

        PropertySet propertySetToQuery;

        // If the body or unique body is requested, the FindItems method cannot be used to query the 
        // propertyset. Instead a GetItem operation is required. The propertyset IdOnly is used in this case
        // for the FindItems operation.
        if (propertySet.Contains(ItemSchema.Body) || propertySet.Contains(ItemSchema.UniqueBody))
            propertySetToQuery = PropertySet.IdOnly;
            propertySetToQuery = propertySet;

        var itemView = new ItemView(512) { PropertySet = propertySetToQuery, Traversal = traversal };
        if (orderBy != null)
            foreach (var order in orderBy)
                itemView.OrderBy.Add(order.Key, order.Value);

        bool hasMoreItems;
            var result = service.FindItems(folderId, searchFilter, itemView);
            if (propertySetToQuery == PropertySet.IdOnly)
                // Load the properties, including the body using a GetItem request.
                service.LoadPropertiesForItems(result, propertySet);
            foreach (var item in result)
                yield return item;
            hasMoreItems = result.MoreAvailable;
            itemView.Offset += 512;
        } while (hasMoreItems);

As you can see, this method uses several .NET 4.0 features: Optional parameters and extension methods. So, if you are still using .NET 2.0, you’ll need to modify the code a little bit.

To use these methods, insert this code into your solution. In the class where you want to use the methods, add a using to the namespace containing the ExchangeServiceExtension. Both methods will then appear in the code completion window on instances of the ExchangeService class:


In the following example, the method is used to iterate over all items in the Inbox folder and printing the items to the console:

var items = service.FindItems(WellKnownFolderName.Inbox, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject));

foreach (var item in items)
    Console.Out.WriteLine("Subject = {0}", item.Subject);

Since the last parameters are optional, they can be omitted. This example adds a sort clause to the call:

var items = service.FindItems(WellKnownFolderName.Inbox, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject), 
    orderBy: new KeyValuePair<PropertyDefinition, SortDirection>(ItemSchema.Subject, SortDirection.Ascending));

Of course, a SearchFilter and an ItemTraversal can also be specified:

var items = service.FindItems(WellKnownFolderName.Inbox, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject), 
    new SearchFilter.ContainsSubstring(ItemSchema.Subject, "test"), ItemTraversal.Associated, 
    new KeyValuePair<PropertyDefinition, SortDirection>(ItemSchema.Subject, SortDirection.Ascending));

Posted by Henning Krause on Thursday, September 8, 2011 11:15 PM, last modified on Thursday, September 8, 2011 11:15 PM
Permalink | Post RSSRSS comment feed

Streaming Subscription - Design considerations

Commenter Mike had questions on some details of the article I wrote about Exchange streaming notifications (See the comments in this blog post). In the MSDN article, I wrote this:

Streaming notifications do not work this way. Instead, you can use a combination of notifications and the ExchangeService.SyncFolderItems method. The SyncFolderItems method gives you a snapshot of the changes that occurred in a particular folder. This method also returns a small cookie that contains information about the synchronization state. You can pass this synchronization state to subsequent calls of the SyncFolderItems method to get all changes that have occurred since that synchronization cookie was first issued. You should persist this synchronization state somewhere (either on disk or in a database) so that the application does not need to process all of the items in the folder gain.

I further outlined the steps an application should follow when using streaming subscriptions:

  • After your application starts, use the SyncFolderItems method to process all unprocessed items in the folder.
  • Create a streaming notification and connection as specified earlier in this article.
  • Use the SyncFolderItems method again to process all events that occurred since the last synchronization and before the subscription was activated.
  • On each OnNotification event, use the GetItem operation to get additional properties of the specified items.
  • Call the SyncFolderItems method periodically to update the local synchronization cookie.

This makes the application seemingly more complex than it needs to be because your application must be able to deal with different change notifications: Those from the streaming subscription and those from SyncFolderItems. Additionally, once a notification is received through the streaming subscription, the synchronization state from the last call to SyncFolderItems is stale. The application must now deal with the situation that the initial call of SyncFolderItems on an application restart might return changes which already have been processed by the application. The application needs to deal with this situation.

Mike asks whether it’s ok to ignore the item ids specified in a notification and just use the SyncFolderItems method on each notification. Using this approach, the synchronization state returned by the SyncFolderItems method would always be current and the whole application design would be more simple.

The answer is: It depends. If you have a low-volume application and your Exchange server is not used at full capacity, this might be ok. If you are writing an in-house application where you know everything about your infrastructure, this might be acceptable. But keep in mind that an application might run several years and the server load of your Exchange Server might go through the roof during the lifetime of your application. And if you are a software developer who sells his application to (hopefully) many customers, you don’t know anything about the performance situation on these servers. So it is best to conform to best practice and use the rules I outlined in the article.

Posted by Henning Krause on Tuesday, August 9, 2011 8:53 PM, last modified on Tuesday, August 9, 2011 8:53 PM
Permalink | Post RSSRSS comment feed

Custom Mail headers and EWS

The mail headers are exposed on the EmailMessage as first class property: InternetMessageHeaders. However, Exchange also stores each mail header in its own property and defines a unique property set for it: PS_INTERNET_HEADERS.

Here is a property definition for a hypothetical custom property:

private static readonly ExtendedPropertyDefinition FrobProperty =
    new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Frob", MapiPropertyType.String);

If a mail is processed by Exchange with message header like this:

Subject: Test mail
X-Frob: Yes
From: "Henning Krause" <>
To: "Someone <someone@example.local>

Exchange will parse the mail and set the value of the extended property defined above to “Yes”.

Retrieving the custom property is as simple as this:

var item = Item.Bind(service, itemId,
    new PropertySet(BasePropertySet.FirstClassProperties, FrobProperty));

The value of the property can then be accessed using this line:

string frobValue;
if (item.TryGetProperty(FrobProperty, out frobValue))
    Console.Out.WriteLine("The item as a frob value of: {0}", frobValue);

You can even search for messages which have the header “X-Frob” set to “Yes”:

var itemId = folder.FindItems(new SearchFilter.IsEqualTo(FrobProperty, "yes"), 
    new ItemView(10) {PropertySet = PropertySet.IdOnly});

This query will return the first ten messages which have said header set to “Yes”.

Note that Exchange has a limit for named properties which are the result of custom mail headers. You may get one of these entries in your EventLog at some point:

Event ID: 9666
Type: Warning
Category: General
Source: msgidNamedPropsQuotaWarning
Description: The number of named properties created for database "<database name>" is close to quota limit. Current number of named properties: <number of named properties>. Quota limit for named properties: <configured quota>. User attempting to create the named property: <user name>. Named property GUID: <GUID of named property>. Named property name/id: <name of named property>.


Event ID: 9667
Type: Error
Category: General
Source: msgidNamedPropsQuotaError
Description: Failed to create a new named property for database "<database name>" because the number of named properties reached the quota limit (<configured quota>). User attempting to create the named property: <user name>. Named property GUID: <GUID of named property>. Named property name/id: <name of named property>.


See this blog post on how to deal with this issue:

Posted by Henning Krause on Monday, August 1, 2011 12:00 PM, last modified on Wednesday, July 27, 2011 5:57 PM
Permalink | Post RSSRSS comment feed

Working with the Master Category List–EWS edition

Back in 2008 I wrote an article about accessing the Master Category List using WebDAV. If you are not sure what the Master Category List is, read that article first…

EWS could not be used at that time, since access to the Folder Associated Items via EWS is a Feature of Exchange 2010. So if you are on Exchange 2007, the old article still applies.

The last article contained some code which simplified updating the list. I’ve updated the code and aligned the method naming with that of the EWS managed API.

This is the class diagram for the updated code:


The classes are really easy to use:

var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new NetworkCredential("", "password") };
service.AutodiscoverUrl("", url => true);

var list = MasterCategoryList.Bind(service);
foreach (var category in list.Categories)
    Console.Out.WriteLine("category = {0}", category.Name);

The only interesting line in the sample above is line 4. The call to MasterCategoryList.Bind() loads the MasterCategoryList from the users Exchange Mailbox. After that, the name of each console is written to the console.

Adding a new category is equally simple:

var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new NetworkCredential("", "password") };
service.AutodiscoverUrl("", url => true);

var list = MasterCategoryList.Bind(service);
list.Categories.Add(new Category("Vacation", CategoryColor.DarkMaroon, CategoryKeyboardShortcut.CtrlF10));

This will add a new category named “Vacation” to the list.

So how does this work? The Master Category List is stored in a hidden message in the calendar folder of a mailbox. EWS in 2010 provides simple access to this message with the UserConfiguration class. This code show how the Master Category List is loaded:

var item = UserConfiguration.Bind(service, "CategoryList", WellKnownFolderName.Calendar,

var reader = new StreamReader(new MemoryStream(item.XmlData), Encoding.UTF8, true);

The configuration data is stored in the XmlData property as UTF-8 encoded byte array.

Here is the new code:

Sourcecode Download

Posted by Henning Krause on Thursday, July 28, 2011 4:00 PM, last modified on Tuesday, June 11, 2013 4:52 PM
Permalink | Post RSSRSS comment feed

Exchange Managed API autodiscover with Powershell

Powershell is a great tool to automate all sorts of things – including fiddling around with your Exchange mailbox. And the Autodiscover makes it really easy to connect to it – especially if you’re on Office 365 and don’t even know your CAS server.

So first, we need to load the EWS Managed API dll into the current runspace:

[Reflection.Assembly]::LoadFrom("C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll")

Then, create an ExchangeService instance and set its credentials:

$service =  New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.Credentials = New-Object System.Net.NetworkCredential("", "password", "domain");

Now we are ready to use AutoDiscover. But depending on your infrastructure, AutoDiscover might need to follow some redirections before it has discovered your CAS Server. Like in this case:


Exception calling "AutodiscoverUrl" with "1" argument(s): "Autodiscover blocked a potentially insecure redirection to To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload."
At line:1 char:25
+ $service.AutodiscoverUrl <<<< ("");
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

This happens because the AutoDiscover process looks at and instead of an A record pointing to the AutoDiscover service, it finds a CNAME redirecting it to Because this might pose a security risk, the AutoDiscoverUrl method aborts  the discovery process and throws the Exception displayed above. The solution is also outlined: Instead of calling the method AutoDiscoverUrl(mailAddress) call the overload which expects a delegate as a second paramter. This delegate has a string as input and returns the $true if the discovery process should follow the redirection; false otherwise.

How can this overload be used with PowerShell? The answer is a ScriptBlock. If you simply want to allow the discovery process to follow all redirects, simply call it this way:

$service.AutodiscoverUrl("", {$true})

But if you want to verify the discovery process is redirected to the correct url, use this version:

$TestUrlCallback = {
 param ([string] $url)
 if ($url -eq "") {$true} else {$false}

$service.AutodiscoverUrl("", $TestUrlCallback)

You can embed whatever checks you need to verify the given url in the third line of the $TestUrlCallback method.

Posted by Henning Krause on Friday, July 22, 2011 5:30 PM, last modified on Sunday, July 24, 2011 1:22 AM
Permalink | Post RSSRSS comment feed

Replying with attachments to an email message with EWS

The EWS Managed API makes some tasks really easy – like replying to an existing email. Given the unique id of an item, this can be done this way:

var message = (EmailMessage) Item.Bind(service, new ItemId(uniqueId), PropertySet.FirstClassProperties);
var reply = message.CreateReply(false);
reply.BodyPrefix = "Response text goes here";

But what if you want to send an attachment along with the reply? This is tricky, because the the instance created by the EmailMessage.CreateReply() method is of type ResponseMessage. Since its not an EmailMessage instance, it does not have an Attachment property. To add an attachment to this reply, it needs to be saved first. The Save method returns an EmailMessage instance. Attachments can be added to this message. Finally, the message can be sent to its destination.

var message = (EmailMessage) Item.Bind(service, new ItemId(uniqueId), PropertySet.FirstClassProperties);
var reply = message.CreateReply(false);
reply.BodyPrefix = "Response text goes here";
var replyMessage = reply.Save(WellKnownFolderName.Drafts);

Posted by Henning Krause on Monday, July 18, 2011 8:04 PM, last modified on Monday, July 18, 2011 8:04 PM
Permalink | Post RSSRSS comment feed

Enumerating Sharepoint Connections in a mailbox with EWS

An interesting question on StackOverflow came up recently: Is it possible to get the SharePoint lists which are connected to an Exchange Mailbox? The data which is synchronized with Outlook is stored in a PST file on the local disk – so no interaction with Exchange on this end. But if a user logs on from another computer, the SharePoint list the user has subscribed to are synchronized there as well. So the configuration seems to be stored in the mailbox somewhere. And indeed, they are. Outlook creates a message item in the associated folder table in the users inbox. Associated items are not visible from Outlook, but they can be accessed using MAPI or EWS. It turns out that Outlook saves the SharePoint connections similar to the RSS feeds. So a good starting point is to have a look at the Sharing Message Object Protocol Specification which lists the properties used for these items.

The SharePoint configuration items have a MessageClass of IPM.Sharing.Index.In, and the property PidLidSharingProviderGuidProperty is set to {0006F0AD-0000-0000-C000-000000000046}.

The configuration data is stored on a few properties. The following method lists all SharePoint connections connected to a mailbox:

   1:  using System;
   2:  using System.Net;
   3:  using Microsoft.Exchange.WebServices.Data;
   5:  namespace ExchangeTest
   6:  {
   7:      internal class Program
   8:      {
   9:          private static readonly Guid PropertySetSharing = new Guid("{00062040-0000-0000-C000-000000000046}");
  11:          private static readonly ExtendedPropertyDefinition PidLidSharingProviderGuidProperty =
  12:              new ExtendedPropertyDefinition(PropertySetSharing, 0x8A01, MapiPropertyType.CLSID);
  14:          private static readonly ExtendedPropertyDefinition SharingRemotePathProperty =
  15:              new ExtendedPropertyDefinition(PropertySetSharing, 0x8A04, MapiPropertyType.String);
  17:          private static readonly ExtendedPropertyDefinition SharingLocalNameProperty =
  18:              new ExtendedPropertyDefinition(PropertySetSharing, 0x8A0F, MapiPropertyType.String);
  20:          private static readonly ExtendedPropertyDefinition SharingRemoteNameProperty =
  21:              new ExtendedPropertyDefinition(PropertySetSharing, 0x8A05, MapiPropertyType.String);
  23:          private static readonly ExtendedPropertyDefinition SharingBrowseUrlProperty =
  24:              new ExtendedPropertyDefinition(PropertySetSharing, 0x8A51, MapiPropertyType.String);
  26:          private static readonly ExtendedPropertyDefinition SharingRemoteTypeProperty =
  27:              new ExtendedPropertyDefinition(PropertySetSharing, 0x8A1D, MapiPropertyType.String);
  29:          private static readonly Guid SharePointProviderId = new Guid("{0006F0AD-0000-0000-C000-000000000046}");
  31:          public static void Main(string[] args)
  32:          {
  33:              var service = new ExchangeService(ExchangeVersion.Exchange2010)
  34:                            {Credentials = new NetworkCredential(, "Password!")};
  36:              service.AutodiscoverUrl(, url => true);
  38:              var folder = Folder.Bind(service, WellKnownFolderName.Inbox);
  39:              var filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
  40:                                                                   new SearchFilter.IsEqualTo(ItemSchema.ItemClass,
  41:                                                                                              "IPM.Sharing.Index.In"),
  42:                                                                   new SearchFilter.IsEqualTo(PidLidSharingProviderGuidProperty,
  43:                                                                                              SharePointProviderId.ToString()));
  44:              var view = new ItemView(512)
  45:                         {
  46:                             Traversal = ItemTraversal.Associated,
  47:                             PropertySet = new PropertySet(BasePropertySet.IdOnly,
  48:                                                           SharingRemotePathProperty, SharingBrowseUrlProperty,
  49:                                                           SharingLocalNameProperty, SharingRemoteNameProperty,
  50:                                                           SharingRemoteTypeProperty)
  51:                         };
  53:              var items = folder.FindItems(filter, view);
  54:              foreach (var item in items)
  55:              {
  56:                  Console.Out.WriteLine("RemotePath = {0}", item.GetValueOrDefault<string>(SharingRemotePathProperty));
  57:                  Console.Out.WriteLine("BrowseUrl = {0}", item.GetValueOrDefault<string>(SharingBrowseUrlProperty));
  58:                  Console.Out.WriteLine("LocalName = {0}", item.GetValueOrDefault<string>(SharingLocalNameProperty));
  59:                  Console.Out.WriteLine("Remotename = {0}", item.GetValueOrDefault<string>(SharingLocalNameProperty));
  60:                  Console.Out.WriteLine("Type = {0}", item.GetValueOrDefault<string>(SharingRemoteTypeProperty));
  61:                  Console.Out.WriteLine(new string('=', 80));
  62:              }
  63:          }
  64:      }
  66:      public static class ItemExtension
  67:      {
  68:          public static T GetValueOrDefault<T>(this Item item, PropertyDefinitionBase property, T defaultValue = default(T))
  69:          {
  70:              T result;
  71:              return item.TryGetProperty(property, out result) ? result : defaultValue;
  72:          }
  73:      }
  74: }

This method dumps the configuration of all SharePoint connections to the console.

To use this method, you’ll need .NET 4. If you are running .NET 2.0, you’ll have to adapt it.

Additionally, this won't work with Exchange 2007, because EWS in that version does not allow a FindItems call on the associated items table. WebDAV is the API of choice in this case.

Posted by Henning Krause on Wednesday, July 13, 2011 9:05 PM, last modified on Wednesday, July 13, 2011 9:05 PM
Permalink | Post RSSRSS comment feed

Correlating a Non-Delivery-Notification to its original message with the Exchange Managed API

If you are automatically process emails in an Exchange Mailbox, you might also need to process non delivery reports (NDRs) and correlate these NDRs to their original values. Luckily, Exchange does most of the heavy lifting, as long as the NDR conforms to the RFC 3461, which defines the proper structure for an NDR that can be automatically parsed. Not all MTAs (Mail transfer agents) do generate these types of NDRs.

First of all, you need to check whether the mail item in question is actually a non delivery report. This is done by examining the Item Class of the mail. An NDR has an item class of REPORT.IPM.Note.NDR. Next, you need to retrieve the property PidTagParentKey from the item. This property contains the PidTagSearchKey of the original mail.

Unfortunately, the PidTagSearchKey cannot be used to bind to the item directly. Instead, you have to issue a FindItem operation to get it. Normally, sent items are all stored in the SentItems folder, so this narrows the search down.

Here is a sample method which describes the process:


   1:  class Program
   2:  {
   3:      private static readonly ExtendedPropertyDefinition PidTagParentKeyProperty = new ExtendedPropertyDefinition(0x25, MapiPropertyType.Binary);
   4:      private static readonly ExtendedPropertyDefinition PidTagSeachKeyProperty = new ExtendedPropertyDefinition(0x300B, MapiPropertyType.Binary);
   7:      private static bool TryGetOriginalMail(string ndrId, ExchangeService service, out Item originalItem)
   8:      {
   9:          byte[] value;
  11:          var item = service.BindToItems(new[] {new ItemId(ndrId)},
  12:                                          new PropertySet(BasePropertySet.IdOnly,
  13:                                                          PidTagParentKeyProperty, ItemSchema.Subject)).First().Item;
  15:          if (!item.TryGetProperty(PidTagParentKeyProperty, out value))
  16:          {
  17:              Console.Out.WriteLine("Correlationtoken not found.");
  18:              originalItem = null;
  19:              return false;
  20:          }
  22:          originalItem = service
  23:              .FindItems(WellKnownFolderName.SentItems,
  24:                          new SearchFilter.IsEqualTo(PidTagSeachKeyProperty, Convert.ToBase64String(value)),
  25:                          new ItemView(1) {PropertySet = PropertySet.FirstClassProperties})
  26:              .FirstOrDefault();
  28:          return true;
  29:      }
  30:  }

Posted by Henning Krause on Monday, June 27, 2011 8:12 PM, last modified on Monday, June 27, 2011 8:12 PM
Permalink | Post RSSRSS comment feed