Esempio n. 1
0
        private void MainThread()
        {
            ExchangeTraceListener trace = new ExchangeTraceListener();

            exService = new ExchangeService();
            exService.TraceListener = trace;
            exService.TraceFlags    = TraceFlags.AutodiscoverConfiguration;
            exService.TraceEnabled  = true;
            exService.Url           = new Uri(ApplicationSettings.General.Outlook365ewsEndpoint);

            // trick for display the Oauth login form after application startup
            Thread.Sleep(ApplicationSettings.General.WaitForApplicationStartup);

            string token = string.Empty;

            do
            {
                try
                {
                    if (IsServiceAvailable())
                    {
                        token = GetAuthenticationToken();
                    }
                }
                catch (Exception ex)
                {
                    Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                }
            } while (string.IsNullOrEmpty(token) && !exitToken.IsCancellationRequested);

            exService.Credentials = new OAuthCredentials(token);

            if (exitToken.IsCancellationRequested)
            {
                return;
            }

            Status = EProviderStatus.Connecting;

            // Cache user display name
            if (string.IsNullOrEmpty(UserSettings.Email.CachedDisplayName))
            {
                string name = GetUserDisplayName(UserSettings.Email.EmailAddress);

                if (name != null && name != string.Empty)
                {
                    UserSettings.Email.CachedDisplayName = name;
                }
            }

            SubscribeNotifications(exService, trace);

            ExchangeSync(exService, trace);

            while (!exitToken.IsCancellationRequested)
            {
                EmailSender(exService, trace);
                Wait(ApplicationSettings.General.WaitForNextEmailCheck);
            }
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        private void EmailSender(ExchangeService service, ExchangeTraceListener trace)
        {
            lock (service)
            {
                while (!emailQueue.IsEmpty)
                {
                    EmailMessageDTO message;
                    bool            IsSent = false;

                    if (!emailQueue.TryDequeue(out message))
                    {
                        continue;
                    }

                    do
                    {
                        try
                        {
                            EmailMessage msg = new EmailMessage(service);

                            msg.Subject    = message.Subject;
                            msg.Body       = message.Body;
                            msg.Importance = message.Importance;

                            msg.ToRecipients.AddRange(message.ToRecipients);
                            msg.CcRecipients.AddRange(message.CcRecipients);

                            foreach (string file in message.Attachments)
                            {
                                msg.Attachments.AddFileAttachment(file);
                            }

                            msg.SendAndSaveCopy();
                            IsSent = true;

                            NotifyMessageSent(message);
                        }
                        catch
                        {
                            if (trace.Result == ETraceResult.LoginError)
                            {
                                Status = EProviderStatus.LoginError;
                                return;
                            }
                            else
                            {
                                Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                            }
                        }
                    }while (!IsSent);
                }
            }
        }
Esempio n. 4
0
        private void OnExchangeStatusChange(StatusChangeMessage <EProviderStatus> x)
        {
            Application.Current.Dispatcher?.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            {
                ExchangeStatus = x.Content;

                if (ExchangeStatus == EProviderStatus.LoginError)
                {
                    ExchangeLoginView loginView = new ExchangeLoginView();
                    loginView.ShowDialog();
                }
            }));
        }
Esempio n. 5
0
        private void Connection_OnSubscriptionError(object sender, SubscriptionErrorEventArgs args)
        {
            Debugger.Break();

            StreamingSubscriptionConnection connection = sender as StreamingSubscriptionConnection;

            if (!connection.IsOpen)
            {
                connection.Close();
            }

            connection.Dispose();
            Status = EProviderStatus.Error;
            Connect();
        }
Esempio n. 6
0
        private void SubscribeNotificationsThread()
        {
            ExchangeTraceListener trace   = new ExchangeTraceListener();
            ExchangeService       service = new ExchangeService
            {
                TraceListener = trace,
                TraceFlags    = TraceFlags.AutodiscoverConfiguration,
                TraceEnabled  = true,
                Url           = exServiceUri
            };

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

            subconn = new StreamingSubscriptionConnection(service, 30);

            do
            {
                try
                {
                    StreamingSubscription streamingSubscription = service.SubscribeToStreamingNotificationsOnAllFolders(EventType.NewMail);

                    subconn.AddSubscription(streamingSubscription);
                    subconn.OnNotificationEvent += Connection_OnNotificationEvent;
                    subconn.OnSubscriptionError += Connection_OnSubscriptionError;
                    subconn.OnDisconnect        += Connection_OnDisconnect;
                    subconn.Open();
                }
                catch
                {
                    if (trace.Result == ETraceResult.LoginError)
                    {
                        Status = EProviderStatus.LoginError;
                        return;
                    }
                    else
                    {
                        Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                    }
                }
            } while ((subconn == null || !subconn.IsOpen) && !exitToken.IsCancellationRequested);
        }
