简体   繁体   中英

Identify item type when handling event in Exchange Web Services (EWS)

I'm using streaming notifications with the EWS API. On the event handler I pick up the fact that an item has been modified, but my attempt to bind the modified item to an email message fails. The error message is specifically

The item type returned by the service (Appointment) isn't compatible with the requested item type (EmailMessage).

It seems like there must be a way to identify the item type before attempting to bind it, but I'm not sure what that is. The error occurs on attempting to Bind , so I can't simply check for null. I could resort to try/catch , but would prefer to do this properly if there is a better way?

Summarised code:

void streamingConnection_OnNotificationEvent(object sender, NotificationEventArgs args)
{
    foreach (NotificationEvent notificationEvent in args.Events)
    {
        ItemEvent itemEvent = notificationEvent as ItemEvent;
        if (itemEvent != null) HandleItemEvent(itemEvent);
    }
}

private void HandleItemEvent(ItemEvent itemEvent)
{
    switch (itemEvent.EventType)
    {
        case EventType.Modified:
            EmailMessage modifiedMessage = EmailMessage.Bind(this.ExchangeService, itemEvent.ItemId);
            // error occurs on Bind if the item type is not an EmailMessage (eg, an Appointment)
            break;
    }
}

Looks like the correct way to bind is to use the generic Item.Bind method, then check if the item is an EmailMessage type. To do this robustly (handle potential issues where the item is moved before it can be bound) I put the logic into a method, similar to below:

private EmailMessage BindToEmailMessage(ItemId itemId)
{
    try
    {
        Item item = Item.Bind(this.ExchangeService, itemId);
        if (item is EmailMessage) return item as EmailMessage;
        else return null;
    }
    catch
    {
        return null;
    }
}

Then change the logic in my existing method to

EmailMessage modifiedMessage = BindToEmailMessage(itemEvent.ItemId);
if (modifiedMessage != null) ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM