Example #1
0
        public async Task <bool> ConnectExchange(string authToken)
        {
            bool success = true;

            try
            {
                ThisExchangeService = new ExchangeService
                {
                    Url         = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"),
                    Credentials = new OAuthCredentials(authToken)
                };

                Folder          Inbox         = Folder.Bind(ThisExchangeService, WellKnownFolderName.Inbox);
                AlternateId     aiAlternateid = new AlternateId(IdFormat.EwsId, Inbox.Id.UniqueId, "*****@*****.**");
                AlternateIdBase aiResponse    = ThisExchangeService.ConvertId(aiAlternateid, IdFormat.EwsId);
                ThisMailbox = ((AlternateId)aiResponse).Mailbox;
            }
            catch (Exception ex)
            {
                success = false;
                Logger.FireWindowsLog(WinLogger.ApplicationEventType.Error, "Exchange Operation Failed - " + ex);
            }

            //success = await EnumerateFoldersAsync();
            return(success);
        }
Example #2
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);
        }
        /// <summary>
        /// Authenticates using the credentials provided to the credential manager. It also
        /// populates the ExchangeService object used by the application.
        /// </summary>
        /// <param name="userprincipalname">The user's name for accessing Exchange</param>
        /// <param name="password">The user's password.</param>
        /// <param name="service">The ExchangeService object for this application.</param>
        /// <returns>A value of true indicates that the client successfully authenticated with EWS.</returns>
        private static bool Authenticate(string userprincipalname, SecureString password, ref ExchangeService service)
        {
            bool authenticated = false;

            try
            {
                service.Credentials = new NetworkCredential(userprincipalname, password);

                // Check if we have the service URL.
                if (service.Url == null)
                {
                    Console.WriteLine("Using Autodiscover to find EWS URL for {0}. Please wait... ", userprincipalname);
                    service.AutodiscoverUrl(userprincipalname, Service.RedirectionUrlValidationCallback);
                    Console.WriteLine("Autodiscover complete.");
                }

                // Once we have the URL, try a ConvertId operation to check if we can access the service. We expect that
                // the user will be authenticated and that we will get an error code due to the invalid format. Expect a
                // ServiceResponseException.
                Console.WriteLine("Attempting to connect to EWS...");
                AlternateIdBase response = service.ConvertId(new AlternateId(IdFormat.EwsId, "Placeholder", userprincipalname), IdFormat.EwsId);
            }

            // The user principal name is in a bad format.
            catch (FormatException fe)
            {
                Console.WriteLine("Error: {0} Please enter your credentials in UPN format.", fe.Message);
                //service = null;
            }

            catch (AutodiscoverLocalException ale)
            {
                Console.WriteLine("Error: {0}", ale.Message);
                //service = null;
            }

            // The credentials were authenticated. We expect this exception since we are providing intentional bad data for ConvertId
            catch (ServiceResponseException)
            {
                Console.WriteLine("Successfully connected to EWS.");
                authenticated = true;
            }

            // The credentials were not authenticated.
            catch (ServiceRequestException)
            {
                throw new ApplicationException("The credentials were not authenticated.");
                //service = null;
            }

            return(authenticated);
        }
