我有一个用EWS managed api (v2.2)创建的应用程序,可以通知我新邮件的到来。我使用StreamingSubscription来监听邮箱事件。我注意到有时候NewMail事件没有被触发(我稍后在邮箱中看到未处理的邮件),并且没有连接/订阅异常被抛出,在一段时间之后,新邮件的接收就像什么也没发生一样...是什么原因导致了这种行为?交换日志中没有可疑的东西,事件就是没有被触发...有什么想法和建议吗?
谢谢。
谢谢。
public class ExchangeClient : IDisposable
{
private ExchangeService _exchange;
private SubscriptionBase _subscription;
private StreamingSubscriptionConnection _connection;
private bool _disposed;
private bool _disposing;
public event EventHandler<ExchangeEventArgs> ExchangeEvent;
public ExchangeClient(string userName, string password, string domain, ExchangeVersion version)
{
_exchange = new ExchangeService(version);
_exchange.Credentials = new WebCredentials(userName, password);
_exchange.AutodiscoverUrl(userName + "@" + domain);
var ids = new FolderId[2] { new FolderId(WellKnownFolderName.Root), new FolderId(WellKnownFolderName.Inbox) };
var events = new List<EventType>();
events.Add(EventType.NewMail);
_subscription = _exchange.SubscribeToStreamingNotifications(ids, events.ToArray());
_connection = new StreamingSubscriptionConnection(_exchange, 30);
_connection.AddSubscription((StreamingSubscription)_subscription);
_connection.OnNotificationEvent += OnNotificationEvent;
_connection.OnSubscriptionError += OnSubscriptionError;
_connection.OnDisconnect += OnDisconnect;
_connection.Open();
}
private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
if (!_disposing && _connection != null)
{
_connection.Open();
}
}
private void OnSubscriptionError(object sender, SubscriptionErrorEventArgs args)
{
throw args.Exception;
}
private void OnNotificationEvent(object sender, NotificationEventArgs args)
{
if (_subscription != null)
{
if (args.Subscription.Id == _subscription.Id)
{
foreach (var notificationEvent in args.Events)
{
switch (notificationEvent.EventType)
{
case EventType.Status:
break;
case EventType.NewMail:
NotificationReceived(new ExchangeEventArgs(
notificationEvent.EventType,
((ItemEvent)notificationEvent).ItemId, ((ItemEvent)notificationEvent).ParentFolderId));
break;
default:
break;
}
}
}
}
}
public void Disconnect()
{
if (_connection.IsOpen)
_connection.Close();
}
private void NotificationReceived(ExchangeEventArgs e)
{
if (ExchangeEvent != null)
{
ExchangeEvent(this, e);
}
}
public void Dispose()
{
_disposing = true;
Dispose(_disposing);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (_connection != null)
{
if (_connection.IsOpen)
_connection.Close();
_connection = null;
}
_exchange = null;
_disposed = true;
}
}
}