Fixing the Charset on MIME Messages When Using ADODB.Stream.ReadText
29 October 09 04:00 PM

We had an issue recently where the customer had written an application to process MIME messages that had body parts encoded with the koi8-r charset…or at least that’s what it said:

------_=_NextPart_001_01C9F067.D9742103
Content-Type: text/plain;
    charset="koi8-r"
Content-Transfer-Encoding: quoted-printable

If you use code similar to the following, the resulting characters returned were not correct.

private string ReadBodyPart()
{
    CDO.IDataSource oIDsrc;
    ADODB.Stream objBpStream = new ADODB.Stream();
    CDO.Message objCDOMsg = new CDO.Message();
    CDO.IBodyPart oIBodyPart;
    
    objBpStream.Open(vtMissing,
        ADODB.ConnectModeEnum.adModeUnknown,
        ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified,
        string.Empty,
        string.Empty);

    objBpStream.LoadFromFile(EML_FILE_PATH);           
    
    oIDsrc = (CDO.IDataSource)objCDOMsg;
    
    oIDsrc.OpenObject(objBpStream, "_Stream");

    objBpStream.Close();


    oIBodyPart = (CDO.IBodyPart)objCDOMsg.TextBodyPart;
    objBpStream = (ADODB.Stream)oIBodyPart.GetDecodedContentStream();
    return objBpStream.ReadText(-1);

}

The problem is that koi8-r is the body name for both “windows-1251” (codepage 1251) and “koi8-r” (codepage 20866). I took a look at what the TextBody and HtmlBody properties were doing because they can return the characters correctly. Turns out, when the message is loaded, we make an API call to GetCharsetInfo and pass in the value defined in the header. This gives us back a structure that contains the uiCodePage used by TextBody and HtmlBody later.

Fortunately, the .net framework provides methods to do this as well. I simply leverage them to correct the charset I’m given.

public static string GetCharSetName(string bodyName)
{
    Encoding encoding = Encoding.GetEncoding(bodyName);
    if (encoding != null)
    {
        int iCP = encoding.WindowsCodePage;
        return Encoding.GetEncoding(iCP).WebName;
    }
    return bodyName;
}

Then I just insert a call to that function above my call to ReadText and we’re good.

private string ReadBodyPart()
{
    CDO.IDataSource oIDsrc;
    ADODB.Stream objBpStream = new ADODB.Stream();
    CDO.Message objCDOMsg = new CDO.Message();
    CDO.IBodyPart oIBodyPart;
    
    objBpStream.Open(vtMissing,
        ADODB.ConnectModeEnum.adModeUnknown,
        ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified,
        string.Empty,
        string.Empty);

    objBpStream.LoadFromFile(EML_FILE_PATH);           
    
    oIDsrc = (CDO.IDataSource)objCDOMsg;
    
    oIDsrc.OpenObject(objBpStream, "_Stream");

    objBpStream.Close();


    oIBodyPart = (CDO.IBodyPart)objCDOMsg.TextBodyPart;
    objBpStream = (ADODB.Stream)oIBodyPart.GetDecodedContentStream();
    objBpStream.Charset = GetCharSetName(objBpStream.Charset);
    return objBpStream.ReadText(-1);

}

Postedby Patrick Creehan | 0 Comments    
Parsing ServerVersion: When an Int Is Really 5 Ints
21 September 09 11:45 AM

I recently had a case where a customer was asking how to figure out the mailbox version of a given user using Exchange Web Services (EWS). We noticed there is a node returned in the AutoDiscover response message called ServerVersion, but this value seems pretty opaque. Here’s a snippet from the AutoDiscover POX response from my test server:

<Protocol>
  <Type>EXCH</Type>
  <Server>MAILBOXEX7.domain.com</Server>
  <ServerDN>/o=First Organization/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=MAILBOXEX7</ServerDN>
  <ServerVersion>720280B0</ServerVersion>
  <MdbDN>/o=First Organization/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=Servers/cn=MAILBOXEX7/cn=Microsoft Private MDB</MdbDN>
  <PublicFolderServer>MAILBOXEX7.domain.com</PublicFolderServer>
  <AD>domainDC.domain.com</AD>
  <ASUrl>https://casserver.domain.com/EWS/Exchange.asmx</ASUrl>
  <EwsUrl>https://casserver.domain.com/EWS/Exchange.asmx</EwsUrl>
  <OOFUrl>https://casserver.domain.com/EWS/Exchange.asmx</OOFUrl>
  <UMUrl>https://casserver.domain.com/UnifiedMessaging/Service.asmx</UMUrl>
  <OABUrl>https://casserver/OAB/4c44408b-66b7-42d9-8247-316fca26961c/</OABUrl>
</Protocol>

The ServerVersion value returned in AutoDiscover is a 32-bit integer value represented in hexidecimal format (720280B0). The integer by itself doesn’t mean anything. It turns out, this integer is really a serialized structure. Here’s how it breaks down:

0x720280B0 (or 1912766640 in decimal) represented in binary is 01110010000000101000000010110000. If we break this binary chunk up into 5 pieces, we’ll see the structure we are after:

0111  001000  000010  1  000000010110000

0111  (7) - The first 4 bits represent a number used for comparison against older version number structures. You can ignore this.

001000 (8) – The next 6 bits represent the major version number.

000010 (2) – The next 6 bits represent the minor version number.

1 (1) – This bit is just a flag that you can ignore.

000000010110000 (176) – The last 15 bits is the build number.

So I can see that my server is running build 08.02.0176.

To parse this value in code is quite easy if you use the binary shift operators. The following sample is in C#, but similar constructs exist in most languages. GetServerVersionIntFromString simply gets the ServerVersion value from the AutoDiscover response body and converts the string value “720280B0” into an unisigned integer using UInt32.Parse

UInt32 intServerVersion = GetServerVersionIntFromString(sb);

uint build = intServerVersion & 0x7FFF;
//get bottom 15 bits
uint minor = (intServerVersion >> 16) & 0x3F;
//get 6 bits from 16 bits in
uint major = (intServerVersion >> 22) & 0x3F;
//gets 6 bits from 22 bits in

I should point out that in Exchange 2010 and above, a new AutoDiscover option is being made available – AutoDiscover SOAP. If you know you will be targeting an Exchange 2010 server, you can use the SOAP AutoDiscover calls which can return you the server major and minor build numbers in a more easily consumable format.

 

<s:Header>
  <a:Action s:mustUnderstand="1">http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetUserSettingsResponse</a:Action>
  <h:ServerVersionInfo xmlns:h="http://schemas.microsoft.com/exchange/2010/Autodiscover" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <h:MajorVersion>14</h:MajorVersion>
    <h:MinorVersion>0</h:MinorVersion>
    <h:MajorBuildNumber>639</h:MajorBuildNumber>
    <h:MinorBuildNumber>20</h:MinorBuildNumber>
    <h:Version>Exchange2010</h:Version>
  </h:ServerVersionInfo>
</s:Header>

MimeContent vs Mime Content
16 September 09 03:46 PM

Recently, I helped a customer with an issue where they were wondering if it was essential to set the ToRecipients, CcRecipients, and BccRecipients if they were setting the same values in the MimeContent property when doing a CreateItem call in Exchange Web Services. While trying to test out the scenarios, I thought “maybe it depends on the order of the elements in your <t:Message>. I soon realized that the order of the properties in the <t:Message> node seemed to matter. As it turns out, MessageType inherits from ItemType and MimeContent is defined on the ItemType where the recipient properties are defined on the MessageType and both of these are xs:sequence types. This means that their elements must appear in a specific order. Any deviation from the prescribed sequence results in a schema validation error returned from EWS. That meant that the MimeContent property itself always had to appear before the recipient properties since MimeContent is the first element described in the ItemType.

Here’s the schema for the ItemType and you can see that MimeContent is first.