Esempio n. 7
0
        private void Connection_OnDisconnect(object sender, SubscriptionErrorEventArgs args)
        {
            StreamingSubscriptionConnection connection = sender as StreamingSubscriptionConnection;

            try
            {
                connection.Open();
            }
            catch (Exception ex)
            {
                if (Status != EProviderStatus.Error)
                {
                    Status = EProviderStatus.Offline;
                }

                connection.Dispose();
                Connect();
            }
        }
Esempio n. 8
0
        private void MainThread()
        {
            ExchangeTraceListener trace = new ExchangeTraceListener();

            exService = new ExchangeService();
            exService.TraceListener = trace;
            exService.TraceFlags    = TraceFlags.AutodiscoverConfiguration;
            exService.TraceEnabled  = true;

            do
            {
                try
                {
                    exService.Credentials = new WebCredentials(UserSettings.Email.EmailAddress, UserSettings.Email.EmailPassword);
                    //exService.UseDefaultCredentials = true;
                    exService.AutodiscoverUrl(UserSettings.Email.EmailAddress, (string redirectionUrl) =>
                    {
                        // The default for the validation callback is to reject the URL.
                        bool result        = false;
                        Uri redirectionUri = new Uri(redirectionUrl);

                        // Validate the contents of the redirection URL. In this simple validation
                        // callback, the redirection URL is considered valid if it is using HTTPS
                        // to encrypt the authentication credentials.
                        if (redirectionUri.Scheme == "https")
                        {
                            result = true;
                        }

                        return(result);
                    });
                }
                catch
                {
                    if (trace.Result == ETraceResult.LoginError)
                    {
                        Status = EProviderStatus.LoginError;
                        return;
                    }
                    else
                    {
                        Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                    }
                }
            } while (exService.Url == null && !exitToken.IsCancellationRequested);

            if (exitToken.IsCancellationRequested)
            {
                return;
            }

            Status = EProviderStatus.Connecting;

            exServiceUri = exService.Url;

            if ((emailSenderThread == null || !emailSenderThread.IsAlive) && !exitToken.IsCancellationRequested)
            {
                emailSenderThread              = new Thread(EmailSenderThread);
                emailSenderThread.Name         = "Email Sender";
                emailSenderThread.IsBackground = true;
                emailSenderThread.Start();
            }

            if ((subscribeThread == null || !subscribeThread.IsAlive) && !exitToken.IsCancellationRequested)
            {
                subscribeThread              = new Thread(SubscribeNotificationsThread);
                subscribeThread.Name         = "Exchange Subscription Thread";
                subscribeThread.IsBackground = true;
                subscribeThread.Start();
            }

            if ((syncThread == null || !syncThread.IsAlive) && !exitToken.IsCancellationRequested)
            {
                syncThread              = new Thread(ExchangeSync);
                syncThread.Name         = "Exchange Sync";
                syncThread.IsBackground = true;
                syncThread.Start();
            }
        }
Esempio n. 9
0
        private void ExchangeSync()
        {
            ExchangeTraceListener trace   = new ExchangeTraceListener();
            ExchangeService       service = new ExchangeService
            {
                TraceListener = trace,
                TraceFlags    = TraceFlags.AutodiscoverConfiguration,
                TraceEnabled  = true,
                Credentials   = new WebCredentials(UserSettings.Email.EmailAddress, UserSettings.Email.EmailPassword),
                Url           = exServiceUri
            };

            bool IsSynced = false;

            Status = EProviderStatus.Syncronizing;

            do
            {
                try
                {
                    ItemView itemView = new ItemView(int.MaxValue)
                    {
                        PropertySet = new PropertySet(BasePropertySet.IdOnly)
                    };
                    FolderView folderView = new FolderView(int.MaxValue)
                    {
                        PropertySet = new PropertySet(BasePropertySet.IdOnly), Traversal = FolderTraversal.Deep
                    };
                    folderView.PropertySet.Add(FolderSchema.WellKnownFolderName);

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

                    // try to get last week messages (high priority)
                    foreach (Item item in FindItemsInSubfolders(service, new FolderId(WellKnownFolderName.MsgFolderRoot), "from:fdl received:>=lastweek", folderView, itemView))
                    {
                        if (exitToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (!(item is EmailMessage))
                        {
                            continue;
                        }

                        EmailMessage message = EmailMessage.Bind(service, item.Id);
                        NotifyNewMessage(message);
                    }

                    // then all the other messages
                    foreach (Item item in FindItemsInSubfolders(service, new FolderId(WellKnownFolderName.MsgFolderRoot), "from:fdl", folderView, itemView))
                    {
                        if (exitToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (!(item is EmailMessage))
                        {
                            continue;
                        }

                        EmailMessage message = EmailMessage.Bind(service, item.Id);
                        NotifyNewMessage(message);
                    }

                    IsSynced = true;
                    Status   = EProviderStatus.Syncronized;
                }
                catch
                {
                    if (trace.Result == ETraceResult.LoginError)
                    {
                        Status = EProviderStatus.LoginError;
                        return;
                    }
                    else
                    {
                        Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                    }
                }
            } while (!IsSynced && !exitToken.IsCancellationRequested);
        }
Esempio n. 10
0
        private void EmailSenderThread()
        {
            ExchangeTraceListener trace   = new ExchangeTraceListener();
            ExchangeService       service = new ExchangeService
            {
                TraceListener = trace,
                TraceFlags    = TraceFlags.AutodiscoverConfiguration,
                TraceEnabled  = true,
                Credentials   = new WebCredentials(UserSettings.Email.EmailAddress, UserSettings.Email.EmailPassword),
                Url           = exServiceUri
            };

            while (!exitToken.IsCancellationRequested)
            {
                while (!emailQueue.IsEmpty)
                {
                    EmailMessageDTO message;
                    bool            IsSent = false;

                    if (!emailQueue.TryDequeue(out message))
                    {
                        continue;
                    }

                    do
                    {
                        try
                        {
                            EmailMessage msg = new EmailMessage(service);

                            msg.Subject    = message.Subject;
                            msg.Body       = message.Body;
                            msg.Importance = message.Importance;

                            msg.ToRecipients.AddRange(message.ToRecipients);
                            msg.CcRecipients.AddRange(message.CcRecipients);

                            foreach (string file in message.Attachments)
                            {
                                msg.Attachments.AddFileAttachment(file);
                            }

                            msg.SendAndSaveCopy();
                            IsSent = true;

                            NotifyMessageSent(message);
                        }
                        catch
                        {
                            if (trace.Result == ETraceResult.LoginError)
                            {
                                Status = EProviderStatus.LoginError;
                                return;
                            }
                            else
                            {
                                Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                            }
                        }
                    }while (!IsSent);
                }

                Wait(ApplicationSettings.General.WaitForNextEmailCheck);
            }
        }
Esempio n. 11
0
        private void ExchangeSync(ExchangeService service, ExchangeTraceListener trace)
        {
            bool IsSynced = false;

            Status = EProviderStatus.Syncronizing;

            do
            {
                try
                {
                    ItemView itemView = new ItemView(int.MaxValue)
                    {
                        PropertySet = new PropertySet(BasePropertySet.IdOnly)
                    };
                    itemView.PropertySet.Add(ItemSchema.DateTimeReceived);
                    itemView.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

                    FolderView folderView = new FolderView(int.MaxValue)
                    {
                        PropertySet = new PropertySet(BasePropertySet.IdOnly), Traversal = FolderTraversal.Deep
                    };
                    folderView.PropertySet.Add(FolderSchema.WellKnownFolderName);

                    SearchFilter.IsEqualTo f1 = new SearchFilter.IsEqualTo(EmailMessageSchema.From, new EmailAddress(ApplicationSettings.EmailRecipients.FDLSystem));
                    // In order to import FDL and EA files, the only way is to work around the "from" address check.
                    // To do this we check if in the recipient fdl_chk is present and, at a later time, we will check if the sender is the FDL System
                    SearchFilter.ContainsSubstring      f2             = new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, ApplicationSettings.EmailRecipients.FDL_CHK_Display, ContainmentMode.Substring, ComparisonMode.IgnoreCase);
                    SearchFilter.SearchFilterCollection compoundFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, f1, f2);

                    lock (service)
                    {
                        foreach (Item item in FindItemsInSubfolders(service, new FolderId(WellKnownFolderName.MsgFolderRoot), compoundFilter, folderView, itemView))
                        {
                            if (exitToken.IsCancellationRequested)
                            {
                                break;
                            }

                            if (!(item is EmailMessage))
                            {
                                continue;
                            }

                            EmailMessage message = EmailMessage.Bind(service, item.Id);

                            // Double check in order to avoiding wrong fdl import (bugfix check the commment above)
                            if (message.From.Address.ToLower() == ApplicationSettings.EmailRecipients.FDLSystem.ToLower())
                            {
                                NotifyNewMessage(message);
                            }
                        }
                    }

                    IsSynced = true;
                    Status   = EProviderStatus.Syncronized;
                }
                catch (Exception ex)
                {
                    if (trace.Result == ETraceResult.LoginError)
                    {
                        Status = EProviderStatus.LoginError;
                        return;
                    }
                    else
                    {
                        Wait(ApplicationSettings.General.WaitForNextConnectionRetry);
                    }
                }
            } while (!IsSynced && !exitToken.IsCancellationRequested);
        }