Click here to Skip to main content
6,634,665 members and growing! (16,648 online)
Email Password   helpLost your password?
Enterprise Systems » Microsoft Exchange » General     Intermediate License: The Code Project Open License (CPOL)

Programming with Exchange Server 2007 (EWS) - Part 3

By Brij

This article is the third in a series on EWS, which explores Exchange Web Services.
C# (C# 2.0, C# 3.0), .NET (.NET 2.0), ASP.NET, Dev
Posted:1 Dec 2008
Views:16,332
Bookmarked:20 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 5.21 Rating: 4.55 out of 5
1 vote, 7.1%
1

2
1 vote, 7.1%
3
3 votes, 21.4%
4
9 votes, 64.3%
5

Background

In my last article, I discussed how to read different folders like inbox, sent items etc., and also do a search on the basis of some criteria.

My previous articles on this series include:

  1. Programming with Exchange Server 2007 (EWS) - Part 1
  2. Programming with Exchange Server 2007 (EWS) - Part 2

In this part, first, I'll discuss reading the details of a mail from the inbox, and also cover the mystery behind extended properties. The key points are:

Introduction

Every mail is of type MessageType or is inherited from MessageType, so we can access all the items from the inbox as MessageType even mails related to Calendaring.

Reading Mails

To read the details of a mail, we need to use the GetItem API provided by EWS, as:

public void GetSignalDetails(ItemIdType p_strItemId)
{
    GetItemType MailId = new GetItemType();
    GetItemResponseType mailResponse;
    string strMsg = string.Empty;

    MailId.ItemIds = new BaseItemIdType[] { idType };
    MailId.ItemShape = new ItemResponseShapeType();
    MailId.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
    mailResponse = _esb.GetItem(MailId);
    ArrayOfResponseMessagesType arrMail = p_mailResponse.ResponseMessages;
    ResponseMessageType[] responseMessages = arrMail.Items;
    foreach (ResponseMessageType respmsg in responseMessages)
    {
        if (respmsg.ResponseClass == ResponseClassType.Error)
        {
            throw new Exception("Error: " + respmsg.MessageText);
        }
        else if (respmsg.ResponseClass == ResponseClassType.Warning)
        {
            throw new Exception("Error: " + respmsg.MessageText);
        }
        //check to determine whether the response message is correct type 
        if (respmsg is ItemInfoResponseMessageType)
        {
            ItemInfoResponseMessageType createItemResp = 
                     (respmsg as ItemInfoResponseMessageType);
            ArrayOfRealItemsType aorit = createItemResp.Items;
            foreach (MessageType myitem in aorit.Items)
            {
                string  strSubject = myMessage.Subject;
                if (myMessage.From != null)
                {
                       string strFrom = myMessage.From.Item.Name;
                }
                StringBuilder objTo = new StringBuilder();

                if (myMessage.ToRecipients != null)
                {
                    //To be checked only for single recipient
                    foreach (EmailAddressType email in myMessage.ToRecipients)
                    {
                        objTo.Append(email.Name + "[" + email.EmailAddress + "];");


                    }
                }
                StringBuilder objCC = new StringBuilder();

                if (myMessage.CcRecipients != null)
                {
                    //To be checked only for single recipient
                    foreach (EmailAddressType email in myMessage.CcRecipients)
                    {
                        objCC.Append(email.Name + "[" + email.EmailAddress + "];");
                    }
                }
                objSignalDetailsRow.MailBody = myMessage.Body.Value;
            }
            //Similarly we can read other properties
        }

In the same way, we can read mails related to Calendaring, which will be explored in subsequent articles.

Setting Read Mails as Read

There is a property of type bool for MessageType called isRead. The first time a mail comes to the inbox, we show it in bold because it is not read yet, but when the mail is read, we need to set the property isRead to true so that the next time we show it as normal. After successfully reading a mail, we need to update this property to true. We have an API UpdateItem to update any existing item. The code to accomplish this is as shown:

public bool SetReadStatus(ItemIdType item)
{
    SetItemFieldType setField = new SetItemFieldType();
    PathToUnindexedFieldType path = new PathToUnindexedFieldType();

    MessageType message = new MessageType();
    message.IsRead = true;
    message.IsReadSpecified = true;
    setField.Item1 = message;
    path.FieldURI = UnindexedFieldURIType.messageIsRead;


    setField.Item = path;
    ItemChangeType[] updatedItems = new ItemChangeType[1];
    updatedItems[0] = new ItemChangeType();
    updatedItems[0].Updates = new ItemChangeDescriptionType[1];
    updatedItems[0].Updates[0] = setField;

    ItemChangeDescriptionType[] updates = new ItemChangeDescriptionType[1];
    updates[0] = new ItemChangeDescriptionType();
    updates[0].Item = path;

    updatedItems[0].Item = new ItemIdType();
    ((ItemIdType)updatedItems[0].Item).Id = item.Id;
    ((ItemIdType)updatedItems[0].Item).ChangeKey = item.ChangeKey;
    UpdateItemType request = new UpdateItemType();
    request.ItemChanges = updatedItems;
    request.ConflictResolution = ConflictResolutionType.AutoResolve;
    request.MessageDisposition = MessageDispositionType.SaveOnly;
    request.MessageDispositionSpecified = true;

    UpdateItemResponseType response = _esb.UpdateItem(request);

    if (response.ResponseMessages.Items[0].ResponseClass != 
                         ResponseClassType.Success)
        return false;
    else
        return true;
}

Extended Properties - Intro

Extended properties are very important for us when we make custom mail applications because, let's say, in a mail, we have default properties in the MessageType item, and if we want a new property, let's say, Classification, for our custom application, then we need to use an extended property.

Extended Properties - How to set them

We can create and set a new property as an extended property at the time of making an instance of the class (i.e., when setting the properties of that class).

MessageType p_objMessage=new p_objMessage();
p_objMessage.ExtendedProperty = new ExtendedPropertyType[1];

PathToExtendedFieldType pathClassification = new PathToExtendedFieldType();
pathClassification.DistinguishedPropertySetId =

DistinguishedPropertySetType.PublicStrings;
pathClassification.DistinguishedPropertySetIdSpecified = true;
pathClassification.PropertyName = "Classification";
pathClassification.PropertyType = MapiPropertyTypeType.String;
p_objMessage.ExtendedProperty[0] = new ExtendedPropertyType();
p_objMessage.ExtendedProperty[0].ExtendedFieldURI = pathClassification;
p_objMessage.ExtendedProperty[0].Item = msgRow.Classification;

Here, I am creating an extended property "Classification" for the MessageType object .This should be done at the time of setting the other properties of that object, after creating the object.

Extended Properties - How to read them

We have two scenarios here:

  • Reading it at the time of searching\reading all the items for folders.
  • Reading at the time of detailed reading.

For the first case: We first need to specify which property we want to read:

PathToExtendedFieldType pathClassification = new PathToExtendedFieldType();
pathClassification.DistinguishedPropertySetId = 
          DistinguishedPropertySetType.PublicStrings;
pathClassification.DistinguishedPropertySetIdSpecified = true;
pathClassification.PropertyName = "Clasification";
pathClassification.PropertyType = MapiPropertyTypeType.String;

But for using this, we first need to create an object of type ItemResponseShapeType as shown below and set the BaseShape property:

ItemResponseShapeType itemProperties = new ItemResponseShapeType();
// Use the Default shape for the response. 
itemProperties.BaseShape = DefaultShapeNamesType.Default;
itemProperties.AdditionalProperties = new BasePathToElementType[]
{ pathClassification };

And finally, we need to set this to the findRequest object, as:

findRequest.ItemShape = itemProperties;

For the second case: we first need to read the details by using GetItem; then again, we need to call the EWS API for all the extended properties because we can't do it in one go. The code is as shown:

public ExtendedPropertyType[] GetExtendedProperties(ItemIdType itemid)
{
    PathToExtendedFieldType pathClassification = new PathToExtendedFieldType();
    pathClassification.DistinguishedPropertySetId = 
       DistinguishedPropertySetType.PublicStrings;
    pathClassification.DistinguishedPropertySetIdSpecified = true;
    pathClassification.PropertyName = "Classification";
    pathClassification.PropertyType = MapiPropertyTypeType.String;


    GetItemType getExPropertiesRequest = new GetItemType();
    ItemIdType iiItemId = new ItemIdType();
    iiItemId = itemid;

    ItemResponseShapeType getResponseShape = new ItemResponseShapeType();
    getResponseShape.BaseShape = DefaultShapeNamesType.AllProperties;
    getResponseShape.IncludeMimeContent = true;
    getExPropertiesRequest.ItemShape = getResponseShape;

    getExPropertiesRequest.ItemShape.AdditionalProperties = 
                                     new BasePathToElementType[1];
    getExPropertiesRequest.ItemShape.AdditionalProperties[0] = pathClassification;


    getExPropertiesRequest.ItemIds = new ItemIdType[1];
    getExPropertiesRequest.ItemIds[0] = iiItemId;
    getExPropertiesRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;

    GetItemResponseType giResponse = _esb.GetItem(getExPropertiesRequest);
    if (giResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
    {
        throw new Exception("Error: " +
        giResponse.ResponseMessages.Items[0].MessageText);
    }
    else
    {
        ItemInfoResponseMessageType rmResponseMessage = 
             giResponse.ResponseMessages.Items[0] as ItemInfoResponseMessageType;

        if (rmResponseMessage.Items.Items[0].ExtendedProperty != null)
        {
            MessageType message = rmResponseMessage.Items.Items[0] as MessageType;
            return (message.ExtendedProperty);
        }
        else
        {
            return null;
        }
    }
}

Note: In this article, _esb is the object of ExchangeService is as in my earlier articles of the series.

I hope this series is useful for all those who are working on EWS. Suggestions are highly appreciated. In the next article, I'll start exploring the Calendaring provided by EWS.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Brij


Member
Brij has done MCA from National Institute of Techlnology,Durgapur, West Bengal, India.He is currently working as a S/W Developer Multinational from last three years. He has also done graduation in Comp Science from Lucknow University .He is also certified as Microsoft Certified Technologies Specialist-Web Applications and Microsoft Cerfied Professional. He is having very good expertise in .NET -Web Application.And also a good exposer in .NET3.0/3.5 framework .He is also a Exchange Server 2007(EWS) Specialist.He has a great passion to learn new Microsoft Tecnologies and love to share the Knowledge.

Artclies:
- Configuration Overview: ASP.NET
2nd Runner Up "Best ASP.NET article of Feb 2009"
- Deployment of a Website on IIS
4th Runner Up "Best ASP.NET article of Feb 2009"
- Programming With Exchange Server 2007 (EWS)-Part 1
- Programming With Exchange Server 2007 (EWS)-Part 2
- Programming With Exchange Server 2007 (EWS)-Part 3

Language / Technology :
C#, ASP.NET, AJAX, XML,XSLT, ADO.Net , Active Directory , Exchange Server 2007 (EWS) , LCS-2005, Java script, Web Services ,Win services,DotnetNuke,Win Services,WSS 3.0,Sharepoint Designer

Database :
SQL Server 2000,SQL Server 2005

Application Server :
IIS 5.1, IIS 6, IIS 7

Performance Tool :
SQL Profiler, Rational Performance Tester (RPT), ANTS Profiler
Occupation: Software Developer (Senior)
Location: India India

Other popular Microsoft Exchange articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh)FirstPrevNext
GeneralHow to get or add contacts to users mailbox, using account with admin rights to access them in Exchange 2007. coding in C# 2008. PinmemberRuslan Guryanov6:50 5 Nov '09  
GeneralHow to check if the mail is replied/forwarded or not Pinmembervstonape20:33 2 Nov '09  
GeneralMy vote of 1 PinmemberBhavneet8313:22 14 Oct '09  
Generalhow to extract body as text PinmemberAmeen Azam Khan4:48 29 Sep '09  
GeneralNice Article but ... [modified] PinmemberMember 29352288:24 25 Sep '09  
GeneralRe: Nice Article but ... PinmemberBrij20:48 26 Sep '09  
GeneralRe: Nice Article but ... PinmemberMember 29352287:02 28 Sep '09  
QuestionSAving Emails or Calender items PinmemberYogesh Deshpande8:22 9 Sep '09  
GeneralMaybe you can provide some information... PinmemberDaxel1238:40 14 Jul '09  
GeneralRe: Maybe you can provide some information... PinmemberBrij20:55 26 Sep '09  
GeneralRe: Maybe you can provide some information... PinmemberEvelen21:36 28 Oct '09  
GeneralHow to add items to a shared calendar in exchange server PinmemberMember 47444580:52 11 Jun '09  
Generalhow to create a mail box with exchange 2007 web service Pinmemberthemahg2:30 21 Apr '09  
GeneralRe: how to create a mail box with exchange 2007 web service PinmemberBrij20:47 26 Sep '09  
Questionhow to get attchment with message [modified] PinmemberHedgehogDworkin7:43 12 Feb '09  
Generalarticle is nice but... PinmemberHedgehogDworkin4:33 12 Feb '09  
GeneralRe: article is nice but... PinmemberBrij4:49 15 Feb '09  
GeneralRe: article is nice but... Pinmemberdarkfoxy3:40 24 Sep '09  
GeneralRe: article is nice but... PinmemberBrij20:53 26 Sep '09  
GeneralAll Extended Properties PinmemberDaxel1237:12 30 Jan '09  
GeneralRe: All Extended Properties PinmemberBrij4:52 15 Feb '09  
GeneralNeed help regarding "Extraction of MessageType from Drafts folder (with itemId string as input)" PinmemberMember 5447437:20 12 Dec '08  
GeneralRe: Need help regarding "Extraction of MessageType from Drafts folder (with itemId string as input)" PinmemberBrij21:21 12 Dec '08  
Generalhooking into exchange events PinmemberYang Yu2:29 4 Dec '08  
AnswerRe: hooking into exchange events PinmemberBrij18:51 4 Dec '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 1 Dec 2008
Editor: Smitha Vijayan
Copyright 2008 by Brij
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project