示例#1
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());
            }
        }
        // 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);
        }
示例#3
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);
        }
示例#4
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);
        }
示例#5
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);
        }
示例#7
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());
            }
        }
示例#8
0
        static void OnEvent(object sender, NotificationEventArgs args)
        {
            StreamingSubscription subscription = args.Subscription;

            // Loop through all item-related events.
            foreach (NotificationEvent notification in args.Events)
            {
                switch (notification.EventType)
                {
                case EventType.NewMail:
                    Console.WriteLine("\n{0}: Mail created:", DateTime.Now.ToString());
                    break;

                case EventType.Created:
                    Console.WriteLine("\n{0} Item or folder created:", DateTime.Now.ToString());
                    break;

                case EventType.Deleted:
                    Console.WriteLine("\n{0} Item or folder deleted:", DateTime.Now.ToString());
                    break;

                case EventType.Moved:
                    Console.WriteLine("\n{0} Item moved:", DateTime.Now.ToString());
                    break;
                }

                // Display the notification identifier.
                if (notification is ItemEvent)
                {
                    // The NotificationEvent for an e-mail message is an ItemEvent.
                    ItemEvent itemEvent = (ItemEvent)notification;
                    //Console.WriteLine("\nItemId: " + itemEvent.ItemId.UniqueId);

                    // Get the details of the item
                    EmailMessage email = EmailMessage.Bind(service, new ItemId(itemEvent.ItemId.UniqueId));
                    Console.WriteLine("Subject: '{0}', Received: {1}, Sender '{2}'", email.Subject, email.DateTimeReceived.ToString(), email.Sender.Address);

                    //old parent folder
                    Folder oldParentFolder = Folder.Bind(service, new FolderId(itemEvent.OldParentFolderId.UniqueId));
                    Console.WriteLine("Source: {0}", oldParentFolder.DisplayName);

                    //new parent folder
                    Folder newParentFolder = Folder.Bind(service, new FolderId(itemEvent.ParentFolderId.UniqueId));
                    Console.WriteLine("Destination: {0}", newParentFolder.DisplayName);
                }
                else
                {
                    // The NotificationEvent for a folder is an FolderEvent.
                    FolderEvent folderEvent = (FolderEvent)notification;
                    Console.WriteLine("\nFolderId: " + folderEvent.FolderId.UniqueId);
                }
            }
        }
        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();
    }
        static void Main(string[] args)
        {
            // Retrieve the initial contents of the rootSyncFolder.
            ContentsSyncState = SyncContents(service, null, RootSyncFolder);

            // Retrieve the initial folder hierarchy, using rootSyncFolder as the root folder.
            FolderSyncState = SyncFolders(service, null, RootSyncFolder);

            // After the initial sync, wait for notifications of new or changed items.
            StreamingSubscription = SetStreamingNotifications(service, ContentsSyncState, RootSyncFolder);

            Signal = new AutoResetEvent(false);

            // Wait for the application to exit.
            Signal.WaitOne();
        }
        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();
        }
        public void OnEvent(object sender, NotificationEventArgs args)
        {
            StreamingSubscription subscription = args.Subscription;

            index++;
            blockCol.Add(index);
            //// Loop through all item-related events.
            foreach (NotificationEvent notification in args.Events)
            {
                switch (notification.EventType)
                {
                case EventType.NewMail:
                    LoggerHelper.Logger.Info("\n-------------Mail created:-------------");
                    break;

                case EventType.Created:
                    LoggerHelper.Logger.Info("\n-------------Item or folder created:-------------");
                    break;

                case EventType.Deleted:
                    LoggerHelper.Logger.Info("\n-------------Item or folder deleted:-------------");
                    break;
                }
                // Display the notification identifier.
                if (notification is ItemEvent)
                {
                    // The NotificationEvent for an email message is an ItemEvent.
                    ItemEvent itemEvent = (ItemEvent)notification;
                    LoggerHelper.Logger.Info("\nItemId: " + itemEvent.ItemId.UniqueId);
                }
                else
                {
                    // The NotificationEvent for a folder is a FolderEvent.
                    FolderEvent folderEvent = (FolderEvent)notification;
                    LoggerHelper.Logger.Info("\nFolderId: " + folderEvent.FolderId.UniqueId);
                }
            }
            //System.Timers.Timer timer = new System.Timers.Timer(5 * 1000 * new Random().Next(1, 10));
            //timer.Elapsed += delegate (object send, System.Timers.ElapsedEventArgs e)
            //{
            //    ReceiveEmailFromServer(exchangeService);
            //};
            //timer.Enabled = true;
            //ReceiveEmailFromServer(exchangeService);
            // AsyncReceiveEmailFromServer();
        }
        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);
        }
示例#15
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);
        }
示例#16
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();
        }
        protected void OnNewItemEvent(object sender, NotificationEventArgs args)
        {
            StreamingSubscription subscription = args.Subscription;

            // Loop through all item-related events.
            foreach (NotificationEvent notification in args.Events)
            {
                object[] emptyArgs = new object[0];

                switch (notification.EventType)
                {
                case EventType.NewMail:
                    _collectCount++;
                    Dispatcher.BeginInvoke(new Action(UpdateCollectCount));
                    ProcessMailItems();
                    break;
                }
            }
        }
        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;
        }
示例#19
0
        /// <summary>
        /// Adds streamingsubscription to the GroupInfo
        /// </summary>
        /// <param name="context">Database context</param>
        /// <param name="Group"></param>
        /// <param name="smtpAddress"></param>
        /// <returns></returns>
        private StreamingSubscription AddSubscription(EWSDbContext context, GroupInfo Group, string smtpAddress)
        {
            StreamingSubscription subscription = null;

            if (_subscriptions.Any(email => email.SmtpAddress.Equals(smtpAddress)))
            {
                var email = _subscriptions.FirstOrDefault(s => s.SmtpAddress.Equals(smtpAddress));
                _subscriptions.Remove(email);
            }

            try
            {
                ExchangeService exchange = Group.ExchangeService;
                exchange.Credentials        = ServiceCredentials;
                exchange.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, smtpAddress);
                subscription = exchange.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Calendar },
                                                                          EventType.Created,
                                                                          EventType.Deleted,
                                                                          EventType.Modified,
                                                                          EventType.Moved,
                                                                          EventType.Copied);


                _traceListener.Trace("SyncProgram", $"CreateStreamingSubscriptionGrouping to room {smtpAddress} with SubscriptionId {subscription.Id}");


                var subscriptions = context.SaveChanges();
                _traceListener.Trace("SyncProgram", $"Streaming subscription persisted {subscriptions} persisted.");

                _subscriptions.Add(new SubscriptionCollection()
                {
                    SmtpAddress = smtpAddress,
                    Streaming   = subscription
                });
            }
            catch (Microsoft.Exchange.WebServices.Data.ServiceRequestException srex)
            {
                _traceListener.Trace("SyncProgram", $"Failed to provision subscription {srex.Message}");
                throw new Exception($"Subscription could not be created for {smtpAddress} with MSG:{srex.Message}");
            }

            return(subscription);
        }
示例#20
0
        private void InitializeComponent()
        {
            this.ServiceName = MyServiceName;

            this.eventLog = new EventLog();

            this.eventLog.Source = this.ServiceName;

            ((System.ComponentModel.ISupportInitialize)(this.eventLog)).BeginInit();

            emailSubscription = EmailHelper.InstanceOf.GetEmailService.SubscribeToStreamingNotifications(
                new FolderId[] {
                EmailHelper.InstanceOf.RfiInboxFolder
            },
                EventType.NewMail);

            //      GroundUpRfiBoxSubscription = EmailHelper.InstanceOf.GetEmailService.SubscribeToStreamingNotifications(
            //        new FolderId[] {
            //          EmailHelper.InstanceOf.NewStoresInboxFolder
            //        },
            //        EventType.NewMail,
            //        EventType.Created,
            //        EventType.Deleted,
            //        EventType.Moved,
            //        EventType.Copied);
//
            //      ExistingRfiBoxSubscription = EmailHelper.InstanceOf.GetEmailService.SubscribeToStreamingNotifications(
            //        new FolderId[] {
            //          EmailHelper.InstanceOf.ExistingStoresInboxFolder
            //        },
            //        EventType.NewMail,
            //        EventType.Created,
            //        EventType.Deleted,
            //        EventType.Moved,
            //        EventType.Copied);

            emailSubscriptionConnection = new StreamingSubscriptionConnection(
                EmailHelper.InstanceOf.GetEmailService,
                30);

            ((System.ComponentModel.ISupportInitialize)(this.eventLog)).EndInit();
        }
