Beispiel #1
0
        /// <summary>
        /// Pull notifications specific folders
        /// </summary>
        /// <param name="folderId">The email folder id</param>
        /// <param name="eventTypes">The notification event type</param>
        /// <returns>The Event Result</returns>
        public GetEventsResults PullNotifications(IEnumerable <FolderId> folderId, params EventType[] eventTypes)
        {
            PullSubscription subscription = _exchangeService.SubscribeToPullNotifications(folderId, lifeTime, null, eventTypes);
            GetEventsResults events       = subscription.GetEvents();

            return(events);
        }
Beispiel #2
0
        static void SetPullNotifications(ExchangeService service)
        {
            // Initiate the subscription object, specifying the folder and events.
            PullSubscription subscription = service.SubscribeToPullNotifications(
                new FolderId[] { WellKnownFolderName.Inbox }, 5, null,
                EventType.NewMail, EventType.Created, EventType.Deleted);

            // Initiate the GetEvents method for the new subscription.
            GetEventsResults events = subscription.GetEvents();

            // Handle the results of the GetEvents method.
            foreach (ItemEvent itemEvent in events.ItemEvents)
            {
                switch (itemEvent.EventType)
                {
                case EventType.NewMail:
                    EmailMessage message = EmailMessage.Bind(service, itemEvent.ItemId);
                    break;

                case EventType.Created:
                    Item item = Item.Bind(service, itemEvent.ItemId);
                    break;

                case EventType.Deleted:
                    Console.WriteLine("Item deleted: " + itemEvent.ItemId.UniqueId);
                    break;
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Pull notifications for all folders
        /// </summary>
        /// <param name="eventTypes">The notification event type</param>
        /// <returns>The Event Result</returns>
        public GetEventsResults PullNotifications(params EventType[] eventTypes)
        {
            PullSubscription subscription = _exchangeService.SubscribeToPullNotificationsOnAllFolders(lifeTime, null, eventTypes);
            GetEventsResults events       = subscription.GetEvents();

            return(events);
        }
Beispiel #4
0
        private void Notify(object o)
        {
            User user = (User)o;

            Console.WriteLine("Notify for " + user.Id + "...");
            GetEventsResults results = user.Subscription.GetEvents();

            Console.WriteLine("Current Watermark: " + user.Subscription.Watermark);

            foreach (ItemEvent eventItem in results.ItemEvents)
            {
                string eventType = String.Empty;
                if (eventItem.EventType == EventType.NewMail)
                {
                    eventType = "新規";
                }
                else if (eventItem.EventType == EventType.Deleted)
                {
                    eventType = "削除";
                }
                else if (eventItem.EventType == EventType.Moved)
                {
                    eventType = "移動";
                }
                Console.WriteLine("ItemId: " + eventItem.ItemId);
                try {
                    EmailMessage message = EmailMessage.Bind(user.Service, eventItem.ItemId);
                    Console.WriteLine(eventType + " : " + message.Subject);
                    Console.WriteLine("Saved Watermark: " + user.Subscription.Watermark);
                } catch (Exception exception) {
                    Console.WriteLine(exception.Message);
                } finally {
                }
            }
        }
Beispiel #5
0
    /// <summary>
    /// Ends an asynchronous request to obtain a collection of events that occurred on the subscribed
    /// folders since the point in time defined by the Watermark property. When EndGetEvents succeeds, Watermark is updated.
    /// </summary>
    /// <param name="asyncResult">An IAsyncResult that references the asynchronous request.</param>
    /// <returns>Returns a collection of events that occurred since the last watermark.</returns>
    GetEventsResults EndGetEvents(IAsyncResult asyncResult)
    {
        GetEventsResults results = this.Service.EndGetEvents(asyncResult);

        this.Watermark           = results.NewWatermark;
        this.moreEventsAvailable = results.MoreEventsAvailable;

        return(results);
    }
Beispiel #6
0
    /// <summary>
    /// Obtains a collection of events that occurred on the subscribed folders since the point
    /// in time defined by the Watermark property. When GetEvents succeeds, Watermark is updated.
    /// </summary>
    /// <returns>Returns a collection of events that occurred since the last watermark.</returns>
    GetEventsResults GetEvents()
    {
        GetEventsResults results = this.Service.GetEvents(this.Id, this.Watermark);

        this.Watermark           = results.NewWatermark;
        this.moreEventsAvailable = results.MoreEventsAvailable;

        return(results);
    }
        public IEnumerable <IIncomingEmailMessage> GetMessages()
        {
            Logger.InfoFormat("Getting email messages...");
            var itemCount = _folder.TotalCount;

            if (itemCount <= 0)
            {
                return(new List <IIncomingEmailMessage>());
            }

            List <Item> items = new List <Item>();

            // Gets new email messages that were recieved after the initial startup.
            GetEventsResults eventResults = subscription.GetEvents();

            foreach (ItemEvent itemEvent in eventResults.ItemEvents)
            {
                Item item = Item.Bind(_folder.Service, itemEvent.ItemId);
                items.Add(item);
            }

            // Gets new email messages on the initial startup.
            var         view       = new ItemView(itemCount);
            List <Item> itemsToAdd = _folder.FindItems(view).ToList();

            items.AddRange(itemsToAdd);

            Logger.InfoFormat("Items found: {0}", items.Count());

            var messages  = new List <IIncomingEmailMessage>();
            int junkCount = 0;

            foreach (var item in items)
            {
                if (item is EmailMessage)
                {
                    EWSIncomingMessage message = new EWSIncomingMessage((EmailMessage)item);
                    messages.Add(message);
                }
                else
                {
                    junkCount++;
                    item.Move(WellKnownFolderName.DeletedItems);
                }
            }

            Logger.InfoFormat("Message count: {0}, Junk count: {1}", messages.Count, junkCount);
            Logger.InfoFormat("Completed getting messages.");
            return(messages);
        }
        void timer_Tick(object sender, EventArgs e)
        {
            GetEventsResults results = _pullSubscription.GetEvents();

            txtSubscriptionActivity.Text += "Pull Subscription checked for new items" + Environment.NewLine;

            foreach (ItemEvent itemEvent in results.ItemEvents)
            {
                switch (itemEvent.EventType)
                {
                case EventType.NewMail:
                    txtSubscriptionActivity.Text += "Pull Subscription: New email received" + Environment.NewLine;
                    break;
                }
            }
        }
Beispiel #9
0
 /// <summary>
 /// Listens for new mails in the user inbox folder, if found, notifies the user and update mail list.
 /// </summary>
 /// <param name="service">EWS Service</param>
 public static void GetLatests(ExchangeService service)
 {
     GetEventsResults eventsInbox = subscriptionInbox.GetEvents();
     EmailMessage message;
     // Loop through all item-related events.
     foreach (ItemEvent itemEvent in eventsInbox.ItemEvents)
     {
         switch (itemEvent.EventType)
         {
             case EventType.NewMail:
                 try
                 {
                     Item item = Item.Bind(service, itemEvent.ItemId);
                     if (item.ItemClass.ToLower() == "IPM.Note".ToLower())
                     {
                         message = EmailMessage.Bind(service, itemEvent.ItemId);
                             Form1.GlobalAccess.Invoke(new Action(() =>
                             {
                             if (Form1.GlobalAccess.mailTree.Nodes.Count == 8)
                             {
                                 try
                                 {
                                     Form1.GlobalAccess.mailTree.Nodes.RemoveAt(8);
                                     mailMessages.RemoveAt(8);
                                 }
                                 catch
                                 {
                                 }
                             }
                             Form1.GlobalAccess.mailTree.Nodes.Insert(0, message.Subject);
                             mailMessages.Insert(0, message);
                             }));
                         }               
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show(ex.Message);
                 }
                 break;
         }
     }
 }
Beispiel #10
0
        //pull notifications
        static void startPullNotification(object param)
        {
            ews _ews = (ews)param;  //need an instance

            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pullnotification: started"));
            int iTimeoutMinutes = 5;

            // Subscribe to pull notifications in the Inbox folder, and get notified when
            // a new mail is received, when an item or folder is created, or when an item
            // or folder is deleted.
            PullSubscription subscription = null;

            try
            {
                subscription = _ews._service.SubscribeToPullNotifications(new FolderId[] { WellKnownFolderName.Inbox },
                                                                          iTimeoutMinutes /* timeOut: the subscription will end if the server is not polled within 5 minutes. */,
                                                                          null /* watermark: null to start a new subscription. */,
                                                                          EventType.NewMail);//, EventType.Created, EventType.Deleted);
            }
            catch (Exception ex)
            {
                _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "Pullnotification: PullSubscription FAILED: " + ex.Message));
            }
            if (subscription == null)
            {
                _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "Pullnotification: END with no subscription"));
                return;
            }
            try
            {
                while (_ews._bRunPullThread)
                {
                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pull sleeping " + (iTimeoutMinutes - 1).ToString() + " minutes..."));
                    int iCount = 0;
                    do
                    {
                        _ews.OnStateChanged(new StatusEventArgs(StatusType.ews_pulse, "ews lives"));
                        iCount += 5000;
                        Thread.Sleep(5000);
                        //Thread.Sleep((iTimeoutMinutes - 1) * 60000);
                    } while (iCount < 60000);//do not sleep longer than iTimeout or you loose the subscription

                    // Wait a couple minutes, then poll the server for new events.
                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pull looking for new mails"));
                    GetEventsResults events = subscription.GetEvents();
                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pull processing"));

                    //to get plain text body only
                    PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                    itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body

                    // Loop through all item-related events.
                    foreach (ItemEvent itemEvent in events.ItemEvents)
                    {
                        switch (itemEvent.EventType)
                        {
                        case EventType.NewMail:
                            utils.helpers.addLog("PullNotification: " + "EventType.NewMail");
                            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "check eMail ..."));
                            // A new mail has been received. Bind to it
                            EmailMessage message        = EmailMessage.Bind(_ews._service, itemEvent.ItemId, itempropertyset);
                            bool         bDoProcessMail = false;
                            if (message.Subject.Contains(helpers.filterSubject) && (!message.Subject.Contains("[processed]")))
                            {
                                if (message.HasAttachments)
                                {
                                    //check for endings of attachements
                                    foreach (Attachment att in message.Attachments)
                                    {
                                        if (att.Name.EndsWith(helpers.filterAttachement))
                                        {
                                            bDoProcessMail = true;
                                            continue;
                                        }
                                    }
                                }
                                if (bDoProcessMail)
                                {
                                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: processMail"));
                                    //create a new IMailMessage from the EmailMessage
                                    MailMsg myMailMsg = new MailMsg(message, _ews._userData.sUser);
                                    _ews._licenseMail.processMail(myMailMsg);

                                    //change subject?
                                    // Bind to the existing item, using the ItemId. This method call results in a GetItem call to EWS.
                                    Item myItem = Item.Bind(_ews._service, itemEvent.ItemId);
                                    myItem.Load();
                                    // Update the Subject of the email.
                                    myItem.Subject += "[processed]";
                                    // Save the updated email. This method call results in an UpdateItem call to EWS.
                                    myItem.Update(ConflictResolutionMode.AlwaysOverwrite);

                                    _ews.OnStateChanged(new StatusEventArgs(StatusType.license_mail, "Pullnotification: email marked"));
                                }
                                else
                                {
                                    _ews.OnStateChanged(new StatusEventArgs(StatusType.other_mail, "PullNotification: mail does not match"));
                                }
                            }
                            break;

                        case EventType.Created:
                            // An item was created in the folder. Bind to it.
                            Item item = Item.Bind(_ews._service, itemEvent.ItemId);
                            utils.helpers.addLog("PullNotification: " + "EventType.Created " + item.ToString());
                            break;

                        case EventType.Deleted:
                            // An item has been deleted. Output its ID to the console.
                            utils.helpers.addLog("Item deleted: " + itemEvent.ItemId.UniqueId);
                            break;

                        default:
                            utils.helpers.addLog("PullNotification: " + itemEvent.EventType.ToString());
                            break;
                        }
                    }

                    // Loop through all folder-related events.
                    foreach (FolderEvent folderEvent in events.FolderEvents)
                    {
                        switch (folderEvent.EventType)
                        {
                        case EventType.Created:
                            // An folder was created. Bind to it.
                            Folder folder = Folder.Bind(_ews._service, folderEvent.FolderId);
                            break;

                        case EventType.Deleted:
                            // A folder has been deleted. Output its Id to the console.
                            utils.helpers.addLog("PullNotification: " + folderEvent.FolderId.UniqueId);
                            break;

                        default:
                            utils.helpers.addLog("PullNotification: " + folderEvent.EventType.ToString());
                            break;
                        }
                    }

                    /*
                     * // As an alternative, you can also loop through all the events.
                     * foreach (NotificationEvent notificationEvent in events.AllEvents)
                     * {
                     *  if (notificationEvent is ItemEvent)
                     *  {
                     *      ItemEvent itemEvent = notificationEvent as ItemEvent;
                     *
                     *      switch (itemEvent.EventType)
                     *      {
                     *          ...
                     *      }
                     *  }
                     *  else
                     *  {
                     *      FolderEvent folderEvent = notificationEvent as FolderEvent;
                     *
                     *      switch (folderEvent.EventType)
                     *      {
                     *          ...
                     *      }
                     *  }
                     * }
                     */
                }//end while
            }
            catch (ThreadAbortException)
            {
                _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: ThreadAbortException"));
                _ews._bRunPullThread = false;
            }
            catch (Exception ex)
            {
                _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: Pull Thread Exception:" + ex.Message));
                _ews._bRunPullThread = false;
            }
            try
            {
                subscription.Unsubscribe();
            }
            catch (Exception ex)
            {
                utils.helpers.addExceptionLog("subscriptions unsubscribe exception");
                _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: subscriptions unsubscribe exception " + ex.Message));
            }
            subscription = null;
            _ews.OnStateChanged(new StatusEventArgs(StatusType.ews_stopped, "ews pull ended"));
            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: Pull ended"));
        }
        /// <summary>
        /// Call GetEvents to get the new notification events and display them
        /// in the ListView.
        /// </summary>
        private void btnGetEvents_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                // Guard statement to bail if we haven't subscribed
                if (this.CurrentSubscription == null)
                {
                    return;
                }

                GetEventsResults events = this.CurrentSubscription.GetEvents();

                this.lblEventsHeader.Text = string.Format(System.Globalization.CultureInfo.CurrentCulture,
                                                          "{0} events returned at {1}",
                                                          events.AllEvents.Count,
                                                          DateTime.Now.ToString());

                this.lstEvents.Items.Clear();

                foreach (ItemEvent itemEvent in events.ItemEvents)
                {
                    ListViewItem item = new ListViewItem();
                    item.Tag  = itemEvent;
                    item.Text = itemEvent.GetType().Name;
                    item.SubItems.Add(itemEvent.TimeStamp.ToString());
                    item.SubItems.Add(itemEvent.EventType.ToString());

                    item.SubItems.Add(
                        itemEvent.ItemId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(itemEvent.ItemId));

                    item.SubItems.Add(
                        itemEvent.OldItemId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(itemEvent.OldItemId));

                    item.SubItems.Add(
                        itemEvent.ParentFolderId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(itemEvent.ParentFolderId));

                    item.SubItems.Add(
                        itemEvent.OldParentFolderId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(itemEvent.OldParentFolderId));

                    this.lstEvents.Items.Add(item);
                }

                foreach (FolderEvent folderEvent in events.FolderEvents)
                {
                    ListViewItem item = new ListViewItem();
                    item.Tag  = folderEvent;
                    item.Text = folderEvent.GetType().Name;
                    item.SubItems.Add(folderEvent.TimeStamp.ToString());
                    item.SubItems.Add(folderEvent.EventType.ToString());

                    item.SubItems.Add(
                        folderEvent.FolderId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(folderEvent.FolderId));

                    item.SubItems.Add(
                        folderEvent.OldFolderId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(folderEvent.OldFolderId));

                    item.SubItems.Add(
                        folderEvent.ParentFolderId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(folderEvent.ParentFolderId));

                    item.SubItems.Add(
                        folderEvent.OldParentFolderId == null ? "" :
                        PropertyInformation.PropertyInterpretation.GetPropertyValue(folderEvent.OldParentFolderId));

                    this.lstEvents.Items.Add(item);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }