Performing grouped item searches by using the EWS Managed API 2.0

Last modified: October 13, 2012

Applies to: EWS Managed API | Exchange Server 2007 Service Pack 1 (SP1) | Exchange Server 2010

Note: This content applies to the EWS Managed API 2.0 and earlier versions. For the latest information about the EWS Managed API, see Web services in Exchange.

You can use the Microsoft Exchange Web Services (EWS) Managed API 1.0 to search for items in a mailbox and group the results.

To use grouped item searches

  1. Create a search filter. The following code shows how to create a search filter that filters for e-mail messages.

    SearchFilter isEqualToEmail = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "IPM.Note");
    

    For more information about how to build search filters, see Working with search filters by using the EWS Managed API 2.0.

  2. Create an ItemView. The following code shows an ItemView object set with a page size of 10. The ItemView object uses the default value of 0 for the offset and the default enumeration value of Beginning for the OffsetBasePoint.

    ItemView view = new ItemView(10);
    
  3. Set the base property set to be returned in the response.

    view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
    view.PropertySet.Add(ItemSchema.Subject);
    view.PropertySet.Add(ItemSchema.DateTimeReceived);
    view.PropertySet.Add(EmailMessageSchema.Sender); 
    
  4. Identify the property and the sort direction for ordering search results.

    view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
    
  5. Set the traversal option to only search the top level of the searched folder.

    view.Traversal = ItemTraversal.Shallow;
    
  6. Set the grouping options for the search results.

    To group search results

    1. Create the grouping object.

      Grouping grouping = new Grouping();
      
    2. Identify the property that is used to group e-mail messages and the sort direction for the grouped items in the search results. The following example shows how to group on the Subject property in a descending sort direction.

      grouping.GroupOn = EmailMessageSchema.Subject;
      grouping.SortDirection = SortDirection.Descending;
      
    3. Identify how the groups are aggregated. The following example shows how to aggregate groups based on the maximum value of the DateTimeReceived property.

      grouping.AggregateOn = ItemSchema.DateTimeReceived;
      grouping.AggregateType = AggregateType.Maximum;
      
  7. Send the request by using the ItemView and Grouping objects to get a collection of GroupedFindItemsResults items. The following example shows a search of the Inbox. Note that this overload of the FindItems method returns a GroupedFindItemsResults collection instead of a FindItemsResults collection.

    GroupedFindItemsResults<Item> findResults = 
          service.FindItems(WellKnownFolderName.Inbox, isEqualToEmail, view, grouping);
    
  8. Process each group and each item in each group that is returned in the response.

    foreach (ItemGroup<Item> myGroup in findResults.ItemGroups)
    {
        Console.WriteLine("\r\nGroup Index: " + myGroup.GroupIndex);
    
        foreach (EmailMessage myItem in myGroup.Items)
        {
            Console.WriteLine("\r\n\t" + (myItem as EmailMessage).Sender.Name);
            Console.WriteLine("\t" + myItem.DateTimeReceived);
        }
    }
    
  9. Check for additional paged search results and request additional search pages if applicable. For more information, see Performing pages searches by using the EWS Managed API 2.0.

    if (findResults.MoreAvailable)
    {
        // Get the remaining items by using subsequent paged find item calls by using offsets.
    }
    

Example

The following code example shows how to search a mailbox and get grouped search results. The search results are returned in a maximum page size of 10. The search is performed on the Inbox and only returns results for e-mail messages. All other item types, such as meeting requests, will not be returned in the grouped result set. Only the ID, Subject, DateTimeReceived, and Sender properties are returned in the result set. Each group is based on the Subject property. The groups are sorted in descending order from the most recent group and are aggregated on the maximum value of the DateTimeReceived property. The items in each group are ordered by the ItemSchema.DateTimeReceived property in ascending order.

// Create a search filter that returns only e-mail messages.
SearchFilter isEqualToEmail = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "IPM.Note");

// Create an ItemView with a page size of 10.
ItemView view = new ItemView(10);

// Indicate that the base property will return the ID, 
// Subject, DateTimeReceived, and Sender.
view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
view.PropertySet.Add(ItemSchema.Subject);
view.PropertySet.Add(ItemSchema.DateTimeReceived);
view.PropertySet.Add(EmailMessageSchema.Sender);

// Order the search results by the DateTimeReceived in ascending order.
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);

// Set the traversal to shallow. Shallow is the default option. 
// Other options are Associated and SoftDeleted.
view.Traversal = ItemTraversal.Shallow;

// Set the grouping for the search results.
Grouping grouping = new Grouping();
grouping.GroupOn = EmailMessageSchema.Subject;
grouping.SortDirection = SortDirection.Descending;
grouping.AggregateOn = ItemSchema.DateTimeReceived;
grouping.AggregateType = AggregateType.Maximum;

// Send the request to search the Inbox and get the grouped results.
GroupedFindItemsResults<Item> findResults = 
    service.FindItems(WellKnownFolderName.Inbox, isEqualToEmail, view, grouping);

// Process each item.
foreach (ItemGroup<Item> myGroup in findResults.ItemGroups)
{
    Console.WriteLine("\r\nGroup Index: " + myGroup.GroupIndex);

    foreach (EmailMessage myItem in myGroup.Items)
    {
        Console.WriteLine("\r\n\t" + (myItem as EmailMessage).Sender.Name);
        Console.WriteLine("\t" + myItem.DateTimeReceived);
    }
}

if (findResults.MoreAvailable)
{
    // Get the remaining items by using subsequent paged find item calls using offsets.
} 
' Create a search filter that returns only e-mail messages.
Dim isEqualToEmail As SearchFilter = New SearchFilter.IsEqualTo(ItemSchema.ItemClass, "IPM.Note")

' Create an ItemView with a page size of 10.
Dim view As New ItemView(10)

' Indicate that the base property will return the Id, 
' Subject, DateTimeReceived, and Sender.
view.PropertySet = New PropertySet(BasePropertySet.IdOnly)
view.PropertySet.Add(ItemSchema.Subject)
view.PropertySet.Add(ItemSchema.DateTimeReceived)
view.PropertySet.Add(EmailMessageSchema.Sender)

' Order the search results by the DateTimeReceived in ascending order.
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending)

' Set the traversal to shallow. Shallow is the default option. 
' Other options are Associated and SoftDeleted.
view.Traversal = ItemTraversal.Shallow

' Set the grouping for the search results.
Dim grouping As New Grouping
grouping.GroupOn = EmailMessageSchema.Subject
grouping.SortDirection = SortDirection.Descending
grouping.AggregateOn = ItemSchema.DateTimeReceived
grouping.AggregateType = AggregateType.Maximum

' Send the request to search the Inbox and get the grouped results.
Dim findResults As GroupedFindItemsResults(Of Item) = _
    service.FindItems(WellKnownFolderName.Inbox, isEqualToEmail, view, grouping)

' Process each item.
For Each mygroup As ItemGroup(Of Item) In findResults.ItemGroups
    Console.WriteLine(vbCrLf & "Group Index: " & mygroup.GroupIndex)
    For Each myItem As EmailMessage In mygroup.Items
        Console.WriteLine(vbCrLf & vbTab & myItem.Sender.Name)
        Console.WriteLine(vbTab & myItem.DateTimeReceived)
    Next
Next
If findResults.MoreAvailable Then
    ' Get the remaining items by using subsequent paged find item calls by using offsets.
End If

The following example shows the XML that is sent by the FindItems method.

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"
      xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types" 
      xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2010" />
  </soap:Header>
  <soap:Body>
    <m:FindItem Traversal="Shallow">
      <m:ItemShape>
        <t:BaseShape>IdOnly</t:BaseShape>
        <t:AdditionalProperties>
          <t:FieldURI FieldURI="item:Subject" />
          <t:FieldURI FieldURI="item:DateTimeReceived" />
          <t:FieldURI FieldURI="message:Sender" />
        </t:AdditionalProperties>
      </m:ItemShape>
      <m:IndexedPageItemView MaxEntriesReturned="10" Offset="0" BasePoint="Beginning" />
      <m:GroupBy Order="Descending">
        <t:FieldURI FieldURI="item:Subject" />
        <t:AggregateOn Aggregate="Maximum">
          <t:FieldURI FieldURI="item:DateTimeReceived" />
        </t:AggregateOn>
      </m:GroupBy>
      <m:Restriction>
        <t:IsEqualTo>
          <t:FieldURI FieldURI="item:ItemClass" />
          <t:FieldURIOrConstant>
            <t:Constant Value="IPM.Note" />
          </t:FieldURIOrConstant>
        </t:IsEqualTo>
      </m:Restriction>
      <m:SortOrder>
        <t:FieldOrder Order="Ascending">
          <t:FieldURI FieldURI="item:DateTimeReceived" />
        </t:FieldOrder>
      </m:SortOrder>
      <m:ParentFolderIds>
        <t:DistinguishedFolderId Id="inbox" />
      </m:ParentFolderIds>
    </m:FindItem>
  </soap:Body>
</soap:Envelope>

The following example shows the XML that is returned by using the FindItems method. The ItemId and ChangeKey attributes have been shortened to preserve readability. In this example, there are three groups in this 10-item response.

<s:Envelope xmlns:s="https://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="14" 
       MinorVersion="0" 
       MajorBuildNumber="639" 
       MinorBuildNumber="20" 
       Version="Exchange2010" 
       xmlns:h="https://schemas.microsoft.com/exchange/services/2006/types"
       xmlns="https://schemas.microsoft.com/exchange/services/2006/types" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:FindItemResponse xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"
         xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:FindItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:RootFolder IndexedPagingOffset="13" TotalItemsInView="26" IncludesLastItemInRange="false">
            <t:Groups>
              <t:GroupedItems>
                <t:GroupIndex>Testing</t:GroupIndex>
                <t:Items>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Testing</t:Subject>
                    <t:DateTimeReceived>2009-10-14T16:31:42Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserTwo</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Testing</t:Subject>
                    <t:DateTimeReceived>2009-10-14T16:31:50Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserTwo</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Testing</t:Subject>
                    <t:DateTimeReceived>2009-10-14T19:44:25Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserOne</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Testing</t:Subject>
                    <t:DateTimeReceived>2009-10-14T19:45:02Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserOne</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Testing</t:Subject>
                    <t:DateTimeReceived>2009-10-14T19:48:02Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserOne</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Testing</t:Subject>
                    <t:DateTimeReceived>2009-10-14T19:48:23Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserOne</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                </t:Items>
              </t:GroupedItems>
              <t:GroupedItems>
                <t:GroupIndex>Over there</t:GroupIndex>
                <t:Items>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Over there</t:Subject>
                    <t:DateTimeReceived>2009-10-14T19:43:34Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserOne</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Over there</t:Subject>
                    <t:DateTimeReceived>2009-10-14T19:45:47Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserTwo</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                </t:Items>
              </t:GroupedItems>
              <t:GroupedItems>
                <t:GroupIndex>Interesting</t:GroupIndex>
                <t:Items>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Interesting</t:Subject>
                    <t:DateTimeReceived>2009-10-02T22:02:18Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserTwo</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                  <t:Message>
                    <t:ItemId Id="AQMkAGEyYzQ" ChangeKey="CQAAABYAAA" />
                    <t:Subject>Interesting</t:Subject>
                    <t:DateTimeReceived>2009-10-05T20:10:11Z</t:DateTimeReceived>
                    <t:Sender>
                      <t:Mailbox>
                        <t:Name>E14UserTwo</t:Name>
                        <t:MailboxType>OneOff</t:MailboxType>
                      </t:Mailbox>
                    </t:Sender>
                  </t:Message>
                </t:Items>
              </t:GroupedItems>
            </t:Groups>
          </m:RootFolder>
        </m:FindItemResponseMessage>
      </m:ResponseMessages>
    </m:FindItemResponse>
  </s:Body>
</s:Envelope>

This example assumes that the ExchangeService object named service is correctly configured to connect to the user’s Client Access server.

Compiling the code

For information about compiling this code, see Getting started with the EWS Managed API 2.0.

Robust programming

  • Write appropriate error handling code for common search errors.

  • Review the client request XML that is sent to the Exchange server.

  • Review the server response XML that is sent from the Exchange server.

  • Set the service binding as shown in Setting the Exchange service URL by using the EWS Managed API 2.0. Do not hard code URLs because if mailboxes move, they might be serviced by a different Client Access server. If the client cannot connect to the service, retry setting the binding by using the AutodiscoverUrl(String) method.

  • Set the target Exchange Web Services schema version by setting the requestedServerVersion parameter of the ExchangeService constructor. For more information, see Versioning EWS requests by using the EWS Managed API 2.0.

Security

  • Use HTTP with SSL for all communication between client and server.

  • Always validate the server certificate that is used for establishing the SSL connections. For more information, see Validating X509 certificates by using the EWS Managed API 2.0.

  • Do not include user names and passwords in trace files.

  • Verify that Autodiscover lookups that use HTTP GET to find an endpoint always prompt for user confirmation; otherwise, they should be blocked.