public void Disconnect() { if (_connection.IsOpen) { _connection.Close(); } }
/// <summary> /// Stops monitoring the Exchange server. /// </summary> public void Stop() { if (_subscriptionConnection.IsOpen) { _subscriptionConnection.Close(); } }
static void Main(string[] args) { var service = new ExchangeService { Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx") }; //service.AutodiscoverUrl("*****@*****.**", Redirect); var credentials = new WebCredentials("*****@*****.**", "password"); service.Credentials = credentials; var subscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail); var connection = new StreamingSubscriptionConnection(service, new StreamingSubscription[] { subscription }, 30); connection.OnNotificationEvent += Connection_OnNotificationEvent; connection.Open(); //var response = service.BindToFolders(new FolderId[] { WellKnownFolderName.Inbox }, PropertySet.FirstClassProperties); //var results = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue)); Console.ReadLine(); connection.Close(); }
/// <summary> /// Stop this service. /// </summary> protected override void OnStop() { try { emailSubscriptionConnection.Close(); } catch (Microsoft.Exchange.WebServices.Data.ServiceLocalException localException) { } emailSubscriptionConnection.RemoveSubscription(emailSubscription); emailSubscriptionConnection.Dispose(); Data.RfiIndexTable.Index.Dispose(); Data.SpamIndexTable.Index.Dispose(); //impersonator.Dispose(); this.eventLog.WriteEntry("RfiCoder has stopped", EventLogEntryType.Information); Logger.LoggerAsync.InstanceOf.GeneralLogger.Info("RfiCoder has stopped: {0}", EventLogEntryType.Information); }
public static void OnEvent(object sender, NotificationEventArgs args) { StreamingSubscription subscription = args.Subscription; foreach (NotificationEvent notification in args.Events) { switch (notification.EventType) { case EventType.NewMail: break; } if (notification is ItemEvent) { ItemEvent itemEvent = (ItemEvent)notification; EmailMessage message = EmailMessage.Bind(args.Subscription.Service, itemEvent.ItemId.UniqueId).Result; StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender; if (_parameters.GeracaoArquivoEmail.EnviadoPor != null) { if (message.Sender.Address.Contains(_parameters.GeracaoArquivoEmail.EnviadoPor)) { receivedEmail = true; connection.Close(); resetEvent.Set(); } return; } receivedEmail = true; connection.Close(); resetEvent.Set(); } else { FolderEvent folderEvent = (FolderEvent)notification; } } }
public void Disconnect() { if (subconn != null) { try { if (subconn.IsOpen) { subconn.Close(); } subconn.Dispose(); } catch { } finally { subconn = null; } } if (exitToken != null) { try { exitToken.Cancel(false); } catch { } } if (mainThread != null && !mainThread.Join(3000)) { try { Debugger.Break(); mainThread.Abort(); } catch { } } mainThread = null; try { exitToken.Dispose(); } catch { } finally { exitToken = new CancellationTokenSource(); } }
private void Connection_OnSubscriptionError(object sender, SubscriptionErrorEventArgs args) { Debugger.Break(); StreamingSubscriptionConnection connection = sender as StreamingSubscriptionConnection; if (!connection.IsOpen) { connection.Close(); } connection.Dispose(); Status = EProviderStatus.Error; Connect(); }
private void exchange_OnDisconnect(object sender, SubscriptionErrorEventArgs args) { // 1 分ごとに継続 (Unsbscribe のときも呼ばれるので、その際は Close になる) StreamingSubscriptionConnection subcon = (StreamingSubscriptionConnection)sender; if (exchangeClients.ContainsKey(Context.ConnectionId)) { subcon.Open(); } else { try { subcon.Close(); } catch { }; } }
/// <summary> /// Adds the user to subscriptions and starts listening with defined parameters. /// </summary> /// <param name="userMailAddress">The desired user's mail address.</param> /// <param name="folderIds">The Exchange folders under observation</param> /// <param name="eventTypes">Notifications will be received for these eventTypes</param> public void Add(string userMailAddress, IEnumerable <FolderId> folderIds, IEnumerable <EventType> eventTypes) { lock (_conLock) { this.isClosingControlled = true; if (_connection.IsOpen) { _connection.Close(); } this._exchangeService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, userMailAddress); if (!this._exchangeService.HttpHeaders.ContainsKey("X-AnchorMailbox")) { this._exchangeService.HttpHeaders.Add("X-AnchorMailbox", userMailAddress); } if (!this._exchangeService.HttpHeaders.ContainsKey("X-PreferServerAffinity")) { this._exchangeService.HttpHeaders.Add("X-PreferServerAffinity", bool.TrueString); } var item = this._exchangeService.SubscribeToStreamingNotifications(folderIds, eventTypes.ToArray()); _connection.AddSubscription(item); this._subscriptions.Add(new MailAddress(userMailAddress), item); _connection.Open(); Debug.WriteLine(string.Format("Subscription added to EWS connection {0}. Started listening.", this.TargetEwsUrl.ToString())); this.isClosingControlled = false; } }
private void UpdateConnection() { try { lock (_connectionLock) { if (null != _connection) { if (_connection.IsOpen) { _connection.Close(); } } _connection = StartNewConnection(); } } catch (Exception ex) { log.WarnFormat("Error setting up connection: {0}", ex); _startConnectionTimer.Start(); // retry } }
static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args) { // Cast the sender as a StreamingSubscriptionConnection object. StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender; // Ask the user if they want to reconnect or close the subscription. 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) { // Close the connection connection.Close(); } else { break; } } } } }
// When the subscription connection expires, determine whether the subscription should be kept open. static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args) { // Cast the sender as a StreamingSubscriptionConnection object. StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender; // Ask the user if they want to reconnect or close the subscription. ConsoleKeyInfo cki; Console.WriteLine("The StreamingSubscriptionConnection has expired."); Console.WriteLine("\r\n"); Console.WriteLine("Do you want to reconnect to the subscription? Enter Y or N"); Console.WriteLine("\r\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(); // Unsubscribe from the notification subscription. StreamingSubscription.Unsubscribe(); // Close the connection. connection.Close(); break; } } } }
////DJB //private void GetGroupingInfo(ExchangeService oExchangeService, string DiscoverMailbox) //{ // //oExchangeService.get // string UseVersion = oExchangeService.RequestedServerVersion.ToString(); // string UseUrl = oExchangeService.Url.ToString(); // djb - need to fix it to the autodiscover url. // string EwsRequest = EwsRequests.GroupingInformationTemplateRequest; // EwsRequest = EwsRequest.Replace("XXXExchangeVersionXXX", UseVersion); // EwsRequest = EwsRequest.Replace("XXXAutoDiscoverServiceServerXXX", UseUrl); // EwsRequest = EwsRequest.Replace("XXXMailboxSmtpXXX", DiscoverMailbox); // // DO raw post // // string sResponse // // if (DoRawPost(UseUrl, oExchangeService.ServerCredentials, EwsRequest, ref sResponse)); // // { // // Extract GroupingInformation and external url from sResponse); // // } // // else // // { // // return error; // // } //} private void StreamingSubscribeWork() { // djb // get a list of maiboxes, thier external ews urls and grouping info // list of items = GetGroupingInfo(ExchangeService oExchangeService, string DiscoverMailbox); // Sort list of items by url + GroupingInformaiton // try { lock (WorkThreads) { WorkThreads.Add(Thread.CurrentThread); SetControlText(ThreadCount, WorkThreads.Count.ToString()); } if (chkSerialize.Checked) { mutConnection.WaitOne(); } string TID = Thread.CurrentThread.ManagedThreadId.ToString("[0]"); ListViewItem item = new ListViewItem(); item.Tag = "[local]ThreadStart"; item.Text = "[local]ThreadStart"; item.SubItems.Add(TID); item.SubItems.Add(DateTime.Now.ToString()); AddToDisplay(lstEvents, item); // Note that EWS Managed API objects should not beshared accross threads - So, each thread should have its own service object. //EWSEditor.Common.EwsEditorServiceInstanceSettings.EwsEditorAppSettings oSettings = new EWSEditor.Common.EwsEditorServiceInstanceSettings.EwsEditorAppSettings(); EWSEditor.Common.EwsEditorAppSettings oCurrentAppSettings = null; ExchangeService ThreadLocalService = EwsProxyFactory.CreateExchangeService( ); // Todo: Flush out oCurrentAppSettings CurrentAppSettings = oCurrentAppSettings; List <StreamingSubscription> ThreadLocalSubscriptions = new List <StreamingSubscription>(); // Create the subscriptions based on the form settings for (int i = 0; i < numSubs.Value; i++) { try { StreamingSubscription CurrentSubscription = null; if (chkAllFoldes.Checked == false) { CurrentSubscription = ThreadLocalService.SubscribeToStreamingNotifications( new FolderId[] { this.CurrentFolderId }, EventTypes.ToArray()); //System.Diagnostics.Debug.WriteLine("-"); //System.Diagnostics.Debug.WriteLine("Subscribe - ID: " + CurrentSubscription.Id + " Watermark: " + CurrentSubscription.Watermark); //System.Diagnostics.Debug.WriteLine("-"); } else { CurrentSubscription = ThreadLocalService.SubscribeToStreamingNotificationsOnAllFolders( EventTypes.ToArray()); //System.Diagnostics.Debug.WriteLine("-"); //System.Diagnostics.Debug.WriteLine("Subscribe - ID: " + CurrentSubscription.Id + " Watermark: " + CurrentSubscription.Watermark); //System.Diagnostics.Debug.WriteLine("-"); } ThreadLocalSubscriptions.Add(CurrentSubscription); lock (ActiveSubscriptions) { ActiveSubscriptions.Add(CurrentSubscription); SetControlText(SubscriptionCount, ActiveSubscriptions.Count.ToString()); } } catch (Exception ex) { DebugLog.WriteException("Error Subscribe or Add [TID:" + TID + "]", ex); item = new ListViewItem(); item.Tag = "[local]SubscribeError"; item.Text = "[local]SubscribeError"; item.ToolTipText = ex.ToString(); item.SubItems.Add(TID); item.SubItems.Add(DateTime.Now.ToString()); AddToDisplay(lstEvents, item); } } // Create a new StreamingSubscriptionConnection StreamingSubscriptionConnection CurrentConnection = new StreamingSubscriptionConnection(ThreadLocalService, (int)SubscriptionLifetime.Value); lock (ActiveConnections) { ActiveConnections.Add(CurrentConnection); SetControlText(ConnectionCount, ActiveConnections.Count.ToString()); } // Add Handlers CurrentConnection.OnDisconnect += OnDisconnect; CurrentConnection.OnSubscriptionError += OnSubscriptionError; CurrentConnection.OnNotificationEvent += OnStreamingEvent; // Add the Subscriptions to the Connection foreach (StreamingSubscription CurrentSubscription in ThreadLocalSubscriptions) { CurrentConnection.AddSubscription(CurrentSubscription); } if (chkSerialize.Checked) { mutConnection.ReleaseMutex(); } // Open the Connection try { if (ThreadLocalService.CookieContainer.Count > 0) { System.Net.CookieCollection MyCookies = ThreadLocalService.CookieContainer.GetCookies(ThreadLocalService.Url); } CurrentConnection.Open(); ShutdownThreads.WaitOne(); } catch (Exception ex) { DebugLog.WriteException("Error Opening StreamingSubscriptionConnection [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex); item = new ListViewItem(); item.Tag = "[local]OpenError"; item.Text = "[local]OpenError"; item.ToolTipText = ex.ToString(); item.SubItems.Add(TID); item.SubItems.Add(DateTime.Now.ToString()); AddToDisplay(lstEvents, item); //System.Diagnostics.Debug.WriteLine("-"); //System.Diagnostics.Debug.WriteLine("Error Opening StreamingSubscriptionConnection [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex); //System.Diagnostics.Debug.WriteLine("-"); } try { // Close Connection if (CurrentConnection.IsOpen) { CurrentConnection.Close(); // Thread.Sleep(500); } } catch (Exception ex) { DebugLog.WriteException("Error Closing Streaming Connection [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex); item = new ListViewItem(); item.Tag = "[local]CloseError"; item.Text = "[local]CloseError"; item.ToolTipText = ex.ToString(); item.SubItems.Add(TID); item.SubItems.Add(DateTime.Now.ToString()); AddToDisplay(lstEvents, item); //System.Diagnostics.Debug.WriteLine("-"); //System.Diagnostics.Debug.WriteLine("Error Closing Streaming Connection [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex); //System.Diagnostics.Debug.WriteLine("-"); } finally { lock (ActiveConnections) { ActiveConnections.Remove(CurrentConnection); SetControlText(ConnectionCount, ActiveConnections.Count.ToString()); } } // Remove Handlers CurrentConnection.OnDisconnect -= OnDisconnect; CurrentConnection.OnSubscriptionError -= OnSubscriptionError; CurrentConnection.OnNotificationEvent -= OnStreamingEvent; foreach (StreamingSubscription CurrentSubscription in ThreadLocalSubscriptions) { try { CurrentConnection.RemoveSubscription(CurrentSubscription); CurrentSubscription.Unsubscribe(); //System.Diagnostics.Debug.WriteLine("-"); //System.Diagnostics.Debug.WriteLine("Unsubscribed - ID: " + CurrentSubscription.Id + " Watermark: " + CurrentSubscription.Watermark); //System.Diagnostics.Debug.WriteLine("-"); } catch (Exception ex) { DebugLog.WriteException("Error Removing/Unsubscribing StreamingSubscription Elements [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex); item = new ListViewItem(); item.Tag = "[local]UnsubscribeError"; item.Text = "[local]UnsubscribeError"; item.ToolTipText = ex.ToString(); item.SubItems.Add(TID); item.SubItems.Add(DateTime.Now.ToString()); AddToDisplay(lstEvents, item); //System.Diagnostics.Debug.WriteLine("-"); //System.Diagnostics.Debug.WriteLine("Error Removing/Unsubscribing StreamingSubscription Elements [TID:" + Thread.CurrentThread.ManagedThreadId.ToString() + "]", ex); //System.Diagnostics.Debug.WriteLine(" ID: " + CurrentSubscription.Id + " Watermark: " + CurrentSubscription.Watermark); //System.Diagnostics.Debug.WriteLine("-"); } finally { lock (ActiveSubscriptions) { //System.Diagnostics.Debug.WriteLine("-"); //System.Diagnostics.Debug.WriteLine("Removing subscription - ID: " + CurrentSubscription.Id + " Watermark: " + CurrentSubscription.Watermark); //System.Diagnostics.Debug.WriteLine("-"); ActiveSubscriptions.Remove(CurrentSubscription); SetControlText(SubscriptionCount, ActiveSubscriptions.Count.ToString()); } } } lock (WorkThreads) { WorkThreads.Remove(Thread.CurrentThread); } SetControlText(ThreadCount, WorkThreads.Count.ToString()); } catch (Exception ex) { DebugLog.WriteException("Unexpected Exception in WorkerThread", ex); } finally { } }