private void btnAutodiscoverExternal_Click(object sender, EventArgs e)
        {
            int iMaxHops = 15;

            bool bDoAutodiscover = true;

            this.Cursor = Cursors.WaitCursor;

            txtTracing.Text = string.Empty;

            _IML = new InMemoryListener();

            bDoAutodiscover = CheckCredentials(
                this.chkDefaultWindowsCredentials.Checked,
                this.txtUser.Text,
                this.txtPassword.Text,
                this.txtDomain.Text
                );

            if (this.txtTargetMailboxText.Text.Trim().Length == 0)
            {
                MessageBox.Show("The target mailbox smtp address needs to be entered.", "Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                bDoAutodiscover = false;
            }

            if (bDoAutodiscover == true)
            {
                txtTracing.Text = string.Empty;
                txtTracing.Update();

                NetworkCredential oNetworkCredential = null;
                oNetworkCredential = GetCredentials(
                    this.chkDefaultWindowsCredentials.Checked,
                    txtUser.Text.Trim(),
                    txtPassword.Text.Trim(),
                    txtDomain.Text.Trim()
                    );

                DoAutoDiscoverRaw(
                    DiscoverType.Pox,
                    ref _IML,
                    txtTargetMailboxText.Text.Trim(),
                    oNetworkCredential,
                    iMaxHops,
                    chkAllowSelfSignedCerts.Checked,
                    chkTraceCertificateInformation.Checked
                    );
            }

            txtTracing.Text = _IML.LogText;

            _IML = null;

            this.Cursor = Cursors.Default;
        }
 public InMemoryPeerFactory(InMemoryConnectionCenter center, InMemoryListener server)
 {
     this.center = center;
     this.server = server;
 }
        private void DoAutodiscoverDirectlyAgainstAutiodiscoverService()
        {
            bool bEnableInMemoryTracing = true;

            this.Cursor = Cursors.WaitCursor;

            _Certs     = string.Empty;
            _Redirects = string.Empty;
            WebCredentials   credentials = null;
            InMemoryListener oIML        = null;

            string sResults = string.Empty;


            // Clear results
            this.txtCerts.Text   = "";
            this.txtTracing.Text = "";
            this.txtResults.Text = "";

            this.txtCerts.Update();
            this.txtTracing.Update();
            this.txtResults.Update();

            _Version = GetExchangeVersion(cmboExchangeVersion.Text.Trim());

            EwsRedirectLoggingCallbackHelper    oEwsRedirectLoggingCallbackHelper    = new EwsRedirectLoggingCallbackHelper();
            EwsCertificateLoggingCallbackHelper oEwsCertificateLoggingCallbackHelper = new EwsCertificateLoggingCallbackHelper();
            // EwsLoggingCallbackHelper oAutodiscoveryCallbackHelper = new EwsLoggingCallbackHelper();


            AutodiscoverService service = new AutodiscoverService(_Version);

            credentials = GetWebCredentials(
                this.chkDefaultWindowsCredentials.Checked,
                txtUser.Text.Trim(),
                txtPassword.Text.Trim(),
                txtDomain.Text.Trim()
                );


            service.Credentials = credentials;

            // Prevent the AutodiscoverService from looking in the local Active Directory for the Exchange Web Services Services SCP.
            service.EnableScpLookup = this.chkEnableScpLookup.Checked;
            service.PreAuthenticate = this.chkPreAuthenticate.Checked;

            if (bEnableInMemoryTracing == true)
            {
                oIML = new InMemoryListener();          // Enable for EWS tracing
                service.TraceFlags    = TraceFlags.All; // Enable for EWS tracing
                service.TraceEnabled  = true;           // Enable for EWS tracing
                service.TraceListener = oIML;           // Enable for EWS tracing
            }

            service.UserAgent = "AutodiscoverCheckerGetUserSettings";

            ServicePointManager.ServerCertificateValidationCallback = oEwsCertificateLoggingCallbackHelper.CertificateValidationCallBack;

            // Handle and Log redirects

            service.RedirectionUrlValidationCallback         = oEwsRedirectLoggingCallbackHelper.RedirectionUrlValidationCallbackAllowAnything;
            oEwsRedirectLoggingCallbackHelper.UseCredentials = this.GetWebWebRequestCredentials(
                this.chkDefaultWindowsCredentials.Checked,
                txtUser.Text.Trim(),
                txtPassword.Text.Trim(),
                txtDomain.Text.Trim()
                );


            // The following is used in the work-arouind for a redirect which involves an SMTP address change - it needs to be st to what you autodiscovering on.
            oEwsRedirectLoggingCallbackHelper.AutodiscoveringAddress       = txtTargetMailbox.Text.Trim();
            oEwsRedirectLoggingCallbackHelper._DoAddressRedirectWorkAround = chkWorkAroundAddressRedirectIssue.Checked;

            // Do Autodiscover:
            sResults = AutodiscoverGetUserSettings(ref service, txtTargetMailbox.Text.Trim());

            if (oEwsRedirectLoggingCallbackHelper._AddressRedirection == true)
            {
                // Lets do Autodiscover again - but this time use the alternative address.

                string AutodiscoveringAddress = oEwsRedirectLoggingCallbackHelper._RedirectEmailAddress;
                oEwsRedirectLoggingCallbackHelper.ResetRedirects();
                oEwsRedirectLoggingCallbackHelper.AutodiscoveringAddress = AutodiscoveringAddress;

                //oEwsRedirectLoggingCallbackHelper.AutodiscoveringAddress = oEwsRedirectLoggingCallbackHelper._RedirectEmailAddress;
                sResults += "\r\n";
                sResults += "Autodiscover failed but a redirect address was found.  So, do Autodiscover again with the new address.\r\n";
                sResults += "Now doing Autodiscover process with: " + AutodiscoveringAddress + "\r\n\r\n";
                sResults += AutodiscoverGetUserSettings(ref service, AutodiscoveringAddress);
            }

            txtCerts.Text    = oEwsCertificateLoggingCallbackHelper._Certificates;
            txtTracing.Text += "\r\n[*****============================[Redirects]=====================================*****]\r\n\r\n";

            txtTracing.Text += oEwsRedirectLoggingCallbackHelper._RedirectionUrls;

            if (bEnableInMemoryTracing == true)
            {
                txtTracing.Text += "\r\n[*****============================[Trace Log]=====================================*****]\r\n\r\n";
                txtTracing.Text += oIML.LogText;
            }

            txtResults.Text = sResults;

            service.TraceListener = null;
            oIML = null;                                // Enable for EWS tracing

            service.RedirectionUrlValidationCallback = null;
            ServicePointManager.ServerCertificateValidationCallback = null;

            oEwsCertificateLoggingCallbackHelper = null;
            oEwsRedirectLoggingCallbackHelper    = null;

            this.Cursor = Cursors.Default;
        }
        private void DoAutodiscoverUsingServiceObject()
        {
            bool bEnableInMemoryTracing = true;

            this.Cursor = Cursors.WaitCursor;

            this.txtCerts.Text   = string.Empty;
            this.txtResults.Text = string.Empty;
            this.txtTracing.Text = string.Empty;
            this.txtCerts.Update();
            this.txtTracing.Update();
            this.txtResults.Update();

            _Certs     = string.Empty;
            _Redirects = string.Empty;
            WebCredentials   credentials = null;
            InMemoryListener oIML        = null;

            string sResults = string.Empty;

            // Clear results
            this.txtCerts.Text   = "";
            this.txtTracing.Text = "";
            this.txtResults.Text = "";

            _Version = GetExchangeVersion(cmboExchangeVersion.Text.Trim());


            //EwsLoggingCallbackHelper oAutodiscoveryCallbackHelper = new EwsLoggingCallbackHelper();

            ExchangeService service = new ExchangeService(_Version);

            credentials = GetWebCredentials(
                this.chkDefaultWindowsCredentials.Checked,
                txtUser.Text.Trim(),
                txtPassword.Text.Trim(),
                txtDomain.Text.Trim()
                );


            service.Credentials = credentials;

            EwsCertificateLoggingCallbackHelper oEwsCertificateLoggingCallbackHelper = new EwsCertificateLoggingCallbackHelper();
            EwsRedirectLoggingCallbackHelper    oEwsRedirectLoggingCallbackHelper    = new EwsRedirectLoggingCallbackHelper();


            //// Handle and Log redirects
            //service.RedirectionUrlValidationCallback = oEwsRedirectLoggingCallbackHelper.RedirectionUrlValidationCallbackAllowAnything;
            oEwsRedirectLoggingCallbackHelper.UseCredentials = this.GetWebWebRequestCredentials(
                this.chkDefaultWindowsCredentials.Checked,
                txtUser.Text.Trim(),
                txtPassword.Text.Trim(),
                txtDomain.Text.Trim()
                );

            // The following is used in the work-arouind for a redirect which involves an SMTP address change - it needs to be st to what you autodiscovering on.
            oEwsRedirectLoggingCallbackHelper.AutodiscoveringAddress       = txtTargetMailbox.Text.Trim();
            oEwsRedirectLoggingCallbackHelper._DoAddressRedirectWorkAround = chkWorkAroundAddressRedirectIssue.Checked;

            // Prevent the AutodiscoverService from looking in the local Active Directory for the Exchange Web Services Services SCP.
            service.EnableScpLookup = this.chkEnableScpLookup.Checked;
            service.PreAuthenticate = this.chkPreAuthenticate.Checked;

            if (bEnableInMemoryTracing == true)
            {
                oIML = new InMemoryListener();          // Enable for EWS tracing
                service.TraceFlags    = TraceFlags.All; // Enable for EWS tracing
                service.TraceEnabled  = true;           // Enable for EWS tracing
                service.TraceListener = oIML;           // Enable for EWS tracing
            }

            service.UserAgent = "AutodiscoverCheckerServiceObject";


            ServicePointManager.ServerCertificateValidationCallback = oEwsCertificateLoggingCallbackHelper.CertificateValidationCallBack;

            // oAutodiscoveryCallbackHelper..
            bool bFoundInfo = true;

            //string sResult = string.Empty;

            sResults += "! Trying to Autodiscover using: " + this.txtTargetMailbox.Text.Trim() + "\r\n";


            try
            {
                service.AutodiscoverUrl(
                    this.txtTargetMailbox.Text.Trim(),
                    oEwsRedirectLoggingCallbackHelper.RedirectionUrlValidationCallbackAllowAnything
                    );

                bFoundInfo = true;
            }
            catch (Exception ex1)
            {
                sResults  += "\r\n";
                sResults  += "!! Error trying to Autodiscover address.\r\n";
                sResults  += "    Address: " + this.txtTargetMailbox.Text.Trim() + "\r\n";
                sResults  += "       Error Message: " + ex1.Message + "\r\n";
                sResults  += "       Inner Error Message: " + ex1.Message + "\r\n";
                sResults  += "\r\n";
                sResults  += "       StackTrace: " + ex1.StackTrace + "\r\n";
                sResults  += "\r\n";
                bFoundInfo = false;
            }

            if (oEwsRedirectLoggingCallbackHelper._AddressRedirection == true)
            {
                try
                {
                    // Lets do Autodiscover again - but this time use the alternative address.
                    //string RedirectEmailAddress = oEwsRedirectLoggingCallbackHelper._RedirectEmailAddress;

                    string AutodiscoveringAddress = oEwsRedirectLoggingCallbackHelper._RedirectEmailAddress;
                    oEwsRedirectLoggingCallbackHelper.ResetRedirects();
                    oEwsRedirectLoggingCallbackHelper.AutodiscoveringAddress = AutodiscoveringAddress;


                    sResults += "! Rediretion Mail Address found (" + AutodiscoveringAddress + ")     * * * \r\n";
                    sResults += "  Autodiscover redirect address was found.  So, do autodiscover again with the new address.\r\n";
                    sResults += "  Starting new Autodiscover call for '" + AutodiscoveringAddress + "'.\r\n";
                    service.AutodiscoverUrl(
                        AutodiscoveringAddress,
                        oEwsRedirectLoggingCallbackHelper.RedirectionUrlValidationCallbackAllowAnything
                        );

                    bFoundInfo = true;
                }
                catch (Exception ex2)
                {
                    sResults  += "\r\n";
                    sResults  += "!! Error trying to Autodiscover redirect address.\r\n";
                    sResults  += "    Address: " + oEwsRedirectLoggingCallbackHelper._RedirectEmailAddress + "\r\n";
                    sResults  += "       Error Message: " + ex2.Message + "\r\n";
                    sResults  += "       Inner Error Message: " + ex2.Message + "\r\n";
                    sResults  += "\r\n";
                    sResults  += "       StackTrace: " + ex2.StackTrace + "\r\n";
                    sResults  += "\r\n";
                    bFoundInfo = false;
                }

                if (bFoundInfo == true)
                {
                    sResults += "\r\n[*****============================[Resolved URL]=====================================*****]\r\n\r\n";
                    sResults += "Server Url: " + service.Url + "\r\n";
                    sResults += "\r\n";
                }
            }

            txtResults.Text = sResults;


            txtCerts.Text    = oEwsCertificateLoggingCallbackHelper._Certificates;
            txtTracing.Text += "\r\n[*****============================[Redirects]=====================================*****]\r\n\r\n";

            txtTracing.Text += oEwsRedirectLoggingCallbackHelper._RedirectionUrls;

            if (bEnableInMemoryTracing == true)
            {
                txtTracing.Text += "\r\n[*****============================[Trace Log]=====================================*****]\r\n\r\n";
                txtTracing.Text += oIML.LogText;
            }

            sResults += "  * Ews URL: ";
            if (service.Url != null)
            {
                sResults += service.Url;
            }
            sResults += "\r\n";



            sResults       += "! Trying to Autodiscover using: " + this.txtTargetMailbox.Text.Trim() + "\r\n";
            sResults       += "\r\n";
            sResults       += "Note: See above fields for details.\r\n";
            txtResults.Text = sResults;

            service.TraceListener = null;
            oIML = null;                                // Enable for EWS tracing

            //service.RedirectionUrlValidationCallback = null;
            ServicePointManager.ServerCertificateValidationCallback = null;

            oEwsRedirectLoggingCallbackHelper    = null;
            oEwsCertificateLoggingCallbackHelper = null;

            this.Cursor = Cursors.Default;
        }
        private bool DoAutoDiscoverRaw(
            DiscoverType oDiscoverType,
            ref InMemoryListener oIML,
            string sEmail,
            NetworkCredential oNetworkCredential,
            int iMaxHops,
            bool bAllowSelfSignedCerts,
            bool bTraceCertificateInformation
            )
        {
            bool bRet = false;

            try
            {
                // Identifies the maximum number of redirections through either SCP pointer or Autodiscover redirects.

                AutodiscoverRaw oAutodiscoverRaw = new AutodiscoverRaw();
                AutodiscoverRaw.AutodiscoverResponseXml response = null;

                if (oDiscoverType == DiscoverType.Scp)
                {
                    // Call Autodiscover service.
                    response =
                        oAutodiscoverRaw.DiscoverScp(
                            ref oIML,
                            sEmail,
                            oNetworkCredential,
                            ref iMaxHops,
                            bAllowSelfSignedCerts,
                            bTraceCertificateInformation
                            );
                }

                if (oDiscoverType == DiscoverType.Pox)
                {
                    // Call Autodiscover service.
                    response =
                        oAutodiscoverRaw.DiscoverPox(
                            ref oIML,
                            sEmail,
                            oNetworkCredential,
                            ref iMaxHops,
                            bAllowSelfSignedCerts,
                            bTraceCertificateInformation
                            );
                }

                if (oDiscoverType == DiscoverType.Soap)
                {
                    // Call Autodiscover service.
                    //string sUrl = string.Empty;
                    response =
                        oAutodiscoverRaw.TryDiscoverSoap(
                            ref oIML,
                            sEmail,
                            oNetworkCredential,
                            ref iMaxHops,
                            bAllowSelfSignedCerts,
                            bTraceCertificateInformation
                            );
                    //if (sUrl == string.Empty)
                    //    response =  false;
                    //else
                    //    response = true;
                }

                // Write response to console.
                WriteResponse(response);

                bRet = true;
            }
            catch (System.Exception e)
            {
                oIML.WriteLine("Error: " + e.ToString());
                //MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //System.Console.WriteLine(e.ToString());
                bRet = false;
            }

            return(bRet);
        }