最近仅通过Web迁移到Outlook 365,并且由于我正在其他应用程序中工作而错过了通知弹出窗口。所以我写了一个WPF应用程序来为我做这件事。它工作得很好,但当我锁定计算机并炸毁它时除外。我遇到的最后一个错误是流订阅在SetStreamingNotifications方法中超时。这是我的代码。其他错误通常在OnDisconnect尝试续订时发生。同样,仅在会议/午餐期间计算机被锁定一段时间后,才会出现问题。有什么我想念的吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Exchange.WebServices.Data;
using System.IO;
using System.Configuration;
namespace Outlook365_Notification
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
static int unreadMessages = 0;
static ExchangeService _service;
static int unreadMessagesFound = 0;
private string _LabelText;
public string LabelText
{
set
{
_LabelText = value;
}
}
public MainWindow()
{
InitializeComponent();
StartServices();
}
public void StartServices()
{
GetCredentials();
SetStreamingNotifications();
ShowUnreadMessages();
}
public void ShowUnreadMessages()
{
string loc = "Start";
try
{
loc = "Clear Items";
listView.Items.Clear();
loc = "Check service";
if (_service == null)
{
loc = "Create Service";
CreateExchangeService();
}
loc = "SearchFilter";
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
loc = "FindItemsResults<Item>";
FindItemsResults<Item> findResults = _service.FindItems(
WellKnownFolderName.Inbox,
sf,
new ItemView(50));
loc = "unreadMessagesFound";
unreadMessagesFound = findResults.Items.Count;
foreach (Item i in findResults)
{
loc = "EmailMessage";
EmailMessage email = EmailMessage.Bind(_service, new ItemId(i.Id.ToString()));
loc = "Add Item";
this.listView.Items.Add(email);
}
loc = "Dispatcher Invoke";
this.Dispatcher.Invoke(() =>
{
this.lblConnectedAs.Content = emailAddress;
});
}
catch(Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - ShowUnreadMessages");
}
}
static void CreateExchangeService()
{
string loc = "Start";
try
{
loc = "_service";
_service = new ExchangeService(ExchangeVersion.Exchange2016)
{
Credentials = new WebCredentials(emailAddress, emailPW)
};
loc = ".Url";
_service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
}
catch(Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - CreateExchangeService");
}
}
public void SetStreamingNotifications()
{
string loc = "Start";
try
{
loc = "service NULL";
if (_service == null)
{
loc = "CreateExchangeService()";
CreateExchangeService();
}
loc = "Streaming Subscription";
// Subscribe to streaming notifications on the Inbox folder, and listen
// for "NewMail", "Created", and "Deleted" events.
StreamingSubscription streamingsubscription = _service.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Inbox },
EventType.NewMail,
EventType.Created,
EventType.Deleted);
loc = "connection";
StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(_service, 30);
loc = "Add Subscription";
connection.AddSubscription(streamingsubscription);
// Delegate event handlers.
loc = "Delegate OnEvent";
connection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
loc = "Delegate OnError";
connection.OnSubscriptionError +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError);
loc = "Delegate OnDisconnect";
connection.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
connection.Open();
}
catch(Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - SetStreamingNotifications");
}
}
public void SetDisconnect()
{
string loc = "Start";
try
{
loc = "Disconnected label";
this.Dispatcher.Invoke(() =>
{
this.lblConnectedAs.Content = "DISCONNECTED";
});
}
catch (Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - SetDisconnect");
}
}
private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
string loc = "";
try
{
loc = "Dispatcher Show";
this.Dispatcher.Invoke(() =>
{
loc = "Show disconnect";
MainWindow mwDisconnect = new MainWindow();
mwDisconnect.SetDisconnect();
});
loc = "connection";
// Cast the sender as a StreamingSubscriptionConnection object.
StreamingSubscriptionConnection renew = (StreamingSubscriptionConnection)sender;
if (renew.CurrentSubscriptions.Count() > 0)
{
loc = "Open";
// reopen connection to keep it going
renew.Open();
}
else
{
loc = "StartServices";
MainWindow mw = new MainWindow();
mw.StartServices();
//SetStreamingNotifications();
}
}
catch(Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - OnDisconnect");
}
}
public void OnEvent(object sender, NotificationEventArgs args)
{
string loc = "";
try
{
loc = "subscription";
StreamingSubscription subscription = args.Subscription;
// Loop through all item-related events.
foreach (NotificationEvent notification in args.Events)
{
loc = "Switch EventType";
switch (notification.EventType)
{
case EventType.NewMail:
//Console.WriteLine("\n-------------Mail created:-------------");
break;
case EventType.Created:
//this.lblMessages.Content = "Hello";
break;
// //Console.WriteLine("\n-------------Item or folder created:-------------");
// break;
//case EventType.Deleted:
// //Console.WriteLine("\n-------------Item or folder deleted:-------------");
// break;
}
loc = "ItemEvent && EventType";
// Display the notification identifier.
if (notification is ItemEvent && notification.EventType == EventType.NewMail)
{
loc = "ItemEvent && EventType - itemEvent";
// The NotificationEvent for an e-mail message is an ItemEvent.
ItemEvent itemEvent = (ItemEvent)notification;
loc = "ItemEvent && EventType - email";
EmailMessage email = EmailMessage.Bind(_service, new ItemId(itemEvent.ItemId.ToString()));
loc = "Dispatcher Invoke";
this.Dispatcher.Invoke(() =>
{
loc = "Dispatcher Invoke ShowUnreadMessages";
ShowUnreadMessages();
loc = "Dispatcher Invoke WindowState";
WindowState = WindowState.Normal;
loc = "Dispatcher Invoke Activate";
Application.Current.MainWindow.Activate();
});
//this.lblMessages.Content = "New mail has arrived!";
//loc = "WriteLine";
//Console.WriteLine("\nItemId: " + itemEvent.ItemId.UniqueId);
}
//else
//{
// // The NotificationEvent for a folder is an FolderEvent.
// FolderEvent folderEvent = (FolderEvent)notification;
// Console.WriteLine("\nFolderId: " + folderEvent.FolderId.UniqueId);
//}
}
}
catch(Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - OnEvent");
}
}
static void OnError(object sender, SubscriptionErrorEventArgs args)
{
string loc = "Start";
try
{
loc = "args.Exception";
// Handle error conditions.
Exception e = args.Exception;
MessageBox.Show(string.Format("Error Details: {0}", loc + ": " + e.Message), "Error - OnError Details");
//loc = "WriteLine";
//Console.WriteLine("\n-------------Error ---" + e.Message + "-------------");
}
catch(Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - OnError");
}
}
static void GetCredentials()
{
string loc = "Start";
try
{
loc = "Email";
emailAddress = ConfigurationSettings.AppSettings.Get("EmailAddress");
loc = "PW";
emailPW = ConfigurationSettings.AppSettings.Get("EmailPW");
}
catch(Exception ex)
{
MessageBox.Show(string.Format("An error occured: {0}", loc + ": " + ex.Message), "Error - GetCredentials");
}
}
static string emailAddress = "";
static string emailPW = "";
}
}
TJ