<!-- Core contents of an item. -->
<xs:complexType name="ItemType">
  <xs:sequence>
    <xs:element name="MimeContent" type="t:MimeContentType" minOccurs="0" />
    <xs:element name="ItemId" type="t:ItemIdType" minOccurs="0" />
    <xs:element name="ParentFolderId" type="t:FolderIdType" minOccurs="0"/>
    <xs:element name="ItemClass" type="t:ItemClassType" minOccurs="0" />
    <xs:element name="Subject" type="xs:string" minOccurs="0" />
    <xs:element name="Sensitivity" type="t:SensitivityChoicesType" minOccurs="0" />
    <xs:element name="Body" type="t:BodyType" minOccurs="0" />
    <xs:element name="Attachments" type="t:NonEmptyArrayOfAttachmentsType" minOccurs="0" />
    <xs:element name="DateTimeReceived" type="xs:dateTime" minOccurs="0" />
    <xs:element name="Size" type="xs:int" minOccurs="0" />
    <xs:element name="Categories" type="t:ArrayOfStringsType" minOccurs="0" />
    <xs:element name="Importance" type="t:ImportanceChoicesType" minOccurs="0" />
    <xs:element name="InReplyTo" type="xs:string" minOccurs="0" />
    <xs:element name="IsSubmitted" type="xs:boolean" minOccurs="0" />
    <xs:element name="IsDraft" type="xs:boolean" minOccurs="0" />
    <xs:element name="IsFromMe" type="xs:boolean" minOccurs="0" />
    <xs:element name="IsResend" type="xs:boolean" minOccurs="0" />
    <xs:element name="IsUnmodified" type="xs:boolean" minOccurs="0" />
    <xs:element name="InternetMessageHeaders" type="t:NonEmptyArrayOfInternetHeadersType" minOccurs="0" />
    <xs:element name="DateTimeSent" type="xs:dateTime" minOccurs="0" />
    <xs:element name="DateTimeCreated" type="xs:dateTime" minOccurs="0" />
    <xs:element name="ResponseObjects" type="t:NonEmptyArrayOfResponseObjectsType" minOccurs="0" />
    <xs:element name="ReminderDueBy" type="xs:dateTime" minOccurs="0" />
    <xs:element name="ReminderIsSet" type="xs:boolean" minOccurs="0" />
    <xs:element name="ReminderMinutesBeforeStart" type="t:ReminderMinutesBeforeStartType" minOccurs="0" />
    <xs:element name="DisplayCc" type="xs:string" minOccurs="0" />
    <xs:element name="DisplayTo" type="xs:string" minOccurs="0" />
    <xs:element name="HasAttachments" type="xs:boolean" minOccurs="0"/>
    <xs:element name="ExtendedProperty" type="t:ExtendedPropertyType" minOccurs="0" maxOccurs="unbounded" />
    <xs:element name="Culture" type="xs:language" minOccurs="0"/>
    <xs:element name="EffectiveRights" type="t:EffectiveRightsType" minOccurs="0" />
    <xs:element name="LastModifiedName" type="xs:string" minOccurs="0" />
    <xs:element name="LastModifiedTime" type="xs:dateTime" minOccurs="0" />
  </xs:sequence>
</xs:complexType>

That’s followed by the MessageType schema that is an extension of ItemType. This is where the recipient properties appear.

<!-- - - - - - - - - - - - - - - - - - - -->
<!--   Message type: derived from item   -->
<!-- - - - - - - - - - - - - - - - - - - -->
<xs:complexType name="MessageType">
  <xs:complexContent>
    <xs:extension base="t:ItemType">
      <xs:sequence>
        <xs:element name="Sender" minOccurs="0" type="t:SingleRecipientType" />
        <xs:element name="ToRecipients" type="t:ArrayOfRecipientsType" minOccurs="0" />
        <xs:element name="CcRecipients" type="t:ArrayOfRecipientsType" minOccurs="0" />
        <xs:element name="BccRecipients" type="t:ArrayOfRecipientsType" minOccurs="0" />
        <xs:element name="IsReadReceiptRequested" type="xs:boolean" minOccurs="0" />
        <xs:element name="IsDeliveryReceiptRequested" type="xs:boolean" minOccurs="0" />
        <xs:element name="ConversationIndex" type="xs:base64Binary" minOccurs="0" />
        <xs:element name="ConversationTopic" type="xs:string" minOccurs="0" />
        <xs:element name="From" type="t:SingleRecipientType" minOccurs="0" />
        <xs:element name="InternetMessageId" type="xs:string" minOccurs="0" />
        <xs:element name="IsRead" type="xs:boolean" minOccurs="0" />
        <xs:element name="IsResponseRequested" type="xs:boolean" minOccurs="0" />
        <xs:element name="References" type="xs:string" minOccurs="0" />
        <xs:element name="ReplyTo" type="t:ArrayOfRecipientsType" minOccurs="0" />
        <xs:element name="ReceivedBy" type="t:SingleRecipientType" minOccurs="0" />
        <xs:element name="ReceivedRepresenting" type="t:SingleRecipientType" minOccurs="0" />
      </xs:sequence>
    </xs:extension>
  </xs:complexContent>
</xs:complexType>

If you think about how the server will process this XML SOAP request, it will get the MimeContent first and then the first-class properties after that. So the server will build out its entire MIME message based on the content of the MimeContent property and then override those values with the first-class properties that follow. The same holds true for other properties like Body, Subject, etc.

After I figured all this out, I found this already clearly explained in Inside Microsoft Exchange Server 2007 Web Services explaining this same phenomenon when attempting to set the subject:

Well, during a CreateItem call, properties are processed on a first-come, first-served basis.  You first create an empty message, set the contents from the MIME, and then set the explicit subject. This really isn’t a problem in practice although it has some interesting implications. The schema mandates a specific ordering of elements within item instances. In other words, trying to put the subject before the MimeContent property results in a schema validation error. Therefore, which property overwrites which is dictated by the ordering as defined in the schema. (page 176)

