private StreamingSubscriptionConnection StartNewConnection() { return(_exchangeServiceManager.ExecutePrivate(_room.RoomAddress, svc => { log.DebugFormat("Opening subscription to {0}", _room.RoomAddress); var calId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(_room.RoomAddress)); var sub = svc.SubscribeToStreamingNotifications( new[] { calId }, EventType.Created, EventType.Deleted, EventType.Modified, EventType.Moved, EventType.Copied, EventType.FreeBusyChanged); // Create a streaming connection to the service object, over which events are returned to the client. // Keep the streaming connection open for 30 minutes. var connection = new StreamingSubscriptionConnection(svc, 30); connection.AddSubscription(sub); connection.OnNotificationEvent += OnNotificationEvent; connection.OnDisconnect += OnDisconnect; connection.Open(); _meetingCacheService.ClearUpcomingAppointmentsForRoom(_room.RoomAddress); log.DebugFormat("Opened subscription to {0} via {1} with {2}", _room.RoomAddress, svc.GetHashCode(), svc.CookieContainer.GetCookieHeader(svc.Url)); IsActive = true; return connection; })); }
public void SetStreamingNotifications() { StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(exchangeService, 1); SubscribeNotification(exchangeService, connection); connection.Open(); }
/// <summary> /// Use this to get notified of events, this uses StreamingNotifications /// </summary> /// <param name="wellKnownFolderName">WellKnownFolderName to look to, Inbox if none is specified</param> /// <param name="eventTypes">params EventType, if nothing specified than EventType.NewMail is taken</param> /// <returns>IObservable which publishes NotificationEvent</returns> public IObservable <NotificationEvent> Observe(WellKnownFolderName wellKnownFolderName = WellKnownFolderName.Inbox, params EventType[] eventTypes) { if (eventTypes == null || eventTypes.Length == 0) { eventTypes = new[] { EventType.NewMail }; } return(Observable.Create <NotificationEvent>( observer => { try { var streamingSubscription = Service.SubscribeToStreamingNotifications(new FolderId[] { wellKnownFolderName }, eventTypes); var connection = new StreamingSubscriptionConnection(Service, 1); connection.AddSubscription(streamingSubscription); connection.OnNotificationEvent += (sender, notificationEventArgs) => { foreach (var notificationEvent in notificationEventArgs.Events) { observer.OnNext(notificationEvent); } }; // Handle errors connection.OnSubscriptionError += (sender, subscriptionErrorEventArgs) => observer.OnError(subscriptionErrorEventArgs.Exception); // Use this to bool disposedConnection = false; // As the time to live is maximum 30 minutes, the connection is closed by the server connection.OnDisconnect += (sender, subscriptionErrorEventArgs) => { if (subscriptionErrorEventArgs.Exception != null || disposedConnection) { return; } // Connection closed by server, just reconnect // See: https://msdn.microsoft.com/en-us/library/office/hh312849.aspx // "This behavior is expected and is not an error condition" connection.Open(); }; // Start the connection connection.Open(); // Return a disposable which disposed the connection and unsubscribes the subscription return Disposable.Create(() => { disposedConnection = true; connection.Dispose(); streamingSubscription.Unsubscribe(); }); } catch (Win32Exception e) { observer.OnError(e); return Disposable.Empty; } })); }
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(); }
static void SetStreamingNotifications(ExchangeService service, IUserData ud) { // Subscribe to streaming notifications on the Inbox folder, and listen // for "NewMail", "Created", and "Deleted" events. try { StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications( new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail, EventType.Created, EventType.Deleted); StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 1); connection.AddSubscription(streamingsubscription); // Delegate event handlers. connection.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent); connection.OnSubscriptionError += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError); connection.OnDisconnect += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect); connection.Open(); Log(string.Format("Zasubskrybowano konto: {0}", ud.EmailAddress)); } catch (Exception e) { Log("Błąd w trakcie próby podłączenia subskrypcji." + e.InnerException.ToString()); } }
public override void Initialize(Robot robot) { base.Initialize(robot); config = new AdapterConfig(robot); if (string.IsNullOrEmpty(config.Email) || string.IsNullOrEmpty(config.Password)) { Logger.Warn("Exchange Adapter requires MMBOT_EXCHANGE_EMAIL and MMBOT_EXCHANGE_PASSWORD"); return; } Service = new ExchangeService { Credentials = new WebCredentials(config.Email, config.Password) }; InitializeExchangeUrl(); var newMailSubscription = Service.SubscribeToStreamingNotifications( new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail); ExchangeConnection = new StreamingSubscriptionConnection(Service, config.SubscriptionLifetime); ExchangeConnection.AddSubscription(newMailSubscription); ExchangeConnection.OnNotificationEvent += OnExchangeNotification; ExchangeConnection.OnDisconnect += OnExchangeDisconnect; }
/// <summary> /// Manages the connection for multiple <see cref="StreamingSubscription"/> items. Attention: Use only for subscriptions on the same CAS. /// </summary> /// <param name="exchangeService">The ExchangeService instance this collection uses to connect to the server.</param> public StreamingSubscriptionCollection(ExchangeService exchangeService, Action <SubscriptionNotificationEventCollection> EventProcessor, GroupIdentifier groupIdentifier) { this._exchangeService = exchangeService; this._EventProcessor = EventProcessor; this._groupIdentifier = groupIdentifier; _connection = CreateConnection(); }
private void SubscribeNotifications(ExchangeService service, ExchangeTraceListener trace) { subconn = new StreamingSubscriptionConnection(service, 30); do { try { StreamingSubscription streamingSubscription = service.SubscribeToStreamingNotificationsOnAllFolders(EventType.NewMail); subconn.AddSubscription(streamingSubscription); subconn.OnNotificationEvent += Connection_OnNotificationEvent; subconn.OnSubscriptionError += Connection_OnSubscriptionError; subconn.OnDisconnect += Connection_OnDisconnect; subconn.Open(); } catch (Exception ex) { if (trace.Result == ETraceResult.LoginError) { Status = EProviderStatus.LoginError; return; } else { Wait(ApplicationSettings.General.WaitForNextConnectionRetry); } } } while ((subconn == null || !subconn.IsOpen) && !exitToken.IsCancellationRequested); }
// Subscribe to streaming notifications for all folder and item events in the root folder. static StreamingSubscription SetStreamingNotifications(ExchangeService service, string cSyncState, FolderId rootSyncFolder) { // Subscribe to streaming notifications on the rootSyncFolder and listen // for events. StreamingSubscription = service.SubscribeToStreamingNotifications( new FolderId[] { rootSyncFolder }, EventType.NewMail, EventType.Created, EventType.Deleted, EventType.Modified, EventType.Moved, EventType.Copied ); StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, WaitTime); connection.AddSubscription(StreamingSubscription); connection.OnNotificationEvent += OnNotificationEvent; connection.OnDisconnect += OnDisconnect; connection.Open(); Console.WriteLine("Now waiting for notifications on the following folder"); Console.WriteLine("FolderId: {0}", rootSyncFolder); Console.WriteLine("--------"); return(StreamingSubscription); }
private StreamingSubscriptionConnection StartNewConnection() { var svc = _exchangeServiceBuilder(); var useImpersonation = bool.Parse(ConfigurationManager.AppSettings["useImpersonation"] ?? "false"); if (useImpersonation) { svc.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, _roomAddress); } log.DebugFormat("Opening subscription to {0}, impersonation: {1}", _roomAddress, useImpersonation); var calId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(_roomAddress)); var sub = svc.SubscribeToStreamingNotifications( new[] { calId }, EventType.Created, EventType.Deleted, EventType.Modified, EventType.Moved, EventType.Copied, EventType.FreeBusyChanged); // Create a streaming connection to the service object, over which events are returned to the client. // Keep the streaming connection open for 30 minutes. var connection = new StreamingSubscriptionConnection(svc, 30); connection.AddSubscription(sub); connection.OnNotificationEvent += OnNotificationEvent; connection.OnDisconnect += OnDisconnect; connection.Open(); _meetingCacheService.ClearUpcomingAppointmentsForRoom(_roomAddress); log.DebugFormat("Opened subscription to {0} via {1} with {2}", _roomAddress, svc.GetHashCode(), svc.CookieContainer.GetCookieHeader(svc.Url)); IsActive = true; return(connection); }
private void SubscribeConnectionEvents(StreamingSubscriptionConnection connection) { // Subscribe to events for this connection connection.OnNotificationEvent += connection_OnNotificationEvent; connection.OnDisconnect += connection_OnDisconnect; connection.OnSubscriptionError += connection_OnSubscriptionError; }
/// <summary> /// Register notification for all folders /// </summary> /// <param name="folders">The folder list</param> /// <param name="eventTypes">The notification event type</param> /// <param name="handler">Callback funtion when notification push from server</param> public void RegisterNotification(FolderId[] folders, EventType[] eventTypes, INotificationHandler handler) { StreamingSubscriptionConnection connection = CreateNotificationConnection(folders, eventTypes); connection.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(handler.OnNotificationEvent); connection.OnSubscriptionError += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(handler.OnNotificationError); connection.OnDisconnect += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(handler.OnNotificationDisconnect); connection.Open(); }
/// <summary> /// create notification connection for subcribing new email from server /// </summary> /// <param name="folders">folders</param> /// <param name="eventTypes">eventTypes</param> /// <returns>StreamingSubscriptionConnection</returns> public StreamingSubscriptionConnection CreateNotificationConnection(FolderId[] folders, params EventType[] eventTypes) { StreamingSubscription streamingsubscription = _exchangeService.SubscribeToStreamingNotifications(folders, eventTypes); StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(_exchangeService, lifeTime); connection.AddSubscription(streamingsubscription); connections.Add(connection); return(connection); }
private bool SubscribeForNotifications() { try { AlternateId outlookFolderId = new AlternateId(IdFormat.HexEntryId, _folder.EntryID, _primarySmtpAddress, false); AlternateId ewsFolderId = _exchangeService.ConvertId(outlookFolderId, IdFormat.EwsId) as AlternateId; _folderId = new FolderId(ewsFolderId.UniqueId); } catch (Exception ex) { AddLog(String.Format("Failed to obtain EWS Folder Id: {0}", ex.Message)); if (ex.Message.Contains("Unauthorized") || ex.Message.Contains("401")) { AddLog("Currently only Windows auth will work (on-prem only)"); } return(false); } try { _streamingSubscription = _exchangeService.SubscribeToStreamingNotifications(new FolderId[] { _folderId }, EventType.Created, EventType.Moved, EventType.Copied, EventType.Modified, EventType.NewMail, EventType.Deleted); // If we have a watermark, we set this so that we don't miss any events } catch (Exception ex) { AddLog(String.Format("Error creating subscription: {0}", ex.Message)); return(false); } try { _streamingSubscriptionConnection = new StreamingSubscriptionConnection(_exchangeService, 30); _streamingSubscriptionConnection.AddSubscription(_streamingSubscription); } catch (Exception ex) { AddLog(String.Format("Error creating subscription connection: {0}", ex.Message)); return(false); } _streamingSubscriptionConnection.OnNotificationEvent += _streamingSubscriptionConnection_OnNotificationEvent; _streamingSubscriptionConnection.OnDisconnect += _streamingSubscriptionConnection_OnDisconnect; _streamingSubscriptionConnection.OnSubscriptionError += _streamingSubscriptionConnection_OnSubscriptionError; try { _streamingSubscriptionConnection.Open(); } catch (Exception ex) { AddLog(String.Format("Error opening subscription connection: {0}", ex.Message)); return(false); } AddLog("Successfully subscribed for notifications"); return(true); }
public void SetStreamingNotifications() { StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(exchangeService, 1); SubscribeNotification(exchangeService, connection); connection.Open(); LoggerHelper.Logger.Info("StreamSubscription event: \r\n1: Notification Event\r\n2: Notification Error\r\n3: Disconnection"); }
/// <summary> /// Initializes a new instance of the <see cref="ExchangeServiceSubscription" /> class. /// </summary> /// <param name="service">The <see cref="ExchangeService" />.</param> /// <param name="folder">The folder to monitor.</param> internal ExchangeServiceSubscription(ExchangeService service, WellKnownFolderName folder) { _service = service; _subscriptionConnection = new StreamingSubscriptionConnection(_service, 30); // 30 minutes is the max StreamingSubscription subscription = _service.SubscribeToStreamingNotifications(new FolderId[] { folder }, EventType.NewMail); _subscriptionConnection.AddSubscription(subscription); _subscriptionConnection.OnNotificationEvent += (s, e) => SubscriptionNotification?.Invoke(this, EventArgs.Empty); }
private StreamingSubscriptionConnection CreateConnection() { var con = new StreamingSubscriptionConnection(this._exchangeService, 30); con.OnSubscriptionError += OnSubscriptionError; con.OnDisconnect += OnDisconnect; con.OnNotificationEvent += OnNotificationEvent; return(con); }
static void Main(string[] args) { var userData = new UserData(); userData.AutodiscoverUrl = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"); var service = Service.ConnectToService(userData); var streamingSubscription = service.SubscribeToStreamingNotifications( new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail, EventType.Created, EventType.Deleted, EventType.Modified, EventType.Moved, EventType.Copied, EventType.FreeBusyChanged); var connection = new StreamingSubscriptionConnection(service, 30); connection.AddSubscription(streamingSubscription); connection.OnNotificationEvent += (s, e) => Console.WriteLine("Mail Received!"); connection.OnDisconnect += (s, e) => { }; connection.Open(); var pushSubscription = service.SubscribeToPushNotificationsOnAllFolders( new Uri(@" https://blockchainui.azurewebsites.net/api/certificate/pushnotification/"), 5, null, EventType.NewMail); // var view = new ItemView(100); // // var findItem = new PropertySet(BasePropertySet.IdOnly); //// view.PropertySet = findItem; // var GetItemsPropertySet = new PropertySet(BasePropertySet.FirstClassProperties); // GetItemsPropertySet.RequestedBodyType = BodyType.Text; //var results = service.FindItems(WellKnownFolderName.Inbox, view) ; // service.LoadPropertiesForItems(results.Items, GetItemsPropertySet); // foreach (var res in results) // { // if (res.Body != null) // { // Thread.Sleep(2000); // Console.WriteLine(res.Body.Text); // } // } Console.ReadKey(); }
public static void OnDisconnect(object sender, SubscriptionErrorEventArgs args) { StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender; if (receivedEmail) { return; } connection.Open(); }
public void ConnectExchange(string userId, string password) { try { ExchangeService sv = null; StreamingSubscriptionConnection subcon = null; // Exchange Online に接続 (今回はデモなので、Address は決めうち !) //ExchangeVersion ver = new ExchangeVersion(); //ver = ExchangeVersion.Exchange2010_SP1; //sv = new ExchangeService(ver, TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time")); sv = new ExchangeService(TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time")); //sv.TraceEnabled = true; // デバッグ用 sv.Credentials = new System.Net.NetworkCredential( userId, password); sv.EnableScpLookup = false; sv.AutodiscoverUrl(userId, exchange_AutodiscoverCallback); // Streaming Notification の開始 (Windows Azure の制約から 1 分ごとに貼り直し) StreamingSubscription sub = sv.SubscribeToStreamingNotifications( new FolderId[] { new FolderId(WellKnownFolderName.Calendar) }, EventType.Created, EventType.Modified, EventType.Deleted); subcon = new StreamingSubscriptionConnection(sv, 1); // only 1 minute ! subcon.AddSubscription(sub); subcon.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(exchange_OnNotificationEvent); subcon.OnDisconnect += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(exchange_OnDisconnect); subcon.OnSubscriptionError += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(exchange_OnSubscriptionError); subcon.Open(); // set client data (Sorry, this is not scalable !) CleanUpExchangeClients(); exchangeClients.TryAdd( Context.ConnectionId, new ExchangeData() { StreamingSubscription = sub, LastUpdate = DateTime.Now }); // 準備完了の送信 ! JObject jsonObj = new JObject(); jsonObj["MailAddress"] = new JValue(userId); jsonObj["Password"] = new JValue(password); jsonObj["ServerUrl"] = new JValue(sv.Url.ToString()); //this.SendMessage(jsonObj.ToString()); this.Clients.Caller.notifyEvent("Ready", jsonObj.ToString()); } catch (Exception exp) { JObject jsonObj = new JObject(); jsonObj["Message"] = new JValue(exp.Message); this.Clients.Caller.notifyEvent("Exception", jsonObj.ToString()); } }
public ExchangeClient(string userName, string password, string domain, ExchangeVersion version) { _exchange = new ExchangeService(version); _exchange.Credentials = new WebCredentials(userName, password); _exchange.AutodiscoverUrl(userName + "@" + domain); _connection = new StreamingSubscriptionConnection(_exchange, 30); CreateSubscription(); _connection.OnNotificationEvent += OnNotificationEvent; _connection.OnSubscriptionError += OnSubscriptionError; _connection.OnDisconnect += OnDisconnect; _connection.Open(); }
private static StreamingSubscriptionConnection CreateStreamingSubscription(ExchangeService service, StreamingSubscription subscription) { var connection = new StreamingSubscriptionConnection(service, 30); connection.AddSubscription(subscription); connection.OnNotificationEvent += OnNotificationEvent; connection.OnSubscriptionError += OnSubscriptionError; connection.OnDisconnect += OnDisconnect; connection.Open(); return(connection); }
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(); } }
public void Watch() { service = new ExchangeService(); service.Credentials = new WebCredentials(EmailID, Password, Domain); service.Url = new Uri(ExchangeURL); StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail); connection = new StreamingSubscriptionConnection(service, 5); connection.AddSubscription(streamingsubscription); connection.OnNotificationEvent += OnNotificationEvent; connection.OnSubscriptionError += OnSubscriptionError; connection.OnDisconnect += OnDisconnect; connection.Open(); }
private void ReconnectToSubscriptions() { // Go through our connections and reconnect any that have closed _reconnect = false; List <string> groupsToRecreate = new List <string>(); lock (_reconnectLock) // Prevent this code being run concurrently (i.e. if an event fires in the middle of the processing) { foreach (string sConnectionGroup in _connections.Keys) { StreamingSubscriptionConnection connection = _connections[sConnectionGroup]; if (!connection.IsOpen) { try { if (radioButtonAuthOAuth.Checked) { // If we are using OAuth, we need to ensure that the token is still valid _logger.Log($"Updating OAuth token on all subscriptions in group {sConnectionGroup}"); foreach (StreamingSubscription subscription in connection.CurrentSubscriptions) { CredentialHandler().ApplyCredentialsToExchangeService(subscription.Service); } } connection.Open(); _logger.Log(String.Format("Re-opened connection for group {0}", sConnectionGroup)); } catch (Exception ex) { if (ex.Message.StartsWith("You must add at least one subscription to this connection before it can be opened")) { // Try recreating this group groupsToRecreate.Add(sConnectionGroup); //AddGroupSubscriptions(sConnectionGroup); This won't currently work as it would involve modifying our _connections collection while reading it } else { _logger.Log($"Failed to reopen connection: {ex.Message}"); } } } } foreach (string sConnectionGroup in groupsToRecreate) { _logger.Log($"Rebuilding subscriptions for group: {sConnectionGroup}"); AddGroupSubscriptions(sConnectionGroup); } } }
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 { }; } }
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(); }
protected void SetStreamingNotifications() { // 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); StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(_service, 5); connection.AddSubscription(streamingsubscription); // Delegate event handlers. connection.OnNotificationEvent += OnNewItemEvent; connection.Open(); }
private async void WatchEmail() { _exchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1); // _exchangeService.TraceEnabled = true; _exchangeService.Credentials = new WebCredentials("carpench", "SOMEPASSWORD", "WWTHC"); // _exchangeService.AutodiscoverUrl("*****@*****.**", url => true); _exchangeService.Url = new Uri("https://mobile.wwt.com/ews/exchange.asmx"); var streamingSubscription = _exchangeService.SubscribeToStreamingNotificationsOnAllFolders(EventType.NewMail); _streamingSubscriptionConnection = new StreamingSubscriptionConnection(_exchangeService, 30); _streamingSubscriptionConnection.AddSubscription(await streamingSubscription); _streamingSubscriptionConnection.OnNotificationEvent += EmailRecieved; _streamingSubscriptionConnection.OnDisconnect += (sender, eventArgs) => _streamingSubscriptionConnection.Open(); _streamingSubscriptionConnection.Open(); }
protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { if (_connection != null) { if (_connection.IsOpen) { _connection.Close(); } _connection = null; } _exchange = null; _disposed = true; } }