Example #1
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"));
        }
Example #2
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"));
        }
Example #3
0
        //thread to get all emails
        public static void _getMails(object param)
        {
            helpers.addLog("_getMails() started...");
            ews _ews = (ews)param;  //need an instance
            _ews.OnStateChanged(new StatusEventArgs(StatusType.busy, "_getMails() started..."));
            const int chunkSize = 50;
            try
            {
                PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body
                //blocking call
                ItemView view = new ItemView(chunkSize);
                view.PropertySet = itempropertyset;

                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
                /*
                private static void GetAttachments(ExchangeService service)
                {
                    // Return a single item.
                    ItemView view = new ItemView(1);

                    string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";

                    // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
                    FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);

                    if (results.TotalCount > 0)
                    {
                        EmailMessage email = results.Items[0] as EmailMessage;
                */
                FindItemsResults<Item> findResults;

                do
                {
                    //findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                    SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
                    filterCollection.Add(new SearchFilter.Not(new SearchFilter.ContainsSubstring(ItemSchema.Subject, sMailHasAlreadyProcessed)));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, helpers.filterSubject));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Attachments, helpers.filterAttachement));
                    findResults = _ews._service.FindItems(WellKnownFolderName.Inbox, filterCollection, view);

                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: found "+ findResults.Items.Count + " items in inbox"));
                    foreach (Item item in findResults.Items)
                    {
                        helpers.addLog("found item...");
                        if (item is EmailMessage)
                        {
                            EmailMessage mailmessage = item as EmailMessage;
                            mailmessage.Load(itempropertyset); //load data from server

                            helpers.addLog("\t is email ...");

                            // If the item is an e-mail message, write the sender's name.
                            helpers.addLog(mailmessage.Sender.Name + ": " + mailmessage.Subject);
                            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: processing eMail " + mailmessage.Subject));

                            MailMsg myMailMsg = new MailMsg(mailmessage, _ews._userData.sUser);

                            // Bind to an existing message using its unique identifier.
                            //EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId));
                            int iRet = _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, item.Id as 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, "processed "+iRet.ToString()));
                        }
                    }
                    view.Offset += chunkSize;
                } while (findResults.MoreAvailable && _ews._bRunThread);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.idle, "readmail done"));
            }
            catch (ThreadAbortException ex)
            {
                helpers.addLog("ThreadAbortException: " + ex.Message);
            }
            catch (Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "readmail exception: " + ex.Message));
            }
            helpers.addLog("_getMails() ended");
            _ews.startPull();
        }
Example #4
0
        //thread to get all emails
        public static void _getMails(object param)
        {
            helpers.addLog("_getMails() started...");
            ews _ews = (ews)param;  //need an instance

            _ews.OnStateChanged(new StatusEventArgs(StatusType.busy, "_getMails() started..."));
            const int chunkSize = 50;

            try
            {
                PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body
                //blocking call
                ItemView view = new ItemView(chunkSize);
                view.PropertySet = itempropertyset;

                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);

                /*
                 * private static void GetAttachments(ExchangeService service)
                 * {
                 *  // Return a single item.
                 *  ItemView view = new ItemView(1);
                 *
                 *  string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";
                 *
                 *  // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
                 *  FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);
                 *
                 *  if (results.TotalCount > 0)
                 *  {
                 *      EmailMessage email = results.Items[0] as EmailMessage;
                 */
                FindItemsResults <Item> findResults;

                do
                {
                    //findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                    SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
                    filterCollection.Add(new SearchFilter.Not(new SearchFilter.ContainsSubstring(ItemSchema.Subject, sMailHasAlreadyProcessed)));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, helpers.filterSubject));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Attachments, helpers.filterAttachement));
                    findResults = _ews._service.FindItems(WellKnownFolderName.Inbox, filterCollection, view);

                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: found " + findResults.Items.Count + " items in inbox"));
                    foreach (Item item in findResults.Items)
                    {
                        helpers.addLog("found item...");
                        if (item is EmailMessage)
                        {
                            EmailMessage mailmessage = item as EmailMessage;
                            mailmessage.Load(itempropertyset); //load data from server

                            helpers.addLog("\t is email ...");

                            // If the item is an e-mail message, write the sender's name.
                            helpers.addLog(mailmessage.Sender.Name + ": " + mailmessage.Subject);
                            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: processing eMail " + mailmessage.Subject));

                            MailMsg myMailMsg = new MailMsg(mailmessage, _ews._userData.sUser);

                            // Bind to an existing message using its unique identifier.
                            //EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId));
                            int iRet = _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, item.Id as 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, "processed " + iRet.ToString()));
                        }
                    }
                    view.Offset += chunkSize;
                } while (findResults.MoreAvailable && _ews._bRunThread);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.idle, "readmail done"));
            }
            catch (ThreadAbortException ex)
            {
                helpers.addLog("ThreadAbortException: " + ex.Message);
            }
            catch (Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "readmail exception: " + ex.Message));
            }
            helpers.addLog("_getMails() ended");
            _ews.startPull();
        }