コード例 #1
0
ファイル: SearchCalendar.cs プロジェクト: kekici/EwsEditor
        private void btnOK_Click(object sender, EventArgs e)
        {
            // If no folder has been identified, warn the user
            if (this._SelectedFolder == null)
            {
                ErrorDialog.ShowWarning("No calendar folder selected.");
                this.DialogResult = DialogResult.None;
                return;
            }


            DateTime start = Convert.ToDateTime(txtStartTime.Text);
            DateTime end   = Convert.ToDateTime(txtEndTime.Text);


            //// TODO: Add more search capablities
            // http://msdn.microsoft.com/en-us/library/dd633700(v=exchg.80).aspx

            SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, start));
            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, end));
            if (this.chkSearchSubject.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, txtSubject.Text));
            }
            if (this.chkSearchToAttendee.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, this.txtToAttendee.Text));
            }
            if (this.chkSearchCCAttendee.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.DisplayCc, this.txtCCAttendee.Text));
            }
            if (this.chkSearchBody.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.Body, this.txtBody.Text));
            }

            ItemView view = new ItemView(20);

            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
            _CurrentService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
            FindItemsResults <Item> findResults = _CurrentService.FindItems(WellKnownFolderName.Calendar, searchFilter, view);

            foreach (Item item in findResults.Items)
            {
                Appointment appt = item as Appointment;
                if (appt.AppointmentType == AppointmentType.RecurringMaster)
                {
                    // Calendar item is a recurring master item for a recurring series.
                }
                if (appt.AppointmentType == AppointmentType.Occurrence)
                {
                    // Calendar item is an occurrence in a recurring series.
                }
                else if (appt.AppointmentType == AppointmentType.Exception)
                {
                    // Calendar item is an exception in a recurring series.
                }
            }
        }
コード例 #2
0
ファイル: FolderIdDialog.cs プロジェクト: zyonet/EwsEditor
        ///// <summary>
        ///// Show modal FolderIdDialog, if 'OK' not clicked return
        ///// NULL.
        ///// </summary>
        ///// <param name="id">Output parameter.</param>
        ///// <returns>
        ///// DialogResult indicating whether the user clicked
        ///// OK or cancelled the dialog.
        ///// </returns>
        //public static DialogResult ShowDialog(ref FolderId )
        //{
        //    id = null;

        //    //dialog._ExchangeService = oExchangeService;

        //    FolderIdDialog dialog = new FolderIdDialog();

        //    DialogResult res = ((Form)dialog).ShowDialog();

        //    if (res == DialogResult.OK)
        //    {
        //        id = dialog.currentFolderId;
        //    }

        //    return res;
        //}

        private void OkButton_Click(object sender, EventArgs e)
        {
            if (UniqueIdRadio.Checked)
            {
                if (this.SpecFolderIdText.Text.Length == 0)
                {
                    ErrorDialog.ShowWarning("A FolderId must be entered.");
                    // this.DialogResult = DialogResult.None;
                    this.ChoseOK = false;
                }
                else
                {
                    this.ChosenFolderId = new FolderId(this.SpecFolderIdText.Text);

                    //FolderId idPublicFoldersRoot = new FolderId(WellKnownFolderName.PublicFoldersRoot);
                    //if (this.ChosenFolderId == idPublicFoldersRoot)
                    //{
                    //    if (_ExchangeService.HttpHeaders.ContainsKey("X-PublicFolderMailbox"))
                    //        _ExchangeService.HttpHeaders.Remove("X-PublicFolderMailbox");
                    //    ...
                    //    GetUserSettingsResponse userResponse = GetUserSettings(adservice, "*****@*****.**", 3, UserSettingName.PublicFolderInformation);
                    //    Console.WriteLine("X-AnchorMailbox value for public folder hierarchy requests: {0}", userResponse.Settings[UserSettingName.PublicFolderInformation]);
                    //}

                    this.ChoseOK = true;
                    this.Close();
                }
            }

            if (WellKnownRadio.Checked)
            {
                WellKnownFolderName name = this.wellKnownFolderCombo.SelectedItem.Value;

                // Exchange throws a schema validation error if FolderId(WellKnownName, Mailbox)
                // is passed an empty string for mailbox address so don't do that!
                if (this.MailboxAddressText.Text.Length == 0)
                {
                    this.ChosenFolderId = new FolderId(name);
                }
                else
                {
                    this.ChosenFolderId = new FolderId(name, new Mailbox(MailboxAddressText.Text));
                }

                this.ChoseOK = true;
                this.Close();
            }

            if (this.rdoSelectFolder.Checked)
            {
                if (this.txtPickedFolder.Text.Trim().Length == 0)
                {
                    ErrorDialog.ShowWarning("A Folder must be selected.");
                    //this.DialogResult = DialogResult.None;
                    this.ChoseOK = false;
                }
                else
                {
                    // base = {AAMkADE3ZDEyNzIyLWNmYTEtNDJjNC1iMDcxLWQ1YzRlOTllNThmZgAuAAAAAAAPhJtWhlq+R7kfwUCSYEOdAQATi1dys5KiTYjQdU3KXtHXAAABXjDIAAA=}
                    ChosenFolderId = new FolderId(this.txtPickedFolder.Text);
                    this.ChoseOK   = true;
                    this.Close();
                }
            }
        }
