在Exchange Web Services (EWS)中处理事件时,确定项目类型

本文关键字:类型 项目 处理事件 Web Exchange Services EWS | 更新日期: 2023-09-27 18:08:51

我正在使用EWS API的流通知。在事件处理程序上,我发现一个项目已被修改,但是我试图将修改后的项目绑定到电子邮件消息失败了。错误信息是

服务返回的项目类型(Appointment)不兼容

似乎在尝试绑定它之前必须有一种方法来识别项目类型,但我不确定那是什么。错误发生在尝试Bind,所以我不能简单地检查null。我可以求助于try/catch,但如果有更好的方法,我更愿意这样做。

总结代码:

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

在Exchange Web Services (EWS)中处理事件时,确定项目类型

看起来正确的绑定方式是使用通用的Item.Bind方法,然后检查项目是否为EmailMessage类型。为了健壮地做到这一点(处理项目在绑定之前被移动的潜在问题),我将逻辑放入一个方法中,如下所示:

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

然后将我现有方法中的逻辑更改为

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