多个 PushNotification 订阅有些可以正常工作,有些则不能

发布于 2024-10-26 00:53:43 字数 8605 浏览 1 评论 0原文

我尝试在 Exchange 开发论坛上发布此内容,但没有得到任何回复,所以我会在这里尝试。 论坛链接

我有一个 Windows 服务,每十五分钟触发一次,以查看是否有任何订阅需要创建或更新。我针对 Exchange 2007 SP1 使用托管 API v1.1。我有一个表存储所有想要监视邮箱的用户。这样,当通知进入“监听服务”时,我就能够查找用户并访问消息以将其登录到我们正在构建的应用程序中。在表中,我有以下列存储订阅信息:

  1. SubscriptionId - VARCHAR(MAX)
  2. Watermark - VARCHAR(MAX)
  3. LastStatusUpdate - DATETIME

我的服务调用一个查询所需数据的函数(基于它正在执行的函数)。如果用户还没有订阅,该服务将创建一个订阅。我正在使用模拟来访问邮箱。这是我的“ActiveSubscription”方法,当用户需要创建或更新订阅时会触发该方法。

private void ActivateSubscription(User user)
{
  if (user.ADGUID.HasValue)
  {
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Settings.ActiveDirectoryServerName, Settings.ActiveDirectoryRootContainer);

    using (UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.Guid, user.ADGUID.Value.ToString()))
    {
      ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SID, up.Sid.Value);
    }
  }
  else
  {
    ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user.EmailAddress);
  }

  PushSubscription pushSubscription = ewService.SubscribeToPushNotifications(
    new FolderId[] { WellKnownFolderName.Inbox, WellKnownFolderName.SentItems },
    Settings.ListenerService, 30, user.Watermark,
    EventType.NewMail, EventType.Created);

  user.Watermark = pushSubscription.Watermark;
  user.SubscriptionID = pushSubscription.Id;
  user.SubscriptionStatusDateTime = DateTime.Now.ToLocalTime();

  _users.Update(user);
}

我们还运行了以下 cmdlet,为我们正在访问 EWS 的用户提供模拟 Exchange Server 的能力。

Get-ExchangeServer | where {$_.IsClientAccessServer -eq $TRUE} | ForEach-Object {Add-ADPermission -Identity $_.distinguishedname -User (Get-User -Identity mailmonitor | select-object).identity -extendedRight ms-Exch-EPI-Impersonation}

上面的“ActivateSubscription”代码按预期工作。或者说我是这么想的。当我测试它时,我让它监视我的邮箱,效果很好。我必须解决的唯一问题是,当收件箱中的项目是新邮件时,订阅会触发两次,我收到了 NewMail 事件和 Created 事件的通知。我实施了一项解决方案,检查以确保该消息尚未记录在我的侦听服务上。一切都很好。

今天,我们开始测试同时监控两个邮箱。这两个邮箱是我的,另一个是开发者的邮箱。我们发现了最奇怪的行为。我的订阅按预期进行。但他没有,他的订阅的传入部分工作正常,但他向监听服务发送的任何电子邮件都从未收到通知。查看 Exchange 上的邮箱属性,我没有发现他的邮箱和我的邮箱有任何区别。我们甚至比较了 Outlook 中的选项/设置。我不明白为什么它在我的邮箱上有效,而在他的邮箱上无效。

创建订阅时是否缺少某些内容。我不认为有,因为我的订阅按预期工作。

我的监听服务代码运行得很好。我已将代码放在下面,以防有人想查看它以确保这不是问题。

提前致谢,特里

监听服务代码:

/// <summary>
/// Summary description for PushNotificationClient
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class PushNotificationClient : System.Web.Services.WebService, INotificationServiceBinding
{
  ExchangeService ewService = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

  public PushNotificationClient()
  {
    //todo: init the service.
    SetupExchangeWebService();
  }

  private void SetupExchangeWebService()
  {
    ewService.Credentials = Settings.ServiceCreds;
    try
    {
      ewService.AutodiscoverUrl(Settings.AutoDiscoverThisEmailAddress);
    }
    catch (AutodiscoverRemoteException e)
    {
      //log auto discovery failed
      ewService.Url = Settings.ExchangeService;
    }
  }

  public SendNotificationResultType SendNotification(SendNotificationResponseType SendNotification1)
  {
    using (var _users = new ExchangeUser(Settings.SqlConnectionString))
    {
      var result = new SendNotificationResultType();

      var responseMessages = SendNotification1.ResponseMessages.Items;
      foreach (var responseMessage in responseMessages)
      {
        if (responseMessage.ResponseCode != ResponseCodeType.NoError)
        {
          //log error and unsubscribe.
          result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
          return result;
        }

        var sendNoficationResponse = responseMessage as SendNotificationResponseMessageType;
        if (sendNoficationResponse == null)
        {
          result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
          return result;
        }

        var notificationType = sendNoficationResponse.Notification;
        var subscriptionId = notificationType.SubscriptionId;
        var previousWatermark = notificationType.PreviousWatermark;

        User user = _users.GetById(subscriptionId);
        if (user != null)
        {
          if (user.MonitorEmailYN == true)
          {
            BaseNotificationEventType[] baseNotifications = notificationType.Items;

            for (int i = 0; i < notificationType.Items.Length; i++)
            {
              if (baseNotifications[i] is BaseObjectChangedEventType)
              {
                var bocet = baseNotifications[i] as BaseObjectChangedEventType;
                AccessCreateDeleteNewMailEvent(bocet, ref user);
              }
            }

            _PreviousItemId = null;
          }
          else
          {
            user.SubscriptionID = String.Empty;
            user.SubscriptionStatusDateTime = null;
            user.Watermark = String.Empty;
            _users.Update(user);

            result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
            return result;
          }

          user.SubscriptionStatusDateTime = DateTime.Now.ToLocalTime();
          _users.Update(user);
        }
        else
        {
          result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
          return result;
        }
      }

      result.SubscriptionStatus = SubscriptionStatusType.OK;
      return result;
    }
  }

  private string _PreviousItemId;
  private void AccessCreateDeleteNewMailEvent(BaseObjectChangedEventType bocet, ref User user)
  {
    var watermark = bocet.Watermark;
    var timestamp = bocet.TimeStamp.ToLocalTime();
    var parentFolderId = bocet.ParentFolderId;

    if (bocet.Item is ItemIdType)
    {
      var itemId = bocet.Item as ItemIdType;
      if (itemId != null)
      {
        if (string.IsNullOrEmpty(_PreviousItemId) || (!string.IsNullOrEmpty(_PreviousItemId) && _PreviousItemId != itemId.Id))
        {
          ProcessItem(itemId, ref user);
          _PreviousItemId = itemId.Id;
        }
      }
    }

    user.SubscriptionStatusDateTime = timestamp;
    user.Watermark = watermark;
    using (var _users = new ExchangeUser(Settings.SqlConnectionString))
    {
      _users.Update(user);
    }

  }

  private void ProcessItem(ItemIdType itemId, ref User user)
  {
    try
    {
      ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user.EmailAddress);
      EmailMessage email = EmailMessage.Bind(ewService, itemId.Id);
      using (var _entity = new SalesAssistantEntityDataContext(Settings.SqlConnectionString))
      {
        var direction = EmailDirection.Incoming;
        if (email.From.Address == user.EmailAddress)
        {
          direction = EmailDirection.Outgoing;
        }


        int? bodyType = (int)email.Body.BodyType;

        var _HtmlToRtf = new HtmlToRtf();
        var message = _HtmlToRtf.ConvertHtmlToText(email.Body.Text);

        bool? IsIncoming = Convert.ToBoolean((int)direction);

        if (IsIncoming.HasValue && IsIncoming.Value == false)
        {
          foreach (var emailTo in email.ToRecipients)
          {
            _entity.InsertMailMessage(email.From.Address, emailTo.Address, email.Subject, message, bodyType, IsIncoming);
          }
        }
        else
        {
          if (email.ReceivedBy != null)
          {
            _entity.InsertMailMessage(email.From.Address, email.ReceivedBy.Address, email.Subject, message, bodyType, IsIncoming);
          }
          else
          {
            var emailToFind = user.EmailAddress;
            if (email.ToRecipients.Any(x => x.Address == emailToFind))
            {
              _entity.InsertMailMessage(email.From.Address, emailToFind, email.Subject, message, bodyType, IsIncoming);
            }
          }
        }
      }
    }
    catch(Exception e)
    {
      //Log exception 
      using (var errorHandler = new ErrorHandler(Settings.SqlConnectionString))
      {
        errorHandler.LogException(e, user.UserID, user.SubscriptionID, user.Watermark, user.SubscriptionStatusDateTime);
      }
      throw e;
    }
  }

}

I tried posting this on the Exchange Development forum and didnt get any replies, so I will try here. Link to forum

I have a windows services that fires every fifteen minutes to see if there is any subscriptions that need to be created or updated. I am using the Managed API v1.1 against Exchange 2007 SP1. I have a table that stores all the users that want there mailbox monitored. So that when a notifcation comes in to the "Listening Service" I am able to look up the user and access the message to log it into the application we are building. In the table I have the following columns that store the subscription information:

  1. SubscriptionId - VARCHAR(MAX)
  2. Watermark - VARCHAR(MAX)
  3. LastStatusUpdate - DATETIME

My services calls a function that queries the data needed (based on which function it is doing). If the user doesn't have a subscription already the service will go and create one. I am using impersonation to access the mailboxes. Here is my "ActiveSubscription" method that is fired when a user needs the subscription either created or updated.

private void ActivateSubscription(User user)
{
  if (user.ADGUID.HasValue)
  {
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Settings.ActiveDirectoryServerName, Settings.ActiveDirectoryRootContainer);

    using (UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.Guid, user.ADGUID.Value.ToString()))
    {
      ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SID, up.Sid.Value);
    }
  }
  else
  {
    ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user.EmailAddress);
  }

  PushSubscription pushSubscription = ewService.SubscribeToPushNotifications(
    new FolderId[] { WellKnownFolderName.Inbox, WellKnownFolderName.SentItems },
    Settings.ListenerService, 30, user.Watermark,
    EventType.NewMail, EventType.Created);

  user.Watermark = pushSubscription.Watermark;
  user.SubscriptionID = pushSubscription.Id;
  user.SubscriptionStatusDateTime = DateTime.Now.ToLocalTime();

  _users.Update(user);
}

We have also ran the following cmdlet to give the user we are accessing the EWS with the ability to impersonate on the Exchange Server.

Get-ExchangeServer | where {$_.IsClientAccessServer -eq $TRUE} | ForEach-Object {Add-ADPermission -Identity $_.distinguishedname -User (Get-User -Identity mailmonitor | select-object).identity -extendedRight ms-Exch-EPI-Impersonation}

The "ActivateSubscription" code above works as expected. Or so I thought. When I was testing it I had it monitoring my mailbox and it worked great. The only problem I had to work around was that the subscription was firing twice when the item was a new mail in the inbox, I got a notification for the NewMail event and Created event. I implemented a work around that checks to make sure the message hasn't already been logged on my Listening service. It all worked great.

Today, we started testing two mailboxes being monitor at the same time. The two mailboxes were mine and another developers mailbox. We found the strangest behavior. My subscription worked as expected. But his didn't, the incoming part of his subscription work properly but any email he sent out the listening service never was sent a notification. Looking at the mailbox properties on Exchange I don't see any difference between his mailbox and mine. We even compared options/settings in Outlook. I can see no reasons why it works on my mailbox and not on his.

Is there something that I am missing when creating the subscription. I didn't think there was since my subscription works as expected.

My listening service code works perfectly well. I have placed the code below incase someone wants to see it to make sure it is not the issue.

Thanks in advance, Terry

Listening Service Code:

/// <summary>
/// Summary description for PushNotificationClient
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class PushNotificationClient : System.Web.Services.WebService, INotificationServiceBinding
{
  ExchangeService ewService = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

  public PushNotificationClient()
  {
    //todo: init the service.
    SetupExchangeWebService();
  }

  private void SetupExchangeWebService()
  {
    ewService.Credentials = Settings.ServiceCreds;
    try
    {
      ewService.AutodiscoverUrl(Settings.AutoDiscoverThisEmailAddress);
    }
    catch (AutodiscoverRemoteException e)
    {
      //log auto discovery failed
      ewService.Url = Settings.ExchangeService;
    }
  }

  public SendNotificationResultType SendNotification(SendNotificationResponseType SendNotification1)
  {
    using (var _users = new ExchangeUser(Settings.SqlConnectionString))
    {
      var result = new SendNotificationResultType();

      var responseMessages = SendNotification1.ResponseMessages.Items;
      foreach (var responseMessage in responseMessages)
      {
        if (responseMessage.ResponseCode != ResponseCodeType.NoError)
        {
          //log error and unsubscribe.
          result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
          return result;
        }

        var sendNoficationResponse = responseMessage as SendNotificationResponseMessageType;
        if (sendNoficationResponse == null)
        {
          result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
          return result;
        }

        var notificationType = sendNoficationResponse.Notification;
        var subscriptionId = notificationType.SubscriptionId;
        var previousWatermark = notificationType.PreviousWatermark;

        User user = _users.GetById(subscriptionId);
        if (user != null)
        {
          if (user.MonitorEmailYN == true)
          {
            BaseNotificationEventType[] baseNotifications = notificationType.Items;

            for (int i = 0; i < notificationType.Items.Length; i++)
            {
              if (baseNotifications[i] is BaseObjectChangedEventType)
              {
                var bocet = baseNotifications[i] as BaseObjectChangedEventType;
                AccessCreateDeleteNewMailEvent(bocet, ref user);
              }
            }

            _PreviousItemId = null;
          }
          else
          {
            user.SubscriptionID = String.Empty;
            user.SubscriptionStatusDateTime = null;
            user.Watermark = String.Empty;
            _users.Update(user);

            result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
            return result;
          }

          user.SubscriptionStatusDateTime = DateTime.Now.ToLocalTime();
          _users.Update(user);
        }
        else
        {
          result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
          return result;
        }
      }

      result.SubscriptionStatus = SubscriptionStatusType.OK;
      return result;
    }
  }

  private string _PreviousItemId;
  private void AccessCreateDeleteNewMailEvent(BaseObjectChangedEventType bocet, ref User user)
  {
    var watermark = bocet.Watermark;
    var timestamp = bocet.TimeStamp.ToLocalTime();
    var parentFolderId = bocet.ParentFolderId;

    if (bocet.Item is ItemIdType)
    {
      var itemId = bocet.Item as ItemIdType;
      if (itemId != null)
      {
        if (string.IsNullOrEmpty(_PreviousItemId) || (!string.IsNullOrEmpty(_PreviousItemId) && _PreviousItemId != itemId.Id))
        {
          ProcessItem(itemId, ref user);
          _PreviousItemId = itemId.Id;
        }
      }
    }

    user.SubscriptionStatusDateTime = timestamp;
    user.Watermark = watermark;
    using (var _users = new ExchangeUser(Settings.SqlConnectionString))
    {
      _users.Update(user);
    }

  }

  private void ProcessItem(ItemIdType itemId, ref User user)
  {
    try
    {
      ewService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, user.EmailAddress);
      EmailMessage email = EmailMessage.Bind(ewService, itemId.Id);
      using (var _entity = new SalesAssistantEntityDataContext(Settings.SqlConnectionString))
      {
        var direction = EmailDirection.Incoming;
        if (email.From.Address == user.EmailAddress)
        {
          direction = EmailDirection.Outgoing;
        }


        int? bodyType = (int)email.Body.BodyType;

        var _HtmlToRtf = new HtmlToRtf();
        var message = _HtmlToRtf.ConvertHtmlToText(email.Body.Text);

        bool? IsIncoming = Convert.ToBoolean((int)direction);

        if (IsIncoming.HasValue && IsIncoming.Value == false)
        {
          foreach (var emailTo in email.ToRecipients)
          {
            _entity.InsertMailMessage(email.From.Address, emailTo.Address, email.Subject, message, bodyType, IsIncoming);
          }
        }
        else
        {
          if (email.ReceivedBy != null)
          {
            _entity.InsertMailMessage(email.From.Address, email.ReceivedBy.Address, email.Subject, message, bodyType, IsIncoming);
          }
          else
          {
            var emailToFind = user.EmailAddress;
            if (email.ToRecipients.Any(x => x.Address == emailToFind))
            {
              _entity.InsertMailMessage(email.From.Address, emailToFind, email.Subject, message, bodyType, IsIncoming);
            }
          }
        }
      }
    }
    catch(Exception e)
    {
      //Log exception 
      using (var errorHandler = new ErrorHandler(Settings.SqlConnectionString))
      {
        errorHandler.LogException(e, user.UserID, user.SubscriptionID, user.Watermark, user.SubscriptionStatusDateTime);
      }
      throw e;
    }
  }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过潦 2024-11-02 00:53:43

我有两个答案给你。
首先,您必须为每个用户创建一个 ExchangeService 实例。就像我理解您的代码一样,您只需创建一个实例并切换模拟,这是不受支持的。我开发了一个与你的非常相似的Windows服务。我的任务是在 CRM 和 Exchange 之间同步邮件。因此,在启动时,我为每个用户创建一个实例,并在应用程序运行时缓存它。

现在介绍缓存模式。使用缓存模式与不使用缓存模式之间的区别只是时间上的差距。在缓存模式下,Outlook 会不时进行同步。并且未及时缓存。当您使用缓存模式并希望事件立即出现在 Exchange 服务器上时,您可以按 Outlook 中的“发送和接收”按钮强制同步。

希望对你有帮助...

I have two answers for you.
At first you will have to create one instance of ExchangeService per user. Like I understand your Code you just create one instance and switch the impersonation, which is not supported. I developed a windowsservice which is pretty similar to yours. Mine is synchronising the mails between our CRM and Exchange. So at startup I create an instance per user and Cache it as long as the application runs.

Now about cache-mode. The diffrence between using cache-mode and not is just a timing gab. In cache-mode Outlook synchronizes from time to time. And non cached it's in time. When you use the cache-mode and want the Events immediatly on your Exchange-Server you can press the "send and receive"-button in Outlook to force the sync.

Hope that helps you...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文