Example #4
0
        /// <summary>
        /// Authenticates using the credentials provided to the credential manager. It also
        /// populates the ExchangeService object used by the application.
        /// </summary>
        /// <param name="userprincipalname">The user's name for accessing Exchange</param>
        /// <param name="password">The user's password.</param>
        /// <param name="service">The ExchangeService object for this application.</param>
        /// <returns>A value of true indicates that the client successfully authenticated with EWS.</returns>
        private static bool Authenticate(string userprincipalname, SecureString password, ref ExchangeService service)
        {
            bool authenticated = false;

            try
            {
                service.Credentials = new NetworkCredential(userprincipalname, password);

                // Check if we have the service URL.
                if (service.Url == null)
                {
                    Console.WriteLine("Wyszukiwanie EWS URL dla konta {0}. Czekaj... ", userprincipalname);
                    service.AutodiscoverUrl(userprincipalname, Service.RedirectionUrlValidationCallback);
                    Console.WriteLine("Wyszukiwanie zakończone.");
                }

                // Once we have the URL, try a ConvertId operation to check if we can access the service. We expect that
                // the user will be authenticated and that we will get an error code due to the invalid format. Expect a
                // ServiceResponseException.
                Console.WriteLine("Łączenie z EWS...");
                AlternateIdBase response = service.ConvertId(new AlternateId(IdFormat.EwsId, "Placeholder", userprincipalname), IdFormat.EwsId);
            }

            // The user principal name is in a bad format.
            catch (FormatException fe)
            {
                Console.WriteLine("Błąd: {0} Wprowadź dane dostępowe w formacie UPN.", fe.Message);
                //service = null;
            }

            catch (AutodiscoverLocalException ale)
            {
                Console.WriteLine("Błąd: {0}", ale.Message);
                //service = null;
            }

            // The credentials were authenticated. We expect this exception since we are providing intentional bad data for ConvertId
            catch (ServiceResponseException)
            {
                Console.WriteLine("Połączono z EWS.");
                authenticated = true;
            }

            // The credentials were not authenticated.
            catch (ServiceRequestException)
            {
                throw new ApplicationException("Dane dostępowe są nieważne.");
                //service = null;
            }

            return(authenticated);
        }
Example #5
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var service = new ExchangeService();

            if (this.DefaultCredentials.IsChecked == true)
            {
                service.UseDefaultCredentials = true;
            }
            else
            {
                service.Credentials = new WebCredentials(this.Email.Text, this.Password.Password);
            }
            service.AutodiscoverUrl(this.Email.Text);



            int counter = 0;

            using (SDK.Database database = new SDK.Database())
            {
                database.Connect();
                foreach (var checkinStyle in CheckinStyles)
                {
                    if (checkinStyle.Link)
                    {
                        Folder folder = new Folder(service);
                        folder.DisplayName = checkinStyle.Name;
                        folder.Save(WellKnownFolderName.Inbox);

                        SDK.CheckinStyle sourceStyle = new SDK.CheckinStyle(database, checkinStyle.GetUri());

                        AlternateId alternateId = new AlternateId();
                        alternateId.Format   = IdFormat.EwsId;
                        alternateId.Mailbox  = this.Email.Text;
                        alternateId.UniqueId = folder.Id.UniqueId;

                        string id = ((AlternateId)service.ConvertId(alternateId, IdFormat.HexEntryId)).UniqueId; // convert the folder ID we get from EWS to the Id Outlook expects

                        var place = sourceStyle.FindOrCreatePlace(SDK.CheckinPlaceTypes.MailForClientProcessing, id);

                        // the Checkin Place name must include the name of the Outlook profile to cater for environments that use multiple Outlook Profiles
                        place.Name = $"{place.Name}:{this.ProfileName.Text}";
                        place.Save();

                        counter++;
                    }
                }
            }

            MessageBox.Show($"Created {counter} folders.");
        }