示例#21
0
        public static void OnEvent(object sender, NotificationEventArgs args)
        {
            StreamingSubscription subscription = args.Subscription;

            foreach (NotificationEvent notification in args.Events)
            {
                switch (notification.EventType)
                {
                case EventType.NewMail:
                    break;
                }

                if (notification is ItemEvent)
                {
                    ItemEvent    itemEvent = (ItemEvent)notification;
                    EmailMessage message   = EmailMessage.Bind(args.Subscription.Service, itemEvent.ItemId.UniqueId).Result;
                    StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;

                    if (_parameters.GeracaoArquivoEmail.EnviadoPor != null)
                    {
                        if (message.Sender.Address.Contains(_parameters.GeracaoArquivoEmail.EnviadoPor))
                        {
                            receivedEmail = true;
                            connection.Close();
                            resetEvent.Set();
                        }

                        return;
                    }

                    receivedEmail = true;
                    connection.Close();
                    resetEvent.Set();
                }
                else
                {
                    FolderEvent folderEvent = (FolderEvent)notification;
                }
            }
        }
示例#22
0
        static void OnEvent(object sender, NotificationEventArgs args)
        {
            StreamingSubscription subscription = args.Subscription;

            // Loop through all item-related events.
            foreach (NotificationEvent notification in args.Events)
            {
                switch (notification.EventType)
                {
                case EventType.NewMail:
                    Console.WriteLine("\n-------------Mail created:-------------");
                    break;

                case EventType.Created:
                    Console.WriteLine("\n-------------Item or folder created:-------------");
                    break;

                case EventType.Deleted:
                    Console.WriteLine("\n-------------Item or folder deleted:-------------");
                    break;
                }
                // Display the notification identifier.
                if (notification is ItemEvent)
                {
                    // The NotificationEvent for an email message is an ItemEvent.
                    ItemEvent itemEvent = (ItemEvent)notification;
                    Console.WriteLine("\nItemId: " + itemEvent.ItemId.UniqueId);
                }
                else
                {
                    // The NotificationEvent for a folder is a FolderEvent.
                    FolderEvent folderEvent = (FolderEvent)notification;
                    Console.WriteLine("\nFolderId: " + folderEvent.FolderId.UniqueId);
                }
            }
        }
示例#23
0
        private void UnsubscribeAll()
        {
            // Unsubscribe all
            if (_subscriptions == null)
            {
                return;
            }

            for (int i = _subscriptions.Keys.Count - 1; i >= 0; i--)
            {
                string sMailbox = _subscriptions.Keys.ElementAt <string>(i);
                StreamingSubscription subscription = _subscriptions[sMailbox];
                try
                {
                    subscription.Unsubscribe();
                    _logger.Log(String.Format("Unsubscribed from {0}", sMailbox));
                }
                catch (Exception ex)
                {
                    _logger.Log(String.Format("Error when unsubscribing {0}: {1}", sMailbox, ex.Message));
                }
                _subscriptions.Remove(sMailbox);
            }
        }
示例#24
0
        private void AddGroupSubscriptions(string sGroup)
        {
            if (!_groups.ContainsKey(sGroup))
            {
                return;
            }

            if (_connections.ContainsKey(sGroup))
            {
                foreach (StreamingSubscription subscription in _connections[sGroup].CurrentSubscriptions)
                {
                    try
                    {
                        subscription.Unsubscribe();
                    }
                    catch { }
                }
                try
                {
                    _connections[sGroup].Close();
                }
                catch { }
            }

            try
            {
                // Create the connection for this group, and the primary mailbox subscription
                GroupInfo             group        = _groups[sGroup];
                StreamingSubscription subscription = AddSubscription(group.PrimaryMailbox, group);

                if (_connections.ContainsKey(sGroup))
                {
                    _connections[sGroup] = new StreamingSubscriptionConnection(subscription.Service, (int)numericUpDownTimeout.Value);
                }
                else
                {
                    _connections.Add(sGroup, new StreamingSubscriptionConnection(subscription.Service, (int)numericUpDownTimeout.Value));
                }

                SubscribeConnectionEvents(_connections[sGroup]);
                _connections[sGroup].AddSubscription(subscription);
                _logger.Log(String.Format("{0} (primary mailbox) subscription created in group {1}", group.PrimaryMailbox, sGroup));

                // Now add any further subscriptions in this group
                foreach (string sMailbox in group.Mailboxes)
                {
                    if (!sMailbox.Equals(group.PrimaryMailbox))
                    {
                        try
                        {
                            subscription = AddSubscription(sMailbox, group);
                            _connections[sGroup].AddSubscription(subscription);
                            _logger.Log(String.Format("{0} subscription created in group {1}", sMailbox, sGroup));
                        }
                        catch (Exception ex)
                        {
                            _logger.Log(String.Format("ERROR when subscribing {0} in group {1}: {2}", sMailbox, sGroup, ex.Message));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Log(String.Format("ERROR when creating subscription connection group {0}: {1}", sGroup, ex.Message));
            }
        }
示例#25
0
        void ProcessNotification(object e, StreamingSubscription Subscription)
        {
            // We have received a notification

            string sMailbox = Subscription.Service.ImpersonatedUserId.Id;

            if (String.IsNullOrEmpty(sMailbox))
            {
                sMailbox = "Unknown mailbox";
            }
            string sEvent = sMailbox + ": ";

            if (e is ItemEvent)
            {
                if (!checkBoxShowItemEvents.Checked)
                {
                    return;                                  // We're ignoring item events
                }
                sEvent += "Item " + (e as ItemEvent).EventType.ToString() + ": ";
            }
            else if (e is FolderEvent)
            {
                if (!checkBoxShowFolderEvents.Checked)
                {
                    return;                                    // We're ignoring folder events
                }
                sEvent += "Folder " + (e as FolderEvent).EventType.ToString() + ": ";
            }

            try
            {
                if (checkBoxQueryMore.Checked)
                {
                    // We want more information, we'll get this on a new thread
                    NotificationInfo info;
                    info.Mailbox = sMailbox;
                    info.Event   = e;
                    info.Service = Subscription.Service;

                    ThreadPool.QueueUserWorkItem(new WaitCallback(ShowMoreInfo), info);
                }
                else
                {
                    // Just log event and ID
                    if (e is ItemEvent)
                    {
                        sEvent += "ItemId = " + (e as ItemEvent).ItemId.UniqueId;
                    }
                    else if (e is FolderEvent)
                    {
                        sEvent += "FolderId = " + (e as FolderEvent).FolderId.UniqueId;
                    }
                }
            }
            catch { }

            if (checkBoxQueryMore.Checked)
            {
                return;
            }

            ShowEvent(sEvent);
        }
        // Catch and display notification events.
        static void OnNotificationEvent(object sender, NotificationEventArgs args)
        {
            bool callSyncContents = false;
            bool callSyncFolders  = false;

            StreamingSubscription subscription = args.Subscription;

            // Loop through all item-related events.
            foreach (NotificationEvent notification in args.Events)
            {
                switch (notification.EventType)
                {
                case EventType.NewMail:
                    Console.WriteLine("Notification: New mail created");
                    break;

                case EventType.Created:
                    Console.WriteLine("Notification: Item or folder created");
                    break;

                case EventType.Deleted:
                    Console.WriteLine("Notification: Item or folder deleted");
                    break;

                case EventType.Modified:
                    Console.WriteLine("Notification: Item or folder modified");
                    break;

                case EventType.Moved:
                    Console.WriteLine("Notification: Item or folder moved");
                    break;

                case EventType.Copied:
                    Console.WriteLine("Notification: Item or folder copied");
                    break;
                }
                // Display the notification identifier.
                if (notification is ItemEvent)
                {
                    ItemEvent itemEvent = (ItemEvent)notification;
                    Console.WriteLine("Notification ItemId: " + itemEvent.ItemId.UniqueId);
                    Console.WriteLine("--------");
                    callSyncContents = true;
                }
                else
                {
                    FolderEvent folderEvent = (FolderEvent)notification;
                    Console.WriteLine("Notification FolderId: " + folderEvent.FolderId.UniqueId);
                    Console.WriteLine("--------");
                    callSyncFolders = true;
                }
            }

            // Delay calling SyncContents and SyncFolders until all notifications have been processed.
            // This will reduce the number of calls to the Exchange database by batching more changes
            // into a single sync call.
            if (callSyncContents == true)
            {
                ContentsSyncState = SyncContents(service, ContentsSyncState, RootSyncFolder);
            }

            if (callSyncFolders == true)
            {
                FolderSyncState = SyncFolders(service, FolderSyncState, RootSyncFolder);
            }
        }
        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
        /// <summary>
        /// Process the GroupInfo and create subscriptions based on AnchorMailbox
        /// </summary>
        /// <param name="context">Database context for subscription update</param>
        /// <param name="groupName">EWS GroupInfo or Dynamic Groupname if Mailboxes > 200</param>
        /// <returns></returns>
        public bool AddGroupSubscriptions(EWSDbContext context, string groupName)
        {
            if (!_groups.ContainsKey(groupName))
            {
                return(false);
            }

            if (_connections == null)
            {
                _connections = new Dictionary <string, StreamingSubscriptionConnection>();
            }


            if (_connections.ContainsKey(groupName))
            {
                var _connection = _connections[groupName];

                foreach (StreamingSubscription subscription in _connection.CurrentSubscriptions)
                {
                    try
                    {
                        subscription.Unsubscribe();
                    }
                    catch { }
                }
                try
                {
                    _connection.Close();

                    _groups[groupName].IsConnectionOpen = false;
                }
                catch { }
            }

            try
            {
                // Create the connection for this group, and the primary mailbox subscription
                var groupInfo      = _groups[groupName];
                var PrimaryMailbox = groupInfo.PrimaryMailbox;
                // Return the subscription, or create a new one if we don't already have one
                StreamingSubscription mailboxSubscription = AddSubscription(context, groupInfo, PrimaryMailbox);
                if (_connections.ContainsKey(groupName))
                {
                    _connections[groupName] = new StreamingSubscriptionConnection(mailboxSubscription.Service, pollingTimeout);
                }
                else
                {
                    _connections.Add(groupName, new StreamingSubscriptionConnection(mailboxSubscription.Service, pollingTimeout));
                }


                SubscribeConnectionEvents(_connections[groupName]);
                _connections[groupName].AddSubscription(mailboxSubscription);
                _traceListener.Trace("SyncProgram", $"{PrimaryMailbox} (primary mailbox) subscription created in group {groupName}");

                // Now add any further subscriptions in this group
                foreach (string sMailbox in groupInfo.Mailboxes.Where(w => !w.Equals(PrimaryMailbox)))
                {
                    try
                    {
                        var localSubscription = AddSubscription(context, groupInfo, sMailbox);
                        _connections[groupName].AddSubscription(localSubscription);
                        _traceListener.Trace("Add secondary subscription", $"{sMailbox} subscription created in group {groupName}");
                    }
                    catch (Exception ex)
                    {
                        _traceListener.Trace("Exception", $"ERROR when subscribing {sMailbox} in group {groupName}: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                _traceListener.Trace("Exception", $"ERROR when creating subscription connection group {groupName}: {ex.Message}");
            }
            return(true);
        }
示例#29
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 { }
        }