They later go on to say the only time you’ll have a conflict is when you try to also set the same properties using the extended properties, so avoid doing that. There’s no need to set both the first-class property and it’s equivalent extended property.

Exchange 2007 SP2 is Released
27 August 09 06:14 PM

In case you missed it, Exchange 2007 SP2 was released this week. There are some cool new features, which the EHLO blog talks about here as well as all the bug fixes etc.

One major thing to point out is that we no longer promote X- headers to custom properties on messages – though you can still get to them through the internet transport headers property.

Postedby Patrick Creehan | 0 Comments    
Line Breaks in Managed Web Service Proxy Classes
22 July 09 09:00 AM

Matt, Rick, and I were working on an issue recently where when an application using EWS would set a contact’s Street address to a value containing a carriage return and line feed, like this:

physicalAddress.Street = "1234 56 Ave NE\r\nc/oPatrick Creehan";

the address card control in Outlook would render it like this:

image

Ugly, right? The problem was that the XMLSerializer would strip out the line feed and leave the carriage return, which the address card didn’t like.

We could prove by sending raw XML requests in a separate application that sending &#x0d;&#x0a; for the carriage return line feed would make everything right, however, if we set the street address like this:

physicalAddress.Street = "1234 56 Ave NE&#x0d;&#x0a;c/oPatrick Creehan";

then the contact’s address card would look like this:

image

Even uglier! It seems that the .net framework, in an attempt to help us out is encoding our string for XML but it wasn’t letting us specify the value we knew was right.

So – the solution is to implement your own class which can handle the XmlSerialization yourself, and replace the auto-generated proxy class’s decision for the type to yours.