Example #6
0
        /// <summary>
        /// Authenticates using the credentials provided to the credential manager. It also
        /// populates the ExchangeService object used by the application.
        /// </summary>
        /// <param name="data">users data : name, password, email, domain</param>
        /// <param name="service">The ExchangeService object for this application.</param>
        /// <returns>A value of true indicates that the client successfully authenticated with EWS.</returns>
        private static bool Authenticate(IUserData data, ref ExchangeService service)
        {
            bool authenticated = false;

            try
            {
                service.Credentials = new WebCredentials(data.UserName, data.Password, data.Domain);

                // Check if we have the service URL.
                if (service.Url == null ||
                    string.IsNullOrWhiteSpace(service.Url.OriginalString))
                {
                    Logger.Message(
                        LocalizibleStrings.StartAutodiscover, data.EmailAddress);
                    service.AutodiscoverUrl(
                        data.EmailAddress, Service.RedirectionUrlValidationCallback);
                    Logger.Message(LocalizibleStrings.AutodiscoverComplete);
                }

                // Once we have the URL, try a ConvertId operation to check if we can access the service. We expect that
                // the user will be authenticated and that we will get an error code due to the invalid format. Expect a
                // ServiceResponseException.
                Logger.Message(LocalizibleStrings.AttemptingConnectEws);
                service.ConvertId(new AlternateId(IdFormat.EwsId, @"Placeholder", data.UserName), IdFormat.EwsId);
            }
            // The user principal name is in a bad format.
            catch (FormatException fe)
            {
                Logger.Error(LocalizibleStrings.AuthInvalidUpn, fe);
            }
            catch (AutodiscoverLocalException ale)
            {
                Logger.Error(LocalizibleStrings.Auth, ale);
            }
            // The credentials were authenticated. We expect this exception since we are providing intentional bad data for ConvertId
            catch (ServiceResponseException)
            {
                Logger.Message(LocalizibleStrings.SuccConnection);
                authenticated = true;
            }
            // The credentials were not authenticated.
            catch (ServiceRequestException exc)
            {
                Logger.Error(LocalizibleStrings.CredNotAuth, exc);
            }
            return(authenticated);
        }
        public String Get_EwsIdFromEntryID(ExchangeService oExchangeService, String sSmtp, String sEntryID)
        {
            // https://blogs.msdn.microsoft.com/brijs/2010/09/09/how-to-convert-exchange-items-entryid-to-ews-unique-itemid-via-ews-managed-api-convertid-call/

            // Create a request to convert identifiers.
            AlternateId objAltID = new AlternateId();

            objAltID.Format   = IdFormat.EntryId;
            objAltID.Mailbox  = sSmtp;
            objAltID.UniqueId = sEntryID;

            //Convert  PR_ENTRYID identifier format to an EWS identifier.
            AlternateIdBase objAltIDBase = oExchangeService.ConvertId(objAltID, IdFormat.EwsId);
            AlternateId     objAltIDResp = (AlternateId)objAltIDBase;

            return(objAltIDResp.UniqueId);
        }
Example #8
0
        public static DialogResult ShowDialog(out ItemId itemId, ExchangeService _CurrentService)
        {
            itemId = null;

            ItemIdDialog diag = new ItemIdDialog();

            diag.Text = "Enter a Item's Id...";



            DialogResult res = diag.ShowDialog();

            if (res == DialogResult.OK)
            {
                if (diag.cmboIdType.Text == "UniqueId")
                {
                    itemId = new ItemId(diag.txtUniqueId.Text);
                }

                if (diag.cmboIdType.Text == "StoreId")
                {
                    string sUniqueId = string.Empty;

                    AlternateId FromId = new AlternateId(
                        IdFormat.StoreId,
                        diag.txtUniqueId.Text.Trim(),
                        diag.txtSmtpAddress.Text.Trim()
                        );
                    //FromId.Format = IdFormat.StoreId;
                    //FromId.Mailbox = diag.txtSmtpAddress.Text.Trim();
                    //FromId.UniqueId = diag.txtUniqueId.Text.Trim();

                    AlternateId ToId =
                        (AlternateId)_CurrentService.ConvertId(FromId, IdFormat.EwsId);

                    sUniqueId = ToId.UniqueId;

                    itemId = new ItemId(diag.txtUniqueId.Text);
                }
            }

            return(res);
        }
Example #9
0
        /// <summary>
        /// Authenticates using the credentials provided to the credential manager. It also 
        /// populates the ExchangeService object used by the application.
        /// </summary>
        /// <param name="userprincipalname">The user's name for accessing Exchange</param>
        /// <param name="password">The user's password.</param>
        /// <param name="service">The ExchangeService object for this application.</param>
        /// <returns>A value of true indicates that the client successfully authenticated with EWS.</returns>
        private static bool Authenticate(string userprincipalname, SecureString password, ref ExchangeService service)
        {
            bool authenticated = false;
            try
            {
                service.Credentials = new NetworkCredential(userprincipalname, password);

                // Check if we have the service URL.
                if (service.Url == null)
                {
                    Console.WriteLine("Wyszukiwanie EWS URL dla konta {0}. Czekaj... ", userprincipalname);
                    service.AutodiscoverUrl(userprincipalname, Service.RedirectionUrlValidationCallback);
                    Console.WriteLine("Wyszukiwanie zakończone.");
                }

                // Once we have the URL, try a ConvertId operation to check if we can access the service. We expect that
                // the user will be authenticated and that we will get an error code due to the invalid format. Expect a
                // ServiceResponseException.
                Console.WriteLine("Łączenie z EWS...");
                AlternateIdBase response = service.ConvertId(new AlternateId(IdFormat.EwsId, "Placeholder", userprincipalname), IdFormat.EwsId);
            }

            // The user principal name is in a bad format.
            catch (FormatException fe)
            {
                Console.WriteLine("Błąd: {0} Wprowadź dane dostępowe w formacie UPN.", fe.Message);
                //service = null;
            }

            catch (AutodiscoverLocalException ale)
            {
                Console.WriteLine("Błąd: {0}", ale.Message);
                //service = null;
            }

            // The credentials were authenticated. We expect this exception since we are providing intentional bad data for ConvertId
            catch (ServiceResponseException)
            {
                Console.WriteLine("Połączono z EWS.");
                authenticated = true;
            }

            // The credentials were not authenticated.
            catch (ServiceRequestException)
            {
                throw new ApplicationException("Dane dostępowe są nieważne.");
                //service = null;
            }

               return authenticated;
        }
Example #10
0
        /// <summary>
        /// Authenticates using the credentials provided to the credential manager. It also 
        /// populates the ExchangeService object used by the application.
        /// </summary>
        /// <param name="data">users data : name, password, email, domain</param>
        /// <param name="service">The ExchangeService object for this application.</param>
        /// <returns>A value of true indicates that the client successfully authenticated with EWS.</returns>
        private static bool Authenticate(IUserData data, ref ExchangeService service)
        {
            bool authenticated = false;
            try
            {
                service.Credentials = new WebCredentials(data.UserName, data.Password, data.Domain);

                // Check if we have the service URL.
                if (service.Url == null
                    || string.IsNullOrWhiteSpace(service.Url.OriginalString))
                {
                    Logger.Message(
                        LocalizibleStrings.StartAutodiscover, data.EmailAddress);
                    service.AutodiscoverUrl(
                        data.EmailAddress, Service.RedirectionUrlValidationCallback);
                    Logger.Message(LocalizibleStrings.AutodiscoverComplete);
                }

                // Once we have the URL, try a ConvertId operation to check if we can access the service. We expect that
                // the user will be authenticated and that we will get an error code due to the invalid format. Expect a
                // ServiceResponseException.
                Logger.Message(LocalizibleStrings.AttemptingConnectEws);
                service.ConvertId(new AlternateId(IdFormat.EwsId, @"Placeholder", data.UserName), IdFormat.EwsId);
            }
            // The user principal name is in a bad format.
            catch (FormatException fe)
            {
                Logger.Error(LocalizibleStrings.AuthInvalidUpn, fe);
            }
            catch (AutodiscoverLocalException ale)
            {
                Logger.Error(LocalizibleStrings.Auth, ale);
            }
            // The credentials were authenticated. We expect this exception since we are providing intentional bad data for ConvertId
            catch (ServiceResponseException)
            {
                Logger.Message(LocalizibleStrings.SuccConnection);
                authenticated = true;
            }
            // The credentials were not authenticated.
            catch (ServiceRequestException exc)
            {
                Logger.Error(LocalizibleStrings.CredNotAuth, exc);
            }
            return authenticated;
        }