Esempio n. 1
0
 private void emailSubscriptionConnection_OnDisconnect(object sender, SubscriptionErrorEventArgs args)
 {
     if (emailSubscriptionConnection.IsOpen == false)
     {
         emailSubscriptionConnection.Open();
     }
 }
Esempio n. 2
0
        /// <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;
                }
            }));
        }
        public void SetStreamingNotifications()
        {
            StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(exchangeService, 1);

            SubscribeNotification(exchangeService, connection);
            connection.Open();
        }
 /// <summary>
 /// Starts monitoring the Exchange server for changes.
 /// </summary>
 public void Start()
 {
     if (!_subscriptionConnection.IsOpen)
     {
         _subscriptionConnection.Open();
     }
 }
Esempio n. 5
0
        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);
        }
Esempio n. 7
0
        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());
            }
        }
Esempio n. 8
0
        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();
        }
Esempio n. 9
0
            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;
                }));
            }
            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 OnDisconnect(object sender, SubscriptionErrorEventArgs args)
 {
     Console.WriteLine("Disconnected");
     if (!connection.IsOpen)
     {
         connection.Open();
     }
 }
Esempio n. 12
0
 private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
 {
     if (args.Exception == null)
     {
         if (!_disposing && _connection != null)
         {
             _connection.Open();
         }
     }
     else
     {
         if (Disconnected != null)
         {
             Disconnected(this, new DisconnectEventArgs("Exchange exception", args.Exception));
         }
     }
 }
Esempio n. 13
0
        /// <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();
        }
Esempio n. 14
0
        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");
        }
Esempio n. 16
0
        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();
        }
Esempio n. 17
0
        public static void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
        {
            StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;

            if (receivedEmail)
            {
                return;
            }

            connection.Open();
        }
Esempio n. 18
0
 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();
 }
Esempio n. 19
0
        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());
            }
        }
        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);
        }
Esempio n. 21
0
        static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
        {
            // Cast the sender as a StreamingSubscriptionConnection object.
            StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;

            if (autoReconnect)
            {
                connection.Open();
                counter = 0;
                Console.WriteLine("{0}: Connection automatically reconnected after {1} minutes", DateTime.Now.ToString(), intervalMin.ToString());
            }
            else
            {
                // 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();
                            counter = 0;
                            Console.WriteLine("{0}; Connection reconnected.", DateTime.Now.ToString());
                            break;
                        }
                        else if (cki.Key == ConsoleKey.N)
                        {
                            // The ReadKey in the Main() consumes the E.
                            Console.WriteLine("\n\nPress E to exit");
                            break;
                        }
                    }
                }
            }
        }
    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();
    }
Esempio n. 23
0
        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);
                }
            }
        }
Esempio n. 24
0
        /// <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;
            }
        }
Esempio n. 25
0
        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 { };
            }
        }
Esempio n. 26
0
        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();
        }
Esempio n. 27
0
        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();
        }
        static void SetStreamingNotifications(ExchangeService service)
        {
            var streamingSubscription = service.SubscribeToStreamingNotifications(
                new FolderId[] { WellKnownFolderName.Inbox },
                EventType.NewMail);

            var connection = new StreamingSubscriptionConnection(service, 30);

            connection.AddSubscription(streamingSubscription);

            connection.OnNotificationEvent += OnEvent;
            connection.OnSubscriptionError += OnError;
            connection.OnDisconnect        += OnDisconnect;
            connection.Open();

            SynchronizeChanges(service);
        }
Esempio n. 29
0
        private void SubscribeNotificationsThread()
        {
            ExchangeTraceListener trace   = new ExchangeTraceListener();
            ExchangeService       service = new ExchangeService
            {
                TraceListener = trace,
                TraceFlags    = TraceFlags.AutodiscoverConfiguration,
                TraceEnabled  = true,
                Url           = exServiceUri
            };

            if (!UserSettings.Email.UseDefaultCredentials)
            {
                service.Credentials = new WebCredentials(UserSettings.Email.EmailAddress, UserSettings.Email.EmailPassword);
            }

            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
                {
                    if (trace.Result == ETraceResult.LoginError)
                    {
                        Status = EProviderStatus.LoginError;
                        return;
                    }
                    else
                    {
                        Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                    }
                }
            } while ((subconn == null || !subconn.IsOpen) && !exitToken.IsCancellationRequested);
        }
Esempio n. 30
0
        static void SetStreamingNotifications(ExchangeService service)
        {
            // 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, EventType.Moved);

            StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, intervalMin);

            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();
        }