Here’s my simple class:

  1.     [SoapTypeAttribute(Namespace = "http://schemas.microsoft.com/exchange/services/2006/types",TypeName="text")]
  2.     public class mstring:IXmlSerializable  
  3.     {
  4.         private string m_string = string.Empty;
  5.         public override string ToString()
  6.         {
  7.             return m_string;
  8.         }
  9.         
  10.         public static mstring CreateMString(string str){
  11.             mstring newmstring = new mstring();
  12.             newmstring.m_string = str;
  13.             return newmstring;
  14.         }
  15.         public static implicit operator mstring(string str)
  16.         {
  17.             return CreateMString(str);
  18.         }
  19.         #region IXmlSerializable Members
  20.         public System.Xml.Schema.XmlSchema GetSchema()
  21.         {
  22.             return new System.Xml.Schema.XmlSchema();
  23.         }
  24.         public void ReadXml(XmlReader reader)
  25.         {
  26.             m_string = reader.ReadContentAsString();
  27.         }
  28.         public void WriteXml(XmlWriter writer)
  29.         {
  30.             string outString = m_string;
  31.             outString = HttpUtility.HtmlEncode(outString);
  32.             outString = outString.Replace("\r", "&#x0d;");
  33.             outString = outString.Replace("\n", "&#x0a;");
  34.             writer.WriteRaw(outString.ToString());
  35.         \

A few things to point out is that I decorated this class with the XML namespace for the Exchange Web Services so that it doesn’t fail schema validation. Also, I didn’t really test whether this works when binding to an existing contact – there may be more work needed in the ReadXML section. In order to support still setting the Street property to a string, I had to override the implicit operator. That allows me to set Street to a string even though technically, now Street is an “mstring.” You’ll notice that the work of actually writing the correct value occurs in WriteXml which we got by implementing IXmlSerializable. Now when the SOAP infrastructure goes to build the request, it will call into our interface to serialize this class.

That reminds me, the last thing you need to do to hook all this up is to go into the web service proxy class Reference.cs and modify the PhysicalAddressDictionaryEntryType so the street properties use your new mstring class instead of string:

  1.     /// <remarks/>
  2.     [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.4918")]
  3.     [System.SerializableAttribute()]
  4.     [System.Diagnostics.DebuggerStepThroughAttribute()]
  5.     [System.ComponentModel.DesignerCategoryAttribute("code")]
  6.     [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.microsoft.com/exchange/services/2006/types")]
  7.     public partial class PhysicalAddressDictionaryEntryType {
  8.         
  9.         private mstring streetField;
  10.         
  11.         private string cityField;
  12.         
  13.         private string stateField;
  14.         
  15.         private string countryOrRegionField;
  16.         
  17.         private string postalCodeField;
  18.         
  19.         private PhysicalAddressKeyType keyField;
  20.         
  21.         /// <remarks/>
  22.         public mstring Street {
  23.             get {
  24.                 return this.streetField;
  25.             }
  26.             set {
  27.                 this.streetField = value;
  28.             }
  29.         }
  30.         /// <remarks/>
  31.         public string City {
  32.             get {
  33.                 return this.cityField;
  34.             }
  35.             set {
  36.                 this.cityField = value;
  37.             }
  38.         }
  39.         
  40.         /// <remarks/>
  41.         public string State {
  42.             get {
  43.                 return this.stateField;
  44.             }
  45.             set {
  46.                 this.stateField = value;
  47.             }
  48.         }
  49.         
  50.         /// <remarks/>
  51.         public string CountryOrRegion {
  52.             get {
  53.                 return this.countryOrRegionField;
  54.             }
  55.             set {
  56.                 this.countryOrRegionField = value;
  57.             }
  58.         }
  59.         
  60.         /// <remarks/>
  61.         public string PostalCode {
  62.             get {
  63.                 return this.postalCodeField;
  64.             }
  65.             set {
  66.                 this.postalCodeField = value;
  67.             }
  68.         }
  69.         
  70.         /// <remarks/>
  71.         [System.Xml.Serialization.XmlAttributeAttribute()]
  72.         public PhysicalAddressKeyType Key {
  73.             get {
  74.                 return this.keyField;
  75.             }
  76.             set {
  77.                 this.keyField = value;
  78.             }
  79.         }
  80.     \

and (after removing the email address so the address will fit on the card) it looks like this:

image

 

Cake.

ConfigureMsgService fails with MAPI_E_INVALID_PARAMETER (0x80070057)
10 July 09 09:02 AM

I recently helped a customer with an issue where they were calling ConfigureMsgService and that call was failing, returning an HRESULT of MAPI_E_INVALID_PARAMETER (0x80070057). After debugging it, we established that the reason that ConfigureMsgService was failing was that the PR_PROFILE_HOME_SERVER_ADDRS property was missing from the profile. Outlook seemed to work fine, logons worked, sending mail worked; it was just that ConfigureMsgService would fail. We tried recreating the profile, but still the property wasn’t being set on the profile.

It turns out that PR_PROFILE_HOME_SERVER_ADDRS gets its value from PR_EMS_AB_NETWORK_ADDRESS, which in turn, gets its value from the networkAddress attribute on the server object in Active Directory. That value was set correctly, but permissions to that object were not. After following the requirements laid out on technet for permissions to AD objects, we determined that the Authenticated Users group was missing the ACL for Read All Properties on the server object. Once we set that permission and recreated the profile, the property was set correctly on the profile and ConfigureMsgService started succeeding.

DeleteItem Ignores ChangeKeys
08 July 09 05:49 PM

According to our documentation, DeleteItem calls should fail with a ErrorStaleObject error when the ChangeKey is not the most recent one. This, however, is not the case. In Exchange 2007, the ChangeKey is completely ignored in DeleteItem calls. This decision was made on the logic that if you are trying to delete an item, chances are you don’t care if you have the most recent copy or not. But, what if you do?

You could try doing a GetItem, check the ChangeKey and then call DeleteItem right after, but that still leaves a small window of time between your GetItem and your DeleteItem calls where the item may have been changed.

Here’s a workaround which will help you implement the logic yourself using pull notifications.

  1. Do a Subscribe on the folder of the item to subscribe for Pull notifications.
  2. Next, do a GetItem and ensure that you do, in fact, have the most recent copy.
  3. Do your DeleteItem.
  4. Do your GetEvents to check for notifications.
  5. If you get just a MovedEvent, then your item was deleted without having been modified (you get a MovedEvent because the item was moved to the Deleted Items folder). You may get a DeletedEvent depending on which flags you passed to DeleteItem. If you get a ModifiedEvent before your MovedEvent, you can then go retrieve the item from the Deleted Items folder and check the values of the properties from the item there. If you hard deleted the item (and therefore got a DeletedEvent) you cannot go get the latest copy from Deleted Items, because it isn’t there.
  6. Unsubscribe.
TNEF (Chapter 2): Old School
27 January 09 06:09 PM

As discussed in Chapter 1 of this captivating series, MAPI contains an interface to allow developers to create and read TNEF data. This interface is the ITnef interface. There are only a few methods in this interface and they are, for the most part, self explanatory. The entire process of creating a TNEF stream can be done in just a few steps:

  1. Call OpenTnefStreamEx to get a TNEF stream to write into.

    Make sure you pass in TNEF_ENCODE since you’ll be creating TNEF. If you were reading TNEF, you’d pass in TNEF_DECODE instead. The other flags to worry about here are TNEF_BEST_DATA, TNEF_COMPATIBILITY, and TNEF_PURE. All of these just signal to MAPI how you want the properties you add to the TNEF stream treated. They will either be all converted to the old-school attributes (TNEF_COMPATIBILITY) – you shouldn’t use this one; some will be converted to attributes but also written to the attMAPIProps section (TNEF_BEST_DATA); or they will all just be written to the MAPI props and none of them written to the attributes (TNEF_PURE).
  2. Call EncodeRecips and pass in the Recipient table you get from a call to IMessage::GetRecipientTable on your message.
  3. Call AddProps passing in an SPropTagArray of non-transmittable prop tags and use the TNEF_PROP_EXCLUDE flag.

    There are essentially two schools of thought for building your TNEF: exclude the props you don’t want and let MAPI deal with the rest; or choose carefully which props you do want to include and add them each piecemeal. These are the reason for having the TNEF_PROP_EXCLUDE and TNEF_PROP_INCLUDE flags. One of them says here are the properties I don’t want you to encode (TNEF_PROP_EXCLUDE) and the other, TNEF_PROP_INCLUDE, says I want you to include all of these properties.

    There’s another method, SetProps, which does just that, sets the value of a property in the TNEF stream to a value you supply. This allows you to modify the data of the message you are trying to encode, or add additional properties that weren’t on the original.

    Back to AddProps for a moment. The flags that supports don’t stop with TNEF_PROP_INCLUDE and TNEF_PROP_EXCLUDE, There is also TNEF_PROP_ATTACHMENTS_ONLY which says “of the properties I’ve given you to work with, I only want you to include/exclude the ones that have to do with attachments. Contrast that with TNEF_PROP_MESSAGE_ONLY which says "”of the properties I’ve given you to work with, I only want you to include/exclude the ones that have to do with the message itself – not attachments.” Then there’s the CONTAINED flags: TNEF_PROP_CONTAINED and TNEF_PROP_CONTAINED_TNEF. TNEF_PROP_CONTAINED means that these properties are going on an attachment; and the TNEF_PROP_CONTAINED_TNEF means I have TNEF data I’m going to give you to put in an attachment – like if you already had a TNEF blob you wanted to include as an attachment, which I’ll demonstrate below.
  4. Once you get all your properties added and included/excluded properly, you call Finish and you’re done. One thing that makes it a little complicated though, is that you have to keep alive all the pointers and streams, etc you’re using in your TNEF until Finish is called, because that’s when all the internal work is actually done. So when you call Finish, that’s when MAPI says, Oh, ok, let me go get that recipient table you gave me. If you’ve already released it, then the process fails.

So it’s pretty easy to do this. This is essentially the way that MFCMAPI demonstrates how to do it (look in File.cpp under SaveToTNEF). There are problems associated with doing it this way when it comes to Unicode properties and when having multiple embedded messages.

The more complicated way to do this to work around some of the issues described above is to add the properties you want explicitly, including each attachment.

The basic difference in the strategy is that instead of calling AddProps with TNEF_PROP_EXCLUDE, call it with TNEF_PROP_INCLUDE and give it the SPropTagArray you get from a call to GetPropList on the message. You’ll need to filter out the non-transmittable properties (such as custom props and things like the Store EntryID). Once you add all the message props, call GetAttachmentTable and loop through each attachment and do one of two things, if it’s not an embedded message, just add the attachment data with AddProps on PR_ATTACH_DATA_BIN; otherwise, you’re going to recurse over yourself and build a TNEF stream from the embedded message. When you call Finish on it, then you’ll add it to the parent TNEF stream by calling AddProps with PR_ATTACH_DATA_OBJ and using the TNEF_PROP_CONTAINED_TNEF flag and give it the stream for your TNEF blob. Once you unwind all the way, you’ll have your “master” TNEF stream. Essentially, you’ll follow the steps here: http://msdn.microsoft.com/en-us/library/cc839833.aspx

Postedby Patrick Creehan | 0 Comments    
TNEF (Chapter 1): Basics
16 January 09 11:17 AM

I’ve worked quite a few cases recently regarding problems some folks have had either reading or composing TNEF content. I’ve learned quite a bit myself as a result, and I thought I’d share. I decided I would do a series of blog posts on the topic and hopefully save some of you the time I spent learning all this.

So, being the first post on the topic, I suppose now would be a good time for a review on just what TNEF is and how it’s structured.

TNEF stands for Transport-Neutral Encapsulation Format. If you use Outlook or any other MAPI client as your mail client, you may know that MAPI is a protocol for communication between the client and the mailbox server. MAPI defines a set of interfaces which the client can use to work with the data in the mailbox. The MAPI structure for the data is hierarchical with messages being contained in containers, which themselves can have a parent container, all the way up to the root of the store. MAPI also defines a set of properties understood by the client and, in some cases, the server. If all mail sent could stay on this one server and only go between clients on this one system, this would be all we need; but we know that’s not the case. A very large quantity of e-mail is sent over the internet to foreign systems every day. The vast majority of those use an industry-standard protocol called SMTP (Simple Mail Transfer Protocol) to send messages in an industry-standard format called MIME (Multipurpose Internet Mail Extensions). MIME is composed of body parts, which can in turn be composed of additional body parts themselves. MIME also allows you to add headers to each of the body parts which allow you to describe the content of that body part. So one body part may be a Word Document attachment, so the MIME headers on that body part would contain the MIME type such as application/doc and the transfer type, such as base64. The content of that body part would then contain a base64 encoding of the document. The headers for the root body part contain information such as the subject of the message, the sender and recipient information, etc.

As a message makes its way through transport from one person’s email client to another person’s, it encounters many “hops” (brief stops at SMTP servers in the routing path) which have the opportunity to modify the headers. They do this in order to track the path the message took or to flag it as SPAM, verify the sender address, etc. So there’s a chance the headers you specify when you send the message won’t be the same as when the message arrives at the destination. The headers also only support text values. One of the problems discovered early on about the MIME format was that it has no concept of “rich text.”

In early versions of Outlook, users wanted the ability to send and receive email that contained rich text bodies. Microsoft devised a plan to create an attachment to the messages it was sending that would have a certain content-type and would come to have a well-known name, “winmail.dat”. This attachment would contain an encapsulation of the MAPI properties that could represent this rich body that would work across any transport and be readable by any system that supported MIME.

The original structure just supported a very simple structure that was basically Name/size/value. These were called “attributes” and the names of these attributes are still prefixed by “att.” Many of the attribute names can be seen here: http://msdn.microsoft.com/en-us/library/cc765736.aspx. The most important of these attributes for the purposes of our discussion will be the attMAPIProps. This attribute contains a list of MAPI properties that the receiving system can set on the message once it has converted the other MIME parts into their MAPI format. Some of the TNEF attributes can be directly translated into MAPI properties as defined by the link earlier in this paragraph, but there is not a 1-1 mapping between TNEF attributes and MAPI properties – hence the attMAPIProps attribute. Attachments and recipient data can also be encoded into the TNEF structure, which we’ll examine more later.

MSDN documents the general structure of TNEF but it’s hard to understand. Last year, when Exchange decided to be among those systems that elected to publicly document their protocols, they created [MS-OXTNEF].pdf, which documents very clearly the structure of the TNEF data and how to parse it. Don’t get too nervous, though. I have parsed a 3MB TNEF blob manually myself, but in Exchange 2007, we provide managed code interfaces to allow you to read (or write) this data very easily. In subsequent posts, I’ll dive more into the structure and into the managed classes, as well as the legacy MAPI ITnef interfaces, and more into problems you may experience in developing TNEF-enabled applications.

Postedby Patrick Creehan | 1 Comments    
New Drop of MAPI/CDO Download Released Today
19 December 08 04:48 PM

After a hiccup earlier this week in getting the new MAPI & CDO downloads published to microsoft.com, they released today.

MAPI / CDO

http://www.microsoft.com/downloads/details.aspx?familyid=E17E7F31-079A-43A9-BFF2-0A110307611E&displaylang=en

CDO 1.21

http://www.microsoft.com/downloads/details.aspx?familyid=2714320D-C997-4DE1-986F-24F081725D36&displaylang=en

Postedby Patrick Creehan | 4 Comments    
Filed under: , ,
MAPI Docs Moved
04 December 08 10:34 AM

So, the Exchange team decided they didn't want to maintain the MAPI documentation anymore since they don't ship MAPI anymore. So the Outlook team stepped up and took over the docs. As such, you can now find them under the Outlook branch in the MSDN left-nav.

http://msdn.microsoft.com/en-us/library/cc765775.aspx

Steve Griffin has been working with the Outlook team on prettying them up and updating them for a few months, and they're now better than ever! He even got a new icon for MFCMAPI out of the deal!

Postedby Patrick Creehan | 0 Comments    
Trouble with Live Search Maps Add-in for Outlook
22 October 08 09:08 AM

Several million of you have downloaded the Live Search Maps Add-in for Outlook which allows integration in Outlook with maps and has some cool functionality around extending your appointment blocks to account for automatically calculated travel time among other things.

We have received a large number of support cases that are caused either directly or indirectly because of this add-in. These include hangs, crashes, and leaks. There could be any number of different reasons for those, but to name one culprit, the add-in interops with CDO 1.21, which if you are a messaging developer following the blogs of anyone on our team, you will know that this is not supported.

http://support.microsoft.com/kb/266353

Worse than that, it is distributing CDO.dll, which is also not supported. http://support.microsoft.com/kb/171440

A customer of mine reported an issue that lead us to another discovery. The add-in installs a custom form to your Personal forms registry and changes the default form for the calendar to IPM.Appointment.Location. The form it publishes is based on the LEO.oft form that it installs in your Program Files. The OFT was clearly customized from an existing item in the designer’s mailbox. The form contains a value for PR_START_DATE and PR_END_DATE set to 4/6/2006. The problem with this is that Outlook doesn’t use PR_START_DATE and PR_END_DATE, but CDO 1.21 does and OWA will set them as well. Outlook uses custom named props to keep track of dates.  Exchange normally keeps these custom props and PR_START/END_DATE in sync, but only if it needs to because of a modification you did from OWA or something like that. Otherwise, the original values will stick.

If you have a CDO 1.21 application which filters based on a date, all the appointments you created with this form in your calendar will appear to be on 4/6/2006.

The long-term plan for what to do about all the problems in this add-in has not been determined at the time of writing of this blog, but it may result in the download being removed from microsoft.com. This won’t help you fix up any items that already exist in your calendar though – nor will it prevent users from using the add-in if they already have it downloaded and installed.

If you insist on continuing to use the add-in, then please at least use this updated form.

You will need to publish this form to your Personal Forms library over the original. If you uncomfortable with that, you can

  1. Uninstall the add-in using Add/Remove Programs.
  2. Remove the existing form from your Personal forms library,
  3. Close Outlook and ensure no instances of Outlook.exe are running in Task Manager.
  4. Reinstall the add-in,
  5. Replace the LEO.oft in the Program Files folder (C:\Program Files\Live Search Maps for Outlook) with the one contained in the ZIP file linked above.
  6. Open Outlook. (the add-in will publish your new form).

This should allow your CDO 1.21 code to execute normally on any newly created items. For existing items, you can use Outlook Object Model or CDO 1.21 (or Extended MAPI) code to loop through the appointments in your calendar and delete the PR_START_DATE and PR_END_DATE properties if they are on 4/6/2006 with a message class of IPM.Appointment.Location. Outlook should still be able to work with the appointment just fine without those properties.

Postedby Patrick Creehan | 6 Comments    
Misha Shneerson : COM Interop: Handling events has side effects
22 October 08 09:04 AM

Misha, a Senior Dev on the VSTO team just posted this blog describing why handling events in managed code can be problematic. This is not news to our team, but he provides a good explanation of why it’s problematic.

Misha Shneerson : COM Interop: Handling events has side effects

If any of what he says sounds familiar, it’s because our own Matt Stehle has been talking about this for a while.

OnSyncDelete Delete
30 September 08 01:58 PM

The Exchange team is looking for some feedback on business scenarios that will be impacted by removing store sinks from the code. With Exchange 2007 and beyond, the new technology designed to replace store sinks is EWS Notifications and Transport Agents. However, with the removal of the synchronous store sinks, OnSyncSave and OnSyncDelete, there will be no means of synchronous notification of changes on the store. If you have a business scenario that makes use of synchronous store sinks, hop over to Matt’s blog post and give him some feedback on this.

Forwarding Appointments in Outlook Prepopulates “To” Field With All Attendees
19 September 08 01:38 PM

We’ve had a lot of folks calling in recently about this one. The symptoms are that if you go to your calendar in Outlook and forward a meeting, the To field is prepopulated with all attendees of the meeting and the Subject field is not prefixed with “FW:.”  The common denominator of all victims of this problem is that they all had their meetings processed with CDO 1.21. This is common if you are a Blackberry user, but could happen if any application processes your appointment with CDO 1.21 before you’ve had a chance to touch it with Outlook.

The real cause of the problem is that CDO 1.21 doesn’t clear the MSGFLAG_UNSENT flag from the PR_MESSAGE_FLAGS property when it does a Respond. Because this flag is still set on the appointment item in the calendar, Outlook (rightfully) thinks the message has not yet been sent and so it treats it like a new message – essentially.

I’ve requested a fix for this issue and it is currently being worked on by our development team. I’ll update this post if/when the fix becomes available.

[UPDATE| The fix is now available and accessible here: http://support.microsoft.com/default.aspx?scid=kb;EN-US;957020.

More Posts Next page »
Page view tracker