コード例 #3
0
        private void MnuSaveAttach_Click(object sender, EventArgs e)
        {
            // Don't do anything if a content row is not selected
            if (this.ContentsGrid.SelectedRows.Count == 0)
            {
                return;
            }

            Attachment attach = this.ContentsGrid.SelectedRows[0].Cells[ColNameAttachmentObj].Value as Attachment;

            // If we can't get the attachment object bail out
            if (attach == null)
            {
                return;
            }

            // Get the file name we'll save to and bail out if we don't succeed
            // Create a file path to save the item properties to
            string fileName = null;

            //fileName = string.Format(
            //System.Globalization.CultureInfo.CurrentCulture,
            //    "{0}\\{1}.xml",
            //    destinationFolderPath,
            //    FileHelper.SanitizeFileName(item.Subject));

            fileName = this.GetTargetFileName(fileName);
            if (fileName == string.Empty)
            {
                return;
            }

            // If the attachment is a FileAttachment then simply save the content
            FileAttachment fileAttach = attach as FileAttachment;

            if (fileAttach != null)
            {
                if (fileAttach.Content == null)
                {
                    ErrorDialog.ShowWarning("Cannot save FileAttachment because FileAttachment.Content is NULL.");
                    return;
                }

                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    System.IO.File.WriteAllBytes(fileName, fileAttach.Content);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
            else
            {
                ItemAttachment itemAttachment = attach as ItemAttachment;
                if (itemAttachment != null)
                {
                    if (itemAttachment.Item == null)
                    {
                        ErrorDialog.ShowWarning("Cannot save ItemAttachment because ItemAttachment.Item is NULL.");
                        return;
                    }

                    try
                    {
                        this.Cursor = Cursors.WaitCursor;

                        EWSEditor.Common.DumpHelper.DumpXML(
                            itemAttachment.Item,
                            fileName);
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }
                }
            }
        }
コード例 #4
0
        private void GetAvailabilityButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                // Get AttendeeInfo from AttendeeList
                List <AttendeeInfo> attendees = null;
                if (!this.TryGetAttendeesFromList(out attendees))
                {
                    ErrorDialog.ShowWarning("There must be at least one attendee listed to retrieve availability for.");
                    return;
                }

                // Get TimeWindow from input
                TimeWindow window = new TimeWindow(
                    this.StartWindowDate.Value.ToUniversalTime(),
                    this.EndWindowDate.Value.ToUniversalTime());

                // Get RequestedData from input
                AvailabilityData requestedData = AvailabilityData.FreeBusy;
                if (this.availDataCombo.SelectedItem.HasValue)
                {
                    requestedData = this.availDataCombo.SelectedItem.Value;
                }

                // Collect AvailabilityOptions from form input
                AvailabilityOptions options = new AvailabilityOptions();
                if (this.CurrentMeetingCheck.Checked)
                {
                    options.CurrentMeetingTime = this.CurrentMeetingDate.Value;
                }
                else
                {
                    options.CurrentMeetingTime = null;
                }

                options.MeetingDuration           = Convert.ToInt32(this.MeetingDurationText.Text);
                options.DetailedSuggestionsWindow = new TimeWindow(
                    this.StartDetailDate.Value,
                    this.EndDetailDate.Value);
                options.GlobalObjectId          = this.GlobalObjectIdText.Text;
                options.GoodSuggestionThreshold = Convert.ToInt32(this.GoodSuggestThresholdText.Text);
                options.MaximumNonWorkHoursSuggestionsPerDay = Convert.ToInt32(this.MaxNonWorkSuggestText.Text);
                options.MaximumSuggestionsPerDay             = Convert.ToInt32(this.MaxSuggestPerDayText.Text);
                options.MergedFreeBusyInterval = Convert.ToInt32(this.MergeFBIntervalText.Text);

                if (this.minSuggestQualCombo.SelectedItem.HasValue)
                {
                    options.MinimumSuggestionQuality = this.minSuggestQualCombo.SelectedItem.Value;
                }

                if (this.requestFBViewCombo.SelectedItem.HasValue)
                {
                    options.RequestedFreeBusyView = this.requestFBViewCombo.SelectedItem.Value;
                }

                // Remember which attendee was selected in the AttendeeList
                int selectedIndex = -1;
                if (this.AttendeeList.SelectedItems != null &&
                    this.AttendeeList.SelectedItems.Count == 1)
                {
                    selectedIndex = this.AttendeeList.SelectedItems[0].Index;
                    this.AttendeeList.Items[selectedIndex].Selected = false;
                }

                // Make the EWS request
                GetUserAvailabilityResults results = this.CurrentService.GetUserAvailability(
                    attendees,
                    window,
                    requestedData,
                    options);

                // Enable result lists
                this.AttendeeAvailabilityList.Enabled = true;
                this.CalEventsList.Enabled            = true;
                this.SuggestionsList.Enabled          = true;

                // Attach AttendeeAvailability to the associated attendee in the ListView.
                // It can be assumed that the order of the AttendeesAvailability and Suggestions
                // results arrays correspond to the order of the attendees.
                for (int i = 0; i < attendees.Count; i++)
                {
                    AttendeeAvailability availResult = null;
                    if (results.AttendeesAvailability != null &&
                        results.AttendeesAvailability[i] != null)
                    {
                        availResult = results.AttendeesAvailability[i];
                    }

                    this.AddResultsToAttendee(attendees[i], availResult);
                }

                if (results.Suggestions != null)
                {
                    // Display the Suggestion in the ListView
                    foreach (Suggestion suggest in results.Suggestions)
                    {
                        foreach (TimeSuggestion time in suggest.TimeSuggestions)
                        {
                            ListViewItem timeItem = this.SuggestionsList.Items.Add(suggest.Date.ToShortDateString());
                            timeItem.SubItems.Add(suggest.Quality.ToString());
                            timeItem.SubItems.Add(time.MeetingTime.ToShortTimeString());
                            timeItem.SubItems.Add(time.Quality.ToString());
                            timeItem.SubItems.Add(time.Conflicts.Count.ToString());
                            timeItem.SubItems.Add(time.IsWorkTime.ToString());
                        }
                    }
                }

                // Reset the selected Attendee and display the results or show a message
                // to inform the user how to display results.
                if (selectedIndex > -1)
                {
                    this.AttendeeList.Items[selectedIndex].Selected = true;
                }
                else
                {
                    //this.AttendeeAvailabilityGroup.Text = "Select an attendee in the list to display availability results.";
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
コード例 #5
0
        private void BtnOK_Click(object sender, EventArgs e)
        {
            // Validation for credential input...
            if (rdoCredentialsUserSpecified.Checked && (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SPECIFY_CREDS);
                return;
            }

            // Validation for Autodiscover input...

            if (this.rdoAutodiscoverEmail.Checked && String.IsNullOrEmpty(this.AutodiscoverEmailText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for URL input...
            if (this.rdoServiceUrl.Checked && String.IsNullOrEmpty(this.ExchangeServiceURLText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for Impersonation input...
            if (this.ImpersonationCheck.Checked && (String.IsNullOrEmpty(this.ImpersonatedIdTextBox.Text) || !this.connectingIdCombo.SelectedItem.HasValue))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_IMPERSON_REQ);
                return;
            }

            try
            {
                Cursor = System.Windows.Forms.Cursors.WaitCursor;

                EwsProxyFactory.RequestedExchangeVersion = exchangeVersionCombo.SelectedItem;

                EwsProxyFactory.OverrideTimezone   = GlobalSettings.OverrideTimezone;
                EwsProxyFactory.SelectedTimeZoneId = GlobalSettings.SelectedTimeZoneId;

                EwsProxyFactory.AllowAutodiscoverRedirect = GlobalSettings.AllowAutodiscoverRedirect;

                EwsProxyFactory.UseDefaultCredentials = this.rdoCredentialsDefaultWindows.Checked;
                if (this.rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.DefaultAuth;
                }

                EwsProxyFactory.CredentialsUserSpecified = this.rdoCredentialsUserSpecified.Checked;

                if (this.rdoCredentialsUserSpecified.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.SpecifiedCredentialsAuth;
                }

                if (this.rdoCredentialsOAuth.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth;
                }

                // MailboxBeingAccessed
                switch (EwsProxyFactory.AuthenticationMethod)
                {
                case RequestedAuthType.DefaultAuth:
                    AutodiscoverEmailText.Text = UserPrincipal.Current.EmailAddress;
                    //if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    //    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    break;

                case RequestedAuthType.SpecifiedCredentialsAuth:
                    if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    }
                    else
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.txtUserName.Text.Trim();
                    }
                    break;

                case RequestedAuthType.oAuth:
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();      // override later in ewsproxyfactory
                    break;
                }

                if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                {
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                }
                if (this.ImpersonationCheck.Checked) // Override
                {
                    EwsProxyFactory.MailboxBeingAccessed = ImpersonatedIdTextBox.Text.Trim();
                }


                EwsProxyFactory.UserImpersonationSelected = this.ImpersonationCheck.Checked;
                //EwsProxyFactory.UserToImpersonate = this.ImpersonatedIdTextBox.Text  // set below
                EwsProxyFactory.ImpersonationType = this.connectingIdCombo.SelectedItem.Value.ToString();
                EwsProxyFactory.ImpersonatedId    = this.ImpersonatedIdTextBox.Text.Trim();


                EwsProxyFactory.UseoAuth         = this.rdoCredentialsOAuth.Checked;
                EwsProxyFactory.oAuthRedirectUrl = this.txtOAuthRedirectUri.Text.Trim();
                EwsProxyFactory.oAuthClientId    = this.txtOAuthAppId.Text.Trim();
                EwsProxyFactory.oAuthServerName  = this.txtOAuthServerName.Text.Trim();
                EwsProxyFactory.oAuthAuthority   = this.txtOAuthAuthority.Text.Trim();


                EwsProxyFactory.EnableScpLookup = GlobalSettings.EnableScpLookups;
                EwsProxyFactory.PreAuthenticate = GlobalSettings.PreAuthenticate;

                EwsProxyFactory.OverrideTimeout = GlobalSettings.OverrideTimeout;
                EwsProxyFactory.Timeout         = GlobalSettings.Timeout;
                EwsProxyFactory.UserAgent       = GlobalSettings.UserAgent;

                EwsProxyFactory.UserName = this.txtUserName.Text.Trim();
                // EwsProxyFactory.Password = this.txtPassword.Text.Trim();   // Don't keep.
                EwsProxyFactory.Domain = this.txtDomain.Text.Trim();

                EwsProxyFactory.SetDefaultProxy            = GlobalSettings.SetDefaultProxy;
                EwsProxyFactory.BypassProxyForLocalAddress = GlobalSettings.BypassProxyForLocalAddress;
                EwsProxyFactory.SpecifyProxySettings       = GlobalSettings.SpecifyProxySettings;
                EwsProxyFactory.ProxyServerName            = GlobalSettings.ProxyServerName;
                EwsProxyFactory.ProxyServerPort            = GlobalSettings.ProxyServerPort;
                EwsProxyFactory.OverrideProxyCredentials   = GlobalSettings.OverrideProxyCredentials;
                EwsProxyFactory.ProxyServerUser            = GlobalSettings.ProxyServerUser;
                EwsProxyFactory.ProxyServerPassword        = GlobalSettings.ProxyServerPassword;
                EwsProxyFactory.ProxyServerDomain          = GlobalSettings.ProxyServerDomain;



                EwsProxyFactory.EwsUrl = this.rdoAutodiscoverEmail.Checked ?
                                         null : new Uri(ExchangeServiceURLText.Text.Trim());

                EwsProxyFactory.UserToImpersonate = this.ImpersonationCheck.Checked ?
                                                    new ImpersonatedUserId(this.connectingIdCombo.SelectedItem.Value, this.ImpersonatedIdTextBox.Text.Trim()) : null;

                EwsProxyFactory.SetXAnchorMailbox = this.chkSetXAnchorMailbox.Checked;
                EwsProxyFactory.XAnchorMailbox    = this.txtXAnchorMailbox.Text.Trim();

                EwsProxyFactory.SetXPublicFolderMailbox = this.chkSetXPublicFolderMailbox.Checked;
                EwsProxyFactory.XPublicFolderMailbox    = this.txtXPublicFolderMailbox.Text.Trim();



                EwsProxyFactory.EnableAdditionalHeader1 = GlobalSettings.EnableAdditionalHeader1;
                EwsProxyFactory.AdditionalHeader1       = GlobalSettings.AdditionalHeader1;
                EwsProxyFactory.AdditionalHeaderValue1  = GlobalSettings.AdditionalHeaderValue1;
                EwsProxyFactory.EnableAdditionalHeader2 = GlobalSettings.EnableAdditionalHeader2;
                EwsProxyFactory.AdditionalHeader2       = GlobalSettings.AdditionalHeader2;
                EwsProxyFactory.AdditionalHeaderValue2  = GlobalSettings.AdditionalHeaderValue2;
                EwsProxyFactory.EnableAdditionalHeader3 = GlobalSettings.EnableAdditionalHeader3;
                EwsProxyFactory.AdditionalHeader3       = GlobalSettings.AdditionalHeader3;
                EwsProxyFactory.AdditionalHeaderValue3  = GlobalSettings.AdditionalHeaderValue3;

                EwsProxyFactory.AddTimeZoneContext        = GlobalSettings.AddTimeZoneContext;
                EwsProxyFactory.SelectedTimeZoneContextId = GlobalSettings.SelectedTimeZoneContextId;


                EwsProxyFactory.ServiceEmailAddress = this.AutodiscoverEmailText.Text.Trim();
                EwsProxyFactory.UseAutoDiscover     = this.rdoAutodiscoverEmail.Checked;

                //EwsProxyFactory.ServiceCredential = rdoCredentialsUserSpecified.Checked ?
                //   new NetworkCredential(
                //       this.txtUserName.Text.Trim(),
                //       this.txtPassword.Text.Trim(),  // This will fail on passwords ending with whitespace
                //       this.txtDomain.Text.Trim()) :
                //   null;

                // ----- Set Credentials ----
                EwsProxyFactory.ServiceCredential        = null;
                EwsProxyFactory.ServiceNetworkCredential = null;

                if (rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.ServiceCredential = (NetworkCredential)CredentialCache.DefaultCredentials;

                    EwsProxyFactory.ServiceNetworkCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
                }

                if (rdoCredentialsUserSpecified.Checked)
                {
                    NetworkCredential oNetworkCredential = new NetworkCredential(
                        this.txtUserName.Text.Trim(),
                        this.txtPassword.Text.Trim(), // This will fail on passwords ending with whitespace
                        this.txtDomain.Text.Trim());

                    EwsProxyFactory.ServiceCredential = oNetworkCredential;

                    EwsProxyFactory.ServiceNetworkCredential = oNetworkCredential;
                }


                if (this.rdoCredentialsOAuth.Checked)
                {
                    AuthenticationHelper oAH = new AuthenticationHelper();

                    EwsProxyFactory.ServiceCredential = oAH.Do_OAuth(ref EwsProxyFactory.MailboxBeingAccessed, ref EwsProxyFactory.AccountAccessingMailbox,
                                                                     EwsProxyFactory.oAuthAuthority, EwsProxyFactory.oAuthClientId, EwsProxyFactory.oAuthRedirectUrl, EwsProxyFactory.oAuthServerName);

                    //EwsProxyFactory.AccountAccessingMailbox
                    //EwsProxyFactory.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
                }

                // ----    Autodiscover    ----

                if (this.rdoAutodiscoverEmail.Checked)
                {
                    EwsProxyFactory.DoAutodiscover();
                }

                // ----    New service & app settings    ----

                CurrentService = EwsProxyFactory.CreateExchangeService();


                // ----    Save settings    ----
                EWSEditor.Common.EwsEditorAppSettings oAppSettings = new EwsEditorAppSettings();
                EwsProxyFactory.SetAppSettingsFromProxyFactory(ref oAppSettings);
                CurrentAppSettings = oAppSettings;

                //CurrentAppSettings.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
                // CurrentAppSettings

                // EwsProxyFactory.AccountAccessingMailbox

                // ----    Do a basic test to be sure that the mailbox can be reached with an EWS call   ----
                if (CheckOnOkay)
                {
                    CurrentService.TestExchangeService();
                }

                CurrentService.OnSerializeCustomSoapHeaders += m_Service_OnSerializeCustomSoapHeaders;


                DialogResult = DialogResult.OK;
            }
            finally
            {
                Cursor = System.Windows.Forms.Cursors.Default;
            }
        }
コード例 #6
0
        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (rdoCredentialsOAuth2.Checked == true)
            {
                if (txtOAuthApplicationId.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo("Applicaiton Id is required for oAuth.");
                    return;
                }
                if (txtOAuthTenantId.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo("Tenant Id is required for oAuth.");
                    return;
                }
            }


            // Doing App permissions flow?
            if (rdoCredentialsOAuth2.Checked == true && rdoCredentialsOAuthApplication.Checked)
            {
                if (txtOAuthTenantId.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo("Client Secret is required for oAuth Applicaiton permissions flow.");
                    return;
                }

                if (this.ImpersonationCheck.Checked == false || this.ImpersonatedIdTextBox.Text.Trim() == string.Empty)
                {
                    // Impersonation is required for app permissions flow
                    ErrorDialog.ShowInfo(DisplayStrings.MSG_IMPERSONATION_NEEDED_FOR_APP_PERMISSIONS_FLOW);
                    return;
                }

                // X-AnchorMailbox is required
                if (this.chkSetXAnchorMailbox.Checked == false || this.txtXAnchorMailbox.Text.Trim() == string.Empty)
                {
                    ErrorDialog.ShowInfo(DisplayStrings.MSG_XANCHORMAILBOX_FOR_APP_PERMISSIONS_FLOW);
                    return;
                }
            }
            // Validation for credential input...
            if (rdoCredentialsUserSpecified.Checked && (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SPECIFY_CREDS);
                return;
            }

            // Validation for Autodiscover input...

            if (this.rdoAutodiscoverEmail.Checked && String.IsNullOrEmpty(this.AutodiscoverEmailText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for URL input...
            if (this.rdoServiceUrl.Checked && String.IsNullOrEmpty(this.ExchangeServiceURLText.Text))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
                return;
            }

            // Validation for Impersonation input...
            if (this.ImpersonationCheck.Checked && (String.IsNullOrEmpty(this.ImpersonatedIdTextBox.Text) || !this.connectingIdCombo.SelectedItem.HasValue))
            {
                ErrorDialog.ShowInfo(DisplayStrings.MSG_IMPERSON_REQ);
                return;
            }

            // Impersonation should always need X-AnchorMailbox header set or call will fail at any time.
            if (this.ImpersonationCheck.Checked == true && this.chkSetXAnchorMailbox.Checked == false)
            {
                ErrorDialog.ShowInfo(DisplayStrings.WARN_IMPERSONATION_NEEDS_XANCHORMAILBOX);
            }

            try
            {
                Cursor = System.Windows.Forms.Cursors.WaitCursor;

                EwsProxyFactory.RequestedExchangeVersion = exchangeVersionCombo.SelectedItem;

                EwsProxyFactory.OverrideTimezone   = GlobalSettings.OverrideTimezone;
                EwsProxyFactory.SelectedTimeZoneId = GlobalSettings.SelectedTimeZoneId;

                EwsProxyFactory.AllowAutodiscoverRedirect = GlobalSettings.AllowAutodiscoverRedirect;

                EwsProxyFactory.UseDefaultCredentials = this.rdoCredentialsDefaultWindows.Checked;
                if (this.rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.DefaultAuth;
                }

                EwsProxyFactory.CredentialsUserSpecified = this.rdoCredentialsUserSpecified.Checked;

                if (this.rdoCredentialsUserSpecified.Checked == true)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.SpecifiedCredentialsAuth;
                }

                if (this.rdoCredentialsOAuth.Checked)
                {
                    EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth;
                }

                if (this.rdoCredentialsOAuth2.Checked)
                {
                    if (this.rdoCredentialsOAuthDelegated.Checked)
                    {
                        EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth2Delegate;
                    }

                    if (this.rdoCredentialsOAuthApplication.Checked)
                    {
                        EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth2Application;
                    }

                    if (this.rdoCredentialsOAuthCertificate.Checked)
                    {
                        EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth2Certificate;
                    }
                }

                // MailboxBeingAccessed
                EwsProxyFactory.MailboxBeingAccessed = string.Empty;
                switch (EwsProxyFactory.AuthenticationMethod)
                {
                case RequestedAuthType.DefaultAuth:
                    AutodiscoverEmailText.Text = UserPrincipal.Current.EmailAddress;
                    break;

                case RequestedAuthType.SpecifiedCredentialsAuth:
                    if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    }
                    else
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.txtUserName.Text.Trim();
                    }
                    break;

                case RequestedAuthType.oAuth2Application:
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    break;

                case RequestedAuthType.oAuth2Delegate:
                    if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                    {
                        EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                    }
                    break;

                default:
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();      // override later in ewsproxyfactory (for oAuth)
                    break;
                }

                if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
                {
                    EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
                }
                if (this.ImpersonationCheck.Checked) // Override
                {
                    EwsProxyFactory.MailboxBeingAccessed = ImpersonatedIdTextBox.Text.Trim();
                }

                if (EwsProxyFactory.MailboxBeingAccessed == string.Empty && this.chkSetXAnchorMailbox.Checked && this.txtXAnchorMailbox.Text.Trim().Length != 0)
                {
                    EwsProxyFactory.MailboxBeingAccessed = this.txtXAnchorMailbox.Text.Trim();
                }


                EwsProxyFactory.UserImpersonationSelected = this.ImpersonationCheck.Checked;
                //EwsProxyFactory.UserToImpersonate = this.ImpersonatedIdTextBox.Text  // set below
                EwsProxyFactory.ImpersonationType = this.connectingIdCombo.SelectedItem.Value.ToString();
                EwsProxyFactory.ImpersonatedId    = this.ImpersonatedIdTextBox.Text.Trim();


                EwsProxyFactory.UseoAuth         = this.rdoCredentialsOAuth.Checked;
                EwsProxyFactory.oAuthRedirectUrl = this.txtOAuthRedirectUri.Text.Trim();
                EwsProxyFactory.oAuthClientId    = this.txtOAuthAppId.Text.Trim();
                EwsProxyFactory.oAuthServerName  = this.txtOAuthServerName.Text.Trim();
                EwsProxyFactory.oAuthAuthority   = this.txtOAuthAuthority.Text.Trim();

                EwsProxyFactory.UseoAuth2           = this.rdoCredentialsOAuth2.Checked;
                EwsProxyFactory.UseOAuthDelegate    = this.rdoCredentialsOAuthDelegated.Checked;
                EwsProxyFactory.UseOAuthApplication = this.rdoCredentialsOAuthApplication.Checked;
                EwsProxyFactory.oAuthApplicationId  = this.txtOAuthApplicationId.Text.Trim();
                EwsProxyFactory.oAuthTenantId       = this.txtOAuthTenantId.Text.Trim();
                EwsProxyFactory.oAuthClientSecret   = this.txtOAuthClientSecret.Text.Trim();
                // EwsProxyFactory.oAuthCertificate = this.txtAuthCertificate.Text.Trim();
                EwsProxyFactory.oBearerToken     = string.Empty;
                EwsProxyFactory.LogSecurityToken = GlobalSettings.LogSecurityToken;


                EwsProxyFactory.EnableScpLookup = GlobalSettings.EnableScpLookups;
                EwsProxyFactory.PreAuthenticate = GlobalSettings.PreAuthenticate;

                EwsProxyFactory.OverrideTimeout = GlobalSettings.OverrideTimeout;
                EwsProxyFactory.Timeout         = GlobalSettings.Timeout;
                EwsProxyFactory.UserAgent       = GlobalSettings.UserAgent;

                EwsProxyFactory.UserName = this.txtUserName.Text.Trim();
                // EwsProxyFactory.Password = this.txtPassword.Text.Trim();   // Don't keep.
                EwsProxyFactory.Domain = this.txtDomain.Text.Trim();

                EwsProxyFactory.SetDefaultProxy            = GlobalSettings.SetDefaultProxy;
                EwsProxyFactory.BypassProxyForLocalAddress = GlobalSettings.BypassProxyForLocalAddress;
                EwsProxyFactory.SpecifyProxySettings       = GlobalSettings.SpecifyProxySettings;
                EwsProxyFactory.ProxyServerName            = GlobalSettings.ProxyServerName;
                EwsProxyFactory.ProxyServerPort            = GlobalSettings.ProxyServerPort;
                EwsProxyFactory.OverrideProxyCredentials   = GlobalSettings.OverrideProxyCredentials;
                EwsProxyFactory.ProxyServerUser            = GlobalSettings.ProxyServerUser;
                EwsProxyFactory.ProxyServerPassword        = GlobalSettings.ProxyServerPassword;
                EwsProxyFactory.ProxyServerDomain          = GlobalSettings.ProxyServerDomain;



                EwsProxyFactory.EwsUrl = this.rdoAutodiscoverEmail.Checked ?
                                         null : new Uri(ExchangeServiceURLText.Text.Trim());

                EwsProxyFactory.UserToImpersonate = this.ImpersonationCheck.Checked ?
                                                    new ImpersonatedUserId(this.connectingIdCombo.SelectedItem.Value, this.ImpersonatedIdTextBox.Text.Trim()) : null;

                EwsProxyFactory.SetXAnchorMailbox = this.chkSetXAnchorMailbox.Checked;
                EwsProxyFactory.XAnchorMailbox    = this.txtXAnchorMailbox.Text.Trim();

                EwsProxyFactory.SetXPublicFolderMailbox = this.chkSetXPublicFolderMailbox.Checked;
                EwsProxyFactory.XPublicFolderMailbox    = this.txtXPublicFolderMailbox.Text.Trim();



                EwsProxyFactory.EnableAdditionalHeader1 = GlobalSettings.EnableAdditionalHeader1;
                EwsProxyFactory.AdditionalHeader1       = GlobalSettings.AdditionalHeader1;
                EwsProxyFactory.AdditionalHeaderValue1  = GlobalSettings.AdditionalHeaderValue1;
                EwsProxyFactory.EnableAdditionalHeader2 = GlobalSettings.EnableAdditionalHeader2;
                EwsProxyFactory.AdditionalHeader2       = GlobalSettings.AdditionalHeader2;
                EwsProxyFactory.AdditionalHeaderValue2  = GlobalSettings.AdditionalHeaderValue2;
                EwsProxyFactory.EnableAdditionalHeader3 = GlobalSettings.EnableAdditionalHeader3;
                EwsProxyFactory.AdditionalHeader3       = GlobalSettings.AdditionalHeader3;
                EwsProxyFactory.AdditionalHeaderValue3  = GlobalSettings.AdditionalHeaderValue3;

                EwsProxyFactory.AddTimeZoneContext        = GlobalSettings.AddTimeZoneContext;
                EwsProxyFactory.SelectedTimeZoneContextId = GlobalSettings.SelectedTimeZoneContextId;


                EwsProxyFactory.ServiceEmailAddress = this.AutodiscoverEmailText.Text.Trim();
                EwsProxyFactory.UseAutoDiscover     = this.rdoAutodiscoverEmail.Checked;

                //EwsProxyFactory.ServiceCredential = rdoCredentialsUserSpecified.Checked ?
                //   new NetworkCredential(
                //       this.txtUserName.Text.Trim(),
                //       this.txtPassword.Text.Trim(),  // This will fail on passwords ending with whitespace
                //       this.txtDomain.Text.Trim()) :
                //   null;

                // ----- Set Credentials ----
                EwsProxyFactory.ServiceCredential        = null;
                EwsProxyFactory.ServiceNetworkCredential = null;

                if (rdoCredentialsDefaultWindows.Checked)
                {
                    EwsProxyFactory.ServiceCredential = (NetworkCredential)CredentialCache.DefaultCredentials;

                    EwsProxyFactory.ServiceNetworkCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
                }

                if (rdoCredentialsUserSpecified.Checked)
                {
                    NetworkCredential oNetworkCredential = new NetworkCredential(
                        this.txtUserName.Text.Trim(),
                        this.txtPassword.Text.Trim(), // This will fail on passwords ending with whitespace
                        this.txtDomain.Text.Trim());

                    EwsProxyFactory.ServiceCredential = oNetworkCredential;

                    EwsProxyFactory.ServiceNetworkCredential = oNetworkCredential;
                }

                // Delegagte oAuth 1
                if (this.rdoCredentialsOAuth.Checked)
                {
                    AuthenticationHelper oAH = new AuthenticationHelper();
                    string sBearerToken      = string.Empty;
                    EwsProxyFactory.ServiceCredential = oAH.Do_OAuth(ref EwsProxyFactory.MailboxBeingAccessed, ref EwsProxyFactory.AccountAccessingMailbox,
                                                                     EwsProxyFactory.oAuthAuthority, EwsProxyFactory.oAuthClientId, EwsProxyFactory.oAuthRedirectUrl, EwsProxyFactory.oAuthServerName, ref sBearerToken);

                    EwsProxyFactory.oBearerToken = sBearerToken;
                }


                // oAuth2
                if (this.rdoCredentialsOAuth2.Checked)
                {
                    // https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
                    // Microsoft.Identity.Client is available under NewGet
                    // https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-acquire-token?tabs=dotnet

                    // https://www.skylinetechnologies.com/Blog/Skyline-Blog/December_2018/async-await-configureawait

                    // Get Access token -----------------

                    if (this.rdoCredentialsOAuthDelegated.Checked)
                    {
                        EWSEditor.Common.Auth.OAuthHelper o = new EWSEditor.Common.Auth.OAuthHelper();
                        AuthenticationResult oResult        = System.Threading.Tasks.Task.Run(async() => await o.GetDelegateToken(EwsProxyFactory.oAuthApplicationId, EwsProxyFactory.oAuthTenantId)).Result;
                        EwsProxyFactory.MsalAuthenticationResult = oResult;
                        var oCredentials = new Microsoft.Exchange.WebServices.Data.OAuthCredentials(oResult.AccessToken);

                        EwsProxyFactory.ServiceCredential              = oCredentials;
                        EwsProxyFactory.MsalAuthenticationResult       = oResult;
                        EwsProxyFactory.oBearerToken                   = oResult.AccessToken;
                        EwsProxyFactory.CurrentPublicClientApplication = o.CurrentPublicClientApplication;

                        EwsProxyFactory.MailboxBeingAccessed = oResult.Account.Username;
                    }

                    if (this.rdoCredentialsOAuthApplication.Checked)
                    {
                        EWSEditor.Common.Auth.OAuthHelper o = new EWSEditor.Common.Auth.OAuthHelper();
                        AuthenticationResult oResult        = System.Threading.Tasks.Task.Run(async() => await o.GetApplicationToken(EwsProxyFactory.oAuthApplicationId,
                                                                                                                                     EwsProxyFactory.oAuthTenantId,
                                                                                                                                     EwsProxyFactory.oAuthClientSecret)).Result;

                        var oCredentials = new Microsoft.Exchange.WebServices.Data.OAuthCredentials(oResult.AccessToken);

                        EwsProxyFactory.ServiceCredential              = oCredentials;
                        EwsProxyFactory.MsalAuthenticationResult       = oResult;
                        EwsProxyFactory.oBearerToken                   = oResult.AccessToken;
                        EwsProxyFactory.CurrentPublicClientApplication = o.CurrentPublicClientApplication;
                    }

                    if (this.rdoCredentialsOAuthCertificate.Checked)
                    {
                        EWSEditor.Common.Auth.OAuthHelper o = new EWSEditor.Common.Auth.OAuthHelper();

                        AuthenticationResult oResult = System.Threading.Tasks.Task.Run(async() => await o.GetCertificateToken(EwsProxyFactory.oAuthApplicationId,
                                                                                                                              EwsProxyFactory.oAuthTenantId,
                                                                                                                              EwsProxyFactory.oAuthClientCertificate)).Result;



                        var oCredentials = new Microsoft.Exchange.WebServices.Data.OAuthCredentials(oResult.AccessToken);

                        EwsProxyFactory.ServiceCredential              = oCredentials;
                        EwsProxyFactory.MsalAuthenticationResult       = oResult;
                        EwsProxyFactory.oBearerToken                   = oResult.AccessToken;
                        EwsProxyFactory.CurrentPublicClientApplication = o.CurrentPublicClientApplication;
                    }
                }


                // ----    Autodiscover    ----

                if (this.rdoAutodiscoverEmail.Checked)
                {
                    EwsProxyFactory.DoAutodiscover();
                }

                // ----    New service & app settings    ----

                CurrentService = EwsProxyFactory.CreateExchangeService();


                // ----    Save settings    ----
                EWSEditor.Common.EwsEditorAppSettings oAppSettings = new EwsEditorAppSettings();
                EwsProxyFactory.SetAppSettingsFromProxyFactory(ref oAppSettings);
                CurrentAppSettings = oAppSettings;


                //CurrentAppSettings.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
                // CurrentAppSettings

                // EwsProxyFactory.AccountAccessingMailbox

                // ----    Do a basic test to be sure that the mailbox can be reached with an EWS call   ----
                CurrentService.TestExchangeService();

                CurrentService.OnSerializeCustomSoapHeaders += m_Service_OnSerializeCustomSoapHeaders;


                DialogResult = DialogResult.OK;
            }
            finally
            {
                Cursor = System.Windows.Forms.Cursors.Default;
            }
        }