Пример #1
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;
                }));
            }
Пример #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;
                }
            }));
        }
            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);
            }
Пример #4
0
        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;
        }
Пример #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);
        }
Пример #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());
            }
        }
Пример #8
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);
        }
Пример #9
0
        /// <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);
        }
        /// <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);
        }
Пример #11
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();
        }
Пример #12
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);
        }
    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();
    }
Пример #15
0
    private void CreateSubscription()
    {
        var ids = new FolderId[2] {
            new FolderId(WellKnownFolderName.Root), new FolderId(WellKnownFolderName.Inbox)
        };
        var events = new List <EventType>();

        events.Add(EventType.NewMail);
        if (_subscription != null)
        {
            ((StreamingSubscription)_subscription).Unsubscribe();
            _connection.RemoveSubscription((StreamingSubscription)_subscription);
        }
        _subscription = _exchange.SubscribeToStreamingNotifications(ids, events.ToArray());
        _connection.AddSubscription((StreamingSubscription)_subscription);
    }
Пример #16
0
        private void launchSubscriptions()
        {
            emailSubscriptionConnection.AddSubscription(emailSubscription);

            //emailSubscriptionConnection.AddSubscription(GroundUpRfiBoxSubscription);

            //emailSubscriptionConnection.AddSubscription(ExistingRfiBoxSubscription);

            emailSubscriptionConnection.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(emailSubscriptionConnection_OnNotificationEvent);

            emailSubscriptionConnection.OnDisconnect += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(emailSubscriptionConnection_OnDisconnect);

            emailSubscriptionConnection.OnSubscriptionError += new StreamingSubscriptionConnection.SubscriptionErrorDelegate(emailSubscriptionConnection_OnSubscriptionError);

            emailSubscriptionConnection.Open();
        }
Пример #17
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();
        }
Пример #18
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();
        }
        private void SubscribeNotification(ExchangeService exchangeService, StreamingSubscriptionConnection connection)
        {
            StreamingSubscription streamingsubscription = exchangeService.SubscribeToStreamingNotifications(
                new FolderId[] { WellKnownFolderName.Inbox },
                EventType.NewMail,
                EventType.Created,
                EventType.Deleted);

            connection.AddSubscription(streamingsubscription);
            // Delegate event handlers.
            connection.OnNotificationEvent +=
                new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
            connection.OnSubscriptionError +=
                new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError);
            connection.OnDisconnect +=
                new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
        }
        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);
        }
Пример #21
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);
        }
Пример #22
0
        private void btnStreamSubscribe_Click(object sender, RoutedEventArgs e)
        {
            ExchangeService service = _context.GetService();

            _streamSubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail);


            StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 10);

            connection.AddSubscription(_streamSubscription);
            connection.OnNotificationEvent += connection_OnNotificationEvent;

            connection.Open();

            txtSubscriptionActivity.Text += "Stream Subscription Created" + Environment.NewLine;

            btnStreamSubscribe.IsEnabled   = false;
            btnStreamUnsubscribe.IsEnabled = true;
        }
Пример #23
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();
        }
Пример #24
0
        public async static void SetStreamingNotifications(ExchangeService service, ManualResetEvent rEvent, GeracaoArquivo parameters)
        {
            resetEvent  = rEvent;
            _parameters = parameters;

            StreamingSubscription subscription;

            subscription = await service.SubscribeToStreamingNotifications(
                new FolderId[] { WellKnownFolderName.Inbox },
                EventType.NewMail);

            StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, parameters.GeracaoArquivoEmail.TempoStreaming);

            connection.AddSubscription(subscription);
            connection.OnNotificationEvent += OnEvent;
            connection.OnDisconnect        += OnDisconnect;
            connection.Open();

            bool status = connection.IsOpen;
        }
Пример #25
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;
            }
        }
Пример #26
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("Test");
            };
            connection.OnDisconnect += (s, e) => { };
            connection.Open();

            var message = new EmailMessage(service)
            {
                Subject = "Test",
                Body    = "This is your last email"
            };

            message.ToRecipients.Add("*****@*****.**");
            message.Send();


            //  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 StreamingSubscriptionConnection AddGroupSubscriptions(
            ref Dictionary <string, StreamingSubscriptionConnection> Connections,
            ref Dictionary <string, StreamingSubscription> SubscriptionList,
            EventType[] SubscribeEvents,
            FolderId[] SubscribeFolders,
            ClassLogger Logger,
            int TimeOut = 30)
        {
            if (Connections.ContainsKey(_name))
            {
                foreach (StreamingSubscription subscription in Connections[_name].CurrentSubscriptions)
                {
                    try
                    {
                        subscription.Unsubscribe();
                    }
                    catch { }
                }
                try
                {
                    if (Connections[_name].IsOpen)
                    {
                        Connections[_name].Close();
                    }
                }
                catch { }
                Connections.Remove(_name);
            }

            StreamingSubscriptionConnection groupConnection = null;

            try
            {
                // Create the subscription to the primary mailbox, then create the subscription connection
                if (SubscriptionList.ContainsKey(_primaryMailbox))
                {
                    SubscriptionList.Remove(_primaryMailbox);
                }
                StreamingSubscription subscription = AddSubscription(_primaryMailbox, ref SubscriptionList, SubscribeEvents, SubscribeFolders);
                groupConnection = new StreamingSubscriptionConnection(subscription.Service, TimeOut);
                Connections.Add(_name, groupConnection);

                //SubscribeConnectionEvents(groupConnection);
                groupConnection.AddSubscription(subscription);
                Logger.Log($"{_primaryMailbox} (primary mailbox) subscription created in group {_name}");

                // Now add any further subscriptions in this group
                foreach (string sMailbox in _mailboxes)
                {
                    if (!sMailbox.Equals(_primaryMailbox))
                    {
                        try
                        {
                            if (SubscriptionList.ContainsKey(sMailbox))
                            {
                                SubscriptionList.Remove(sMailbox);
                            }
                            subscription = AddSubscription(sMailbox, ref SubscriptionList, SubscribeEvents, SubscribeFolders);
                            groupConnection.AddSubscription(subscription);
                            Logger.Log($"{sMailbox} subscription created in group {_name}");
                        }
                        catch (Exception ex)
                        {
                            Logger.Log(String.Format("ERROR when subscribing {0} in group {1}: {2}", sMailbox, _name, ex.Message));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log($"ERROR when creating subscription connection group {_name}: {ex.Message}");
            }
            return(groupConnection);
        }
Пример #28
0
        ////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 { }
        }
Пример #29
0
        private static void SubscribeToNewMails(ExchangeService service, List <IAcceptEmails> emailHandlers)
        {
            var subscription = service.SubscribeToStreamingNotifications(new[] { new FolderId(WellKnownFolderName.Inbox) },
                                                                         EventType.NewMail);

            var connection = new StreamingSubscriptionConnection(service, 30);

            connection.AddSubscription(subscription);

            connection.OnNotificationEvent += (StreamingSubscriptionConnection.NotificationEventDelegate)((sender, args) =>
            {
                foreach (var e in args.Events)
                {
                    var itemEvent = e as ItemEvent;
                    if (itemEvent != null)
                    {
                        Trace.WriteLine(string.Format("Got {0} event with ItemId {1} ...", itemEvent.EventType, itemEvent.ItemId));
                        var email = EmailMessage.Bind(service, itemEvent.ItemId);
                        Trace.WriteLine(string.Format("... is email with subject {0}", email.Subject));

                        var parsedEmail = new Email(email.Subject,
                                                    email.Body,
                                                    EmailParser.GetSlackFormattedSummary(email.Body),
                                                    email.Id.UniqueId,
                                                    email.DateTimeReceived,
                                                    email.ToRecipients.Select(x => x.Address.ToLowerInvariant()).ToList(),
                                                    IsFirstEmailInConversation(email));

                        foreach (var handler in emailHandlers)
                        {
                            handler.Accept(parsedEmail);
                        }
                    }
                    else
                    {
                        Trace.WriteLine("Unknown EWS event type " + e.GetType().Name);
                    }
                }
            });
            connection.OnDisconnect += (sender, args) =>
            {
                Trace.WriteLine("EWS subscription disconnected: " + args.Exception);
                ((StreamingSubscriptionConnection)sender).Open();
                Trace.WriteLine("EWS subscription reconnected");
            };
            connection.OnSubscriptionError += (sender, args) =>
            {
                Trace.WriteLine("EWS subscription ERROR: " + args.Exception);
                while (true)
                {
                    Trace.WriteLine("Trying to resubscribe ...");
                    try
                    {
                        SubscribeToNewMails(service, emailHandlers);
                        break;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                }
            };
            connection.Open();
        }