Я пытаюсь создать процесс, который будет работать в фоновом режиме непрерывно. Эта служба будет следить за входящими новыми сообщениями электронной почты в папке «Входящие» и «Разбирать электронную почту». У нас есть Exchange Server, поэтому я использую API с управлением Exchange. Я создал класс C#, как указано в документации EWS. У меня есть экземпляр службы, который я тестировал отдельно. Я создаю потоковые уведомления и новое почтовое событие в папке «Входящие». Но я не знаю, как тестировать приложение, так как я запустил окно консоли приложения. Я отправил почту в свой почтовый ящик вручную, но не знаю, когда будет запускаться событие New mail, и если оно отобразит сообщение на консоли. Я не уверен, что нам нужно иметь что-то присутствующее или настроенное на стороне сервера. Я хотел бы знать, есть ли способ сохранить этот процесс без 30 минут. так как я хочу создать сервис. Пожалуйста, ищите помощи.EWS управляемый API, как проверить приложение C#
namespace NewMailNotification
{
class Program
{
static void Main(string[] args)
{
ExchangeService service = new ExchangeService (ExchangeVersion.Exchange2010_SP2);
service.Url = null;
string user = ConfigurationSettings.AppSettings["user"];
string userid = ConfigurationSettings.AppSettings["user-id"];
string PWD = ConfigurationSettings.AppSettings["PWD"];
try
{
service.Credentials = new WebCredentials(user.ToString(), PWD.ToString());
service.AutodiscoverUrl(userid.ToString(), RedirectionUrlValidationCallback);
}
catch (Exception e)
{
Console.WriteLine("---" + e.Message);
}
SetStreamingNotification(service);
}
private static bool RedirectionUrlValidationCallback(string RedirectionUrl)
{
bool result = false;
Uri redirectionUri = new Uri(RedirectionUrl);
if (redirectionUri.Scheme == "https")
{
Console.WriteLine(redirectionUri);
result = true;
}
return result;
}
//Notification subscription and event
static void SetStreamingNotification(ExchangeService service)
{
//subscribe to streaming notification onthe inbox folder, and listen to newmail
StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox },
EventType.NewMail,
EventType.Created,
EventType.Deleted);
StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 30);
connection.AddSubscription(streamingsubscription);
//Delegate an event handlers
connection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
connection.OnSubscriptionError +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError);
connection.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
connection.Open();
Console.WriteLine("--------- StreamSubscription event -------");
}
static void OnEvent(object sender, NotificationEventArgs args)
{
StreamingSubscription subscription = args.Subscription;
//Loop through all item-related events.
foreach(NotificationEvent notification in args.Events)
{
switch (notification.EventType)
{
case EventType.NewMail:
Console.WriteLine("\n----------------Mail Received-----");
break;
case EventType.Created:
Console.WriteLine("\n-------------Item or Folder deleted-------");
break;
case EventType.Deleted:
Console.WriteLine("\n------------Item or folder deleted---------");
break;
}
//Display the notification identifier.
if (notification is ItemEvent)
{
//The notificationEvent for a folder is a Folderevent.
FolderEvent folderevent = (FolderEvent)notification;
Console.WriteLine("\nFolderId: " + folderevent.FolderId.UniqueId);
}
else
{
//The notificationevent for a foler is a FolderEvent
FolderEvent folderevent = (FolderEvent)notification;
Console.WriteLine("\nFolderId: " + folderevent.FolderId.UniqueId);
}
}
}
static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
{
StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;
//ask the usr if they want to reconnect or close the connection
ConsoleKeyInfo cki;
Console.WriteLine("The connection to the subscription is disconnected.");
Console.WriteLine("Do you want to reconnect to the subscription? Y/N");
while (true)
{
cki = Console.ReadKey(true);
{
if (cki.Key == ConsoleKey.Y)
{
connection.Open();
Console.WriteLine("Connection Open.");
Console.WriteLine("\r\n");
break;
}
else if (cki.Key == ConsoleKey.N)
{
// Signal.Set();
bool isOpen = connection.IsOpen;
if (isOpen == true)
{
connection.Close();
}
else
{
break;
}
}
}//while end
}
}
static void OnError(object sender,SubscriptionErrorEventArgs args)
{
Exception e=args.Exception;
Console.WriteLine("\n------------Error----"+e.Message+"----------");
}
}//class end
} // конец пространства имен