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

冷暖自知 提交于 2019-12-10 18:33:01

问题


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;
    }
}

回答1:


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) ...


来源:https://stackoverflow.com/questions/24259082/identify-item-type-when-handling-event-in-exchange-web-services-ews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!