private void DoWork()
        {
            lastAutodiscoverResponse = null;

            AutodiscoverService autodiscoverService = new AutodiscoverService(ExchangeVersion.Exchange2013);

            if (this.verbose)
            {
                autodiscoverService.TraceEnabled = true;
                autodiscoverService.TraceFlags   = TraceFlags.All;
            }

            autodiscoverService.Url                   = new Uri(this.endpoint);
            autodiscoverService.Credentials           = new OAuthCredentials(this.token);
            autodiscoverService.UserAgent             = Constants.UserAgent;
            autodiscoverService.ClientRequestId       = Guid.NewGuid().ToString();
            autodiscoverService.ReturnClientRequestId = true;

            Console.WriteLine("Doing Autodiscover API call");
            Console.WriteLine("");

            lastAutodiscoverResponse = autodiscoverService.GetUserSettings(mailbox, UserSettingName.ExternalEwsUrl);

            Console.WriteLine("");
            Console.WriteLine("SUCCESS: Autodiscover API call");
            Console.WriteLine("");
        }
Example #2
0
        public static GetUserSettingsResponse GetUserSettings(
            AutodiscoverService service,
            string emailAddress,
            int maxHops,
            params UserSettingName[] settings)
        {
            Uri url = null;
            GetUserSettingsResponse response = null;

            for (int attempt = 0; attempt < maxHops; attempt++)
            {
                service.Url             = url;
                service.EnableScpLookup = (attempt < 2);

                response = service.GetUserSettings(emailAddress, settings);

                if (response.ErrorCode == AutodiscoverErrorCode.RedirectAddress)
                {
                    url = new Uri(response.RedirectTarget);
                }
                else if (response.ErrorCode == AutodiscoverErrorCode.RedirectUrl)
                {
                    url = new Uri(response.RedirectTarget);
                }
                else
                {
                    return(response);
                }
            }

            throw new Exception("No suitable Autodiscover endpoint was found.");
        }
Example #3
0
        public string GetDomainSettings( )
        //public string  GetDomainSettings(string sServerDomain, string sUser, string sPassword, string sDomain, ExchangeVersion oExchangeVersion)
        {
            // https://msdn.microsoft.com/en-us/library/office/jj900161(v=exchg.150).aspx


            string sRet = string.Empty;

            AutodiscoverService autodiscoverService = new AutodiscoverService("domain.contoso.com");

            autodiscoverService.Credentials = new NetworkCredential("User1", "password", "domain.contoso.com");

            // Submit a request and get the settings. The response contains only the
            // settings that are requested, if they exist.
            GetDomainSettingsResponse domainresponse = autodiscoverService.GetDomainSettings(
                "domain",
                ExchangeVersion.Exchange2013,
                DomainSettingName.ExternalEwsUrl,
                DomainSettingName.ExternalEwsVersion);

            // Display each retrieved value. The settings are part of a key/value pair.
            foreach (KeyValuePair <DomainSettingName, Object> domainsetting in domainresponse.Settings)
            {
                Console.WriteLine(domainsetting.Key.ToString() + ": " + domainsetting.Value.ToString());
            }


            // Console.WriteLine(domainresponse.Settings[DomainSettingName.ExternalEwsUrl]);

            return(sRet);
        }
        private void AutodiscoverViewerForm_Load(object sender, EventArgs e)
        {
            this.exchangeVersionCombo.TransformComboBox(this.TempExchangeVersionCombo);
            this.exchangeVersionCombo.HasEmptyItem = true;
            this.exchangeVersionCombo.Text         = "Exchange2013";
            //this.TempExchangeVersionCombo.Text = "Exchange2007_SP1";

            AutodiscoverService oTempService = new AutodiscoverService();

            cmboUserAgent.Items.Clear();
            cmboUserAgent.Items.Add(oTempService.UserAgent);
            UserAgentHelper.AddUserAgentsToComboBox(ref cmboUserAgent);
            cmboUserAgent.Text = oTempService.UserAgent;

            rdoUseAutoDiscover.Checked        = true;
            rdoUseUserSpecifiedUrl.Checked    = false;
            txtAutodiscoverServiceURL.Enabled = false;

            txtInfo.Text      = String.Empty;
            txtInfo.BackColor = System.Drawing.SystemColors.Control;

            SetFields();

            SetEnablementOptionalHeaders();
        }
Example #5
0
        /// <summary>
        /// Creates a new Notification subscription for the desired user and starts listening. Automatically assigns subscriptions to adequate CAS connections. Uses AutoDiscover to determine User's EWS Url.
        /// </summary>
        /// <param name="userMailAddress">The desired user's mail address. Used for AutoDiscover</param>
        /// <param name="folderIds">The Exchange folders under observation</param>
        /// <param name="eventTypes">Notifications will be received for these eventTypes</param>
        public void AddSubscription(MailAddress userMailAddress, IEnumerable <FolderId> folderIds, IEnumerable <EventType> eventTypes)
        {
            AutodiscoverService autodiscoverService = new AutodiscoverService(this._exchangeVersion);

            autodiscoverService.Credentials = this._credentials;
            autodiscoverService.RedirectionUrlValidationCallback = x => true;
            //only on o365!
            autodiscoverService.EnableScpLookup = false;

            var exchangeService = new ExchangeService(this._exchangeVersion)
            {
                Credentials = this._credentials
            };

            Debug.WriteLine("Autodiscover EWS Url for Subscription User...");
            //exchangeService.AutodiscoverUrl(userMailAddress.ToString(), x => true);

            var    response  = autodiscoverService.GetUserSettings(userMailAddress.ToString(), UserSettingName.GroupingInformation, UserSettingName.ExternalEwsUrl);
            string extUrl    = "";
            string groupInfo = "";

            response.TryGetSettingValue <string>(UserSettingName.ExternalEwsUrl, out extUrl);
            response.TryGetSettingValue <string>(UserSettingName.GroupingInformation, out groupInfo);

            var ewsUrl = new Uri(extUrl);

            exchangeService.Url = ewsUrl;
            var collection = FindOrCreateSubscriptionCollection(exchangeService, new GroupIdentifier(groupInfo, ewsUrl));

            collection.Add(userMailAddress.ToString(), folderIds, eventTypes.ToArray());
            if (_subscriptionCollections.Contains(collection) == false)
            {
                this._subscriptionCollections.Add(collection);
            }
        }
        private ExchangeService GetExchangeService(EmailCredentials credentials)
        {
            var url      = credentials.AccessEndPoint;
            var cacheKey = BuildCacheKey(credentials.Email);

            if (string.IsNullOrWhiteSpace(url))
            {
                url = _cacheRepository.Get <string>(cacheKey);
            }
            if (string.IsNullOrWhiteSpace(url))
            {
                var autodiscover = new AutodiscoverService(ExchangeVersion.Exchange2013_SP1)
                {
                    RedirectionUrlValidationCallback = x => true,
                    Credentials = new WebCredentials(credentials.Email, credentials.Password)
                };
                var userSettings = autodiscover.GetUsersSettings(new List <string>()
                {
                    credentials.Email
                }, UserSettingName.ExternalEwsUrl);

                var successResponse = userSettings.First(x => x.ErrorCode == AutodiscoverErrorCode.NoError);
                successResponse.TryGetSettingValue(UserSettingName.ExternalEwsUrl, out url);
                _cacheRepository.Put(cacheKey, url, new CacheRepositoryOptions());
            }
            var service =
                new ExchangeService(ExchangeVersion.Exchange2013_SP1)
            {
                Credentials = new WebCredentials(credentials.Email, credentials.Password),
                Url         = new Uri(url)
            };

            return(service);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GetUserSettingsRequest"/> class.
        /// </summary>
        /// <param name="service">Autodiscover service associated with this request.</param>
        /// <param name="url">URL of Autodiscover service.</param>
        /// <param name="expectPartnerToken"></param>
        internal GetUserSettingsRequest(AutodiscoverService service, Uri url, bool expectPartnerToken)
            : base(service, url)
        {
            this.expectPartnerToken = expectPartnerToken;

            // make an explicit https check.
            if (expectPartnerToken && !url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw new ServiceValidationException(Strings.HttpsIsRequired);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GetUserSettingsRequest"/> class.
        /// </summary>
        /// <param name="service">Autodiscover service associated with this request.</param>
        /// <param name="url">URL of Autodiscover service.</param>
        /// <param name="expectPartnerToken"></param>
        internal GetUserSettingsRequest(AutodiscoverService service, Uri url, bool expectPartnerToken)
            : base(service, url)
        {
            this.expectPartnerToken = expectPartnerToken;

            // make an explicit https check.
            if (expectPartnerToken && !url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw new ServiceValidationException(Strings.HttpsIsRequired);
            }
        }
Example #9
0
        public static void Run()
        {
            //ExStart: AutoDiscoverUsingEWS
            string email            = "*****@*****.**";
            string password         = "******";
            AutodiscoverService svc = new AutodiscoverService();

            svc.Credentials = new NetworkCredential(email, password);

            IDictionary <UserSettingName, object> userSettings = svc.GetUserSettings(email, UserSettingName.ExternalEwsUrl).Settings;
            string ewsUrl = (string)userSettings[UserSettingName.ExternalEwsUrl];

            Console.WriteLine("Auto discovered EWS Url: " + ewsUrl);
            //ExEnd: AutoDiscoverUsingEWS
        }
Example #10
0
        private void GoRun_Click(object sender, EventArgs e)
        {
            bool          bError = false;
            StringBuilder oSB    = new StringBuilder();

            AutodiscoverService autodiscoverService = new AutodiscoverService(TargetMailDomain.Text.Trim(), this.exchangeVersionCombo.SelectedItem.Value);

            autodiscoverService.UseDefaultCredentials = this.chkDefaultWindowsCredentials.Checked;

            if (this.chkDefaultWindowsCredentials.Checked == false)
            {
                if (txtUser.Text.Trim().Length != 0 || txtUser.Text.Trim().Length != 0)
                {
                    if (txtDomain.Text.Trim().Length == 0)
                    {
                        autodiscoverService.Credentials = new NetworkCredential(txtUser.Text.Trim(), txtPassword.Text.Trim());
                    }
                    else
                    {
                        autodiscoverService.Credentials = new NetworkCredential(txtUser.Text.Trim(), txtPassword.Text.Trim(), txtDomain.Text.Trim());
                    }
                }
                else
                {
                    MessageBox.Show("Uer ID and Password need to be set at a mimum.");
                }
            }

            if (bError == false)
            {
                // Submit a request and get the settings. The response contains only the
                // settings that are requested, if they exist.
                GetDomainSettingsResponse domainresponse = autodiscoverService.GetDomainSettings(
                    TargetMailDomain.Text.Trim(),
                    this.exchangeVersionCombo.SelectedItem.Value,
                    DomainSettingName.ExternalEwsUrl,
                    DomainSettingName.ExternalEwsVersion);

                // Display each retrieved value. The settings are part of a key value pair.
                foreach (KeyValuePair <DomainSettingName, Object> domainsetting in domainresponse.Settings)
                {
                    oSB.AppendLine(domainsetting.Key.ToString() + ": " + domainsetting.Value.ToString());
                }
            }

            txtResults.Text = oSB.ToString();
        }
        private void CreateAutodiscoverService()
        {
            _autodiscover = new AutodiscoverService(ExchangeVersion.Exchange2013);  // Minimum version we need is 2013

            _autodiscover.RedirectionUrlValidationCallback = RedirectionCallback;
            if (_traceListener != null)
            {
                _autodiscover.TraceListener = _traceListener;
                _autodiscover.TraceFlags    = TraceFlags.All;
                _autodiscover.TraceEnabled  = true;
            }
            if (CredentialHandler != null)
            {
                _credentialHandler = CredentialHandler;
                _credentialHandler.ApplyCredentialsToAutodiscoverService(_autodiscover);
            }
        }
Example #12
0
 public Mailboxes(WebCredentials AutodiscoverCredentials, ClassLogger Logger, ITraceListener TraceListener = null)
 {
     _logger       = Logger;
     _mailboxes    = new Dictionary <string, MailboxInfo>();
     _autodiscover = new AutodiscoverService(ExchangeVersion.Exchange2013);  // Minimum version we need is 2013
     _autodiscover.RedirectionUrlValidationCallback = RedirectionCallback;
     if (TraceListener != null)
     {
         _autodiscover.TraceListener = TraceListener;
         _autodiscover.TraceFlags    = TraceFlags.All;
         _autodiscover.TraceEnabled  = true;
     }
     if (!(AutodiscoverCredentials == null))
     {
         _autodiscover.Credentials = AutodiscoverCredentials;
     }
 }
Example #13
0
        static void Main(string[] args)
        {
            Console.Title           = "EWS Test Console";
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WindowHeight    = Console.LargestWindowHeight * 9 / 10;
            Console.WindowWidth     = Console.LargestWindowWidth / 2;
            Console.SetWindowPosition(0, 0);
            Console.SetBufferSize(200, 3000);

            // Create an AutodiscoverService object to provide user settings.
            AutodiscoverService autodiscover = new AutodiscoverService();

            // Get the email address and password from the console.
            IUserData userData = UserDataFromConsole.GetUserData();

            // Create credentials for the Autodiscover service.
            autodiscover.Credentials = new NetworkCredential(userData.EmailAddress, userData.Password);

            // Create an array that contains all the UserSettingName enumeration values.
            // Your application should only request the settings that it needs.
            UserSettingName[] allSettings = (UserSettingName[])Enum.GetValues(typeof(UserSettingName));


            // Get all the user setting values for the email address.
            Console.Write("Doing autodiscover lookup for " + userData.EmailAddress + "...");

            GetUserSettingsResponse response = GetUserSettings(autodiscover, userData.EmailAddress, 10, allSettings);

            Console.WriteLine(" complete.");
            Console.WriteLine();

            // Write the user setting values to the console.
            foreach (UserSettingName settingKey in response.Settings.Keys)
            {
                Console.WriteLine(string.Format("{0}: {1}", settingKey, response.Settings[settingKey]));
            }

            Console.WriteLine("\r\n");
            Console.WriteLine("Press or select Enter...");
            Console.ReadLine();
        }
 private string GetExchangeServerVersion(string domain)
 {
     AutodiscoverService adAutoDiscoverService = new AutodiscoverService(domain);
     adAutoDiscoverService.Credentials = new WebCredentials(username, password);
     adAutoDiscoverService.EnableScpLookup = true;
     adAutoDiscoverService.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
     adAutoDiscoverService.PreAuthenticate = true;
     adAutoDiscoverService.TraceEnabled = true;
     adAutoDiscoverService.KeepAlive = false;
     try
     {
         GetUserSettingsResponse adResponse = adAutoDiscoverService.GetUserSettings(username, (new UserSettingName[1] { UserSettingName.EwsSupportedSchemas }));
         string schema = adResponse.Settings[UserSettingName.EwsSupportedSchemas].ToString();
         return schema;
     }
     catch (Exception ex)
     {
         NotifyDownloadStatus(DownloadStatus.INFORM, "The username or password is incorrect. Please try again.");
     }
     return "";
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AutodiscoverDnsClient"/> class.
 /// </summary>
 /// <param name="service">The service.</param>
 internal AutodiscoverDnsClient(AutodiscoverService service)
 {
     this.service = service;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetUserSettingsRequest"/> class.
 /// </summary>
 /// <param name="service">Autodiscover service associated with this request.</param>
 /// <param name="url">URL of Autodiscover service.</param>
 internal GetUserSettingsRequest(AutodiscoverService service, Uri url)
     : this(service, url, false)
 {
 }
Example #17
0
        public void AutodiscoverGetUserSettings(AutodiscoverService service, string[] sUserSmtpAddresses)
        {
            string sRet = string.Empty;

            txtResults.Text = string.Empty;

            try
            {
                GetUserSettingsResponseCollection response = service.GetUsersSettings(
                    sUserSmtpAddresses.Select(addr => addr.Trim()).Where(addr => addr != ""),
                    System.Enum.GetValues(typeof(UserSettingName)) as UserSettingName[]);


                if (response.ErrorCode == AutodiscoverErrorCode.NoError)
                {
                    AutodiscoverResultForm.Show(this, response.Select(r => new AutodiscoverResultForm.AutodiscoverResult(r, service.Url)));
                }
                else
                {
                    sRet += "Response Error:\r\n\r\n";
                    sRet += "    AutodiscoverErrorCode : " + response.ErrorCode.ToString() + "\r\n";
                    sRet += "    Error Message:          " + response.ErrorMessage + "\r\n";
                }
            }
            catch (AutodiscoverLocalException oAutodiscoverLocalException)
            {
                sRet += "Caught AutodiscoverLocalException Exception:\r\n\r\n";
                sRet += "    Error Message: " + oAutodiscoverLocalException.Message + "\r\n";
                sRet += "    Inner Error Message: " + oAutodiscoverLocalException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + oAutodiscoverLocalException.StackTrace + "\r\n";
                sRet += "    See: " + oAutodiscoverLocalException.HelpLink + "\r\n";
            }

            catch (AutodiscoverRemoteException oAutodiscoverRemoteException)
            {
                sRet += "Caught AutodiscoverRemoteException Exception:\r\n\r\n";
                sRet += "    Error Message: " + oAutodiscoverRemoteException.Message + "\r\n";
                sRet += "    Inner Error Message: " + oAutodiscoverRemoteException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + oAutodiscoverRemoteException.StackTrace + "\r\n";
                sRet += "    See: " + oAutodiscoverRemoteException.HelpLink + "\r\n";
            }
            catch (AutodiscoverResponseException oAutodiscoverResponseException)
            {
                sRet += "Caught AutodiscoverResponseException Exception:\r\n\r\n";
                sRet += "    Error Message: " + oAutodiscoverResponseException.Message + "\r\n";
                sRet += "    Inner Error Message: " + oAutodiscoverResponseException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + oAutodiscoverResponseException.StackTrace + "\r\n";
                sRet += "    See: " + oAutodiscoverResponseException.HelpLink + "\r\n";
            }
            catch (ServerBusyException srBusyException)  // 2013+
            {
                Console.WriteLine(srBusyException);
                sRet += "Caught ServerBusyException Exception:\r\n\r\n";
                sRet += "    BackOffMilliseconds: " + srBusyException.BackOffMilliseconds.ToString() + "\r\n";
                sRet += "    Error Message: " + srBusyException.Message + "\r\n";
                sRet += "    Inner Error Message: " + srBusyException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + srBusyException.StackTrace + "\r\n";
                sRet += "    See: " + srBusyException.HelpLink + "\r\n";
            }
            catch (Exception ex)
            {
                sRet += "Caught Exception:\r\n\r\n";
                sRet += "    Error Message: " + ex.Message + "\r\n";
                sRet += "    Inner Error Message: " + ex.InnerException + "\r\n";
                sRet += "    Stack Trace: " + ex.StackTrace + "\r\n";
                sRet += "    See: " + ex.HelpLink + "\r\n";
            }

            txtResults.Text = sRet;
        }
Example #18
0
        public static ResultType SendAutodiscoverOAuthRequest(ADUser user, string orgDomain, Uri targetUri, out string diagnosticMessage, bool appOnly = false, bool useCachedToken = false, bool reloadConfig = false)
        {
            string domain = TestOAuthConnectivityHelper.GetDomain(user, orgDomain);

            if (domain == null)
            {
                diagnosticMessage = Strings.NullUserError;
                return(ResultType.Error);
            }
            ICredentials     icredentials     = TestOAuthConnectivityHelper.GetICredentials(appOnly, user, domain);
            OAuthCredentials oauthCredentials = icredentials as OAuthCredentials;

            if (icredentials == null)
            {
                diagnosticMessage = Strings.NullUserError;
                return(ResultType.Error);
            }
            StringBuilder             stringBuilder      = new StringBuilder();
            ValidationResultCollector resultCollector    = new ValidationResultCollector();
            LocalConfiguration        localConfiguration = LocalConfiguration.Load(resultCollector);

            oauthCredentials.Tracer             = new TestOAuthConnectivityHelper.TaskOauthOutboundTracer();
            oauthCredentials.LocalConfiguration = localConfiguration;
            Guid value = Guid.NewGuid();

            oauthCredentials.ClientRequestId = new Guid?(value);
            string value2 = TestOAuthConnectivityHelper.CheckReloadConfig(reloadConfig);
            string value3 = TestOAuthConnectivityHelper.CheckUseCachedToken(useCachedToken);

            stringBuilder.AppendLine(value2);
            stringBuilder.AppendLine(value3);
            AutodiscoverService autodiscoverService = new AutodiscoverService(4);

            autodiscoverService.Url          = new Uri(targetUri.Scheme + "://" + targetUri.Host + "/autodiscover/autodiscover.svc");
            autodiscoverService.TraceEnabled = true;
            autodiscoverService.Credentials  = new OAuthCredentials(oauthCredentials);
            ResultType result = ResultType.Success;

            try
            {
                string text = (user == null) ? ("@" + domain) : user.PrimarySmtpAddress.ToString();
                GetUserSettingsResponse userSettings = autodiscoverService.GetUserSettings(text, new UserSettingName[]
                {
                    58,
                    75
                });
                if (userSettings.ErrorCode != null && (userSettings.ErrorCode != 3 || !(text == "@" + domain)))
                {
                    result = ResultType.Error;
                }
            }
            catch (Exception ex)
            {
                stringBuilder.AppendLine(ex.ToString());
                result = ResultType.Error;
            }
            stringBuilder.AppendLine(Strings.TestOutboundOauthLog);
            stringBuilder.AppendLine(Strings.ClientRequestId(value.ToString()));
            stringBuilder.AppendLine(oauthCredentials.Tracer.ToString());
            stringBuilder.AppendLine(Strings.TestOAuthResponseDetails("Exchange"));
            stringBuilder.AppendLine(Strings.TestOutboundOauthLog);
            stringBuilder.AppendLine(Strings.TestOAuthResponseDetails("Autodiscover"));
            stringBuilder.AppendLine(oauthCredentials.Tracer.ToString());
            diagnosticMessage = stringBuilder.ToString();
            return(result);
        }
        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor     = Cursors.WaitCursor;
                txtResults.Text = string.Empty;
                txtResults.Update();


                txtInfo.Text = string.Empty;
                txtInfo.Update();



                // Create the AutodiscoverService object and set the request
                // ExchangeVersion if one was selected
                AutodiscoverService service = null;
                Uri oURI = null;

                if (this.rdoUseAutoDiscover.Checked == true)
                {
                    if (this.exchangeVersionCombo.SelectedItem.HasValue)
                    {
                        service = new AutodiscoverService(this.exchangeVersionCombo.SelectedItem.Value);
                    }
                    else
                    {
                        service = new AutodiscoverService();
                    }
                }
                else
                {
                    oURI = new Uri(this.txtAutodiscoverServiceURL.Text);
                    if (this.exchangeVersionCombo.SelectedItem.HasValue)
                    {
                        service = new AutodiscoverService(oURI, this.exchangeVersionCombo.SelectedItem.Value);
                    }
                    else
                    {
                        service = new AutodiscoverService(oURI);
                    }
                }

                // Set the AutodiscoverService credentials
                service.UseDefaultCredentials = this.chkDefaultWindowsCredentials.Checked;
                if (!service.UseDefaultCredentials)
                {
                    service.Credentials = new WebCredentials(txtUser.Text.Trim(), txtPassword.Text.Trim(), txtDomain.Text.Trim());
                }

                // Enable/Disable the SCP lookup against Active Directory
                service.EnableScpLookup = this.chkEnableScpLookup.Checked;

                service.ReturnClientRequestId = true;  // This will give us more data back about the servers used in the response headers

                // Enable/Disable pre-authenticating requests
                service.PreAuthenticate = this.chkPreAuthenticate.Checked;

                if (cmboUserAgent.Text.Trim().Length != 0)
                {
                    service.UserAgent = cmboUserAgent.Text.Trim();
                }

                if (chkOptHeader1.Checked == true)
                {
                    service.HttpHeaders.Add(txtHeader1Name.Text, txtHeader1Value.Text);
                }
                if (chkOptHeader2.Checked == true)
                {
                    service.HttpHeaders.Add(txtHeader2Name.Text, txtHeader2Value.Text);
                }
                if (chkOptHeader3.Checked == true)
                {
                    service.HttpHeaders.Add(txtHeader3Name.Text, txtHeader3Value.Text);
                }


                // Create and set the trace listener
                service.TraceEnabled = true;
                //service.TraceEnablePrettyPrinting = true;  // Hmmm not implemented in the 2.2 version of the manage api for the autodiscover object - it is for service
                service.TraceListener = new EwsTraceListener();

                System.Net.WebProxy oWebProxy = null;
                if (this.rdoSpecifyProxySettings.Checked == true)
                {
                    oWebProxy = new System.Net.WebProxy(this.txtProxyServerName.Text.Trim(), Convert.ToInt32(this.txtProxyServerPort.Text.Trim()));

                    service.WebProxy = oWebProxy;
                }

                // Allow/Disallow following 302 redirects in the Autodiscover sequence
                service.RedirectionUrlValidationCallback = ValidationCallbackHelper.RedirectionUrlValidationCallback;

                AutodiscoverGetUserSettings(ref service, this.TargetMailboxText.Text.Trim());

                txtInfo.Text = "Autodiscover URL used: " + service.Url;

                //GetUserSettingsResponse response = service.GetUserSettings(this.TargetMailboxText.Text, System.Enum.GetValues(typeof(UserSettingName)) as UserSettingName[]);
                //ErrorDialog.ShowInfo("Autodiscover completed successfully!  Check the EWSEditor Log Viewer for detailed output.");


                //ErrorDialog.ShowInfo(sResponse);
                this.Cursor = Cursors.Default;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        // Token: 0x0600059B RID: 1435 RVA: 0x0002B16C File Offset: 0x0002936C
        public static Uri DiscoverCloudArchiveEwsUrl(ADUser user)
        {
            Uri    result = null;
            string text   = null;
            string domain = user.ArchiveDomain.Domain;
            Uri    uri    = null;
            EndPointDiscoveryInfo endPointDiscoveryInfo;
            bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(OrganizationId.ForestWideOrgId, domain, null, null, null, out uri, out endPointDiscoveryInfo);

            if (endPointDiscoveryInfo != null && endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success)
            {
                ElcEwsClientHelper.Tracer.TraceDebug <SmtpAddress, EndPointDiscoveryInfo.DiscoveryStatus, string>(0L, "Getting autodiscover url for {0} encountered problem with status {1}. {2}", user.PrimarySmtpAddress, endPointDiscoveryInfo.Status, endPointDiscoveryInfo.Message);
            }
            if (!flag || uri == null)
            {
                ElcEwsClientHelper.Tracer.TraceError <SmtpAddress>(0L, "Failed to get autodiscover URL for {0}.", user.PrimarySmtpAddress);
                return(null);
            }
            SmtpAddress      archiveAddress = new SmtpAddress(SmtpProxyAddress.EncapsulateExchangeGuid(domain, user.ArchiveGuid));
            Guid             value          = Guid.NewGuid();
            OAuthCredentials oauthCredentialsForAppActAsToken = OAuthCredentials.GetOAuthCredentialsForAppActAsToken(OrganizationId.ForestWideOrgId, user, domain);

            oauthCredentialsForAppActAsToken.ClientRequestId = new Guid?(value);
            AutodiscoverService service = new AutodiscoverService(EwsWsSecurityUrl.FixForAnonymous(uri), 4)
            {
                Credentials     = new OAuthCredentials(oauthCredentialsForAppActAsToken),
                PreAuthenticate = true,
                UserAgent       = ElcEwsClientHelper.GetOAuthUserAgent("ElcAutoDiscoverClient")
            };

            service.ClientRequestId       = value.ToString();
            service.ReturnClientRequestId = true;
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ElcEwsClientHelper.CertificateErrorHandler));
                GetUserSettingsResponse response = null;
                Exception arg   = null;
                bool      flag2 = ElcEwsClientHelper.ExecuteEwsCall(delegate
                {
                    response = service.GetUserSettings(archiveAddress.ToString(), new UserSettingName[]
                    {
                        58
                    });
                }, out arg);
                if (flag2)
                {
                    if (response.ErrorCode == null)
                    {
                        if (!response.TryGetSettingValue <string>(58, ref text) || string.IsNullOrEmpty(text))
                        {
                            ElcEwsClientHelper.Tracer.TraceError <SmtpAddress, SmtpAddress>(0L, "Sucessfully called autodiscover, but did not retrieve a url for {0}/{1}.", user.PrimarySmtpAddress, archiveAddress);
                        }
                    }
                    else
                    {
                        ElcEwsClientHelper.Tracer.TraceError(0L, "Unable to autodiscover EWS endpoint for {0}/{1}, error code: {2}, message {3}.", new object[]
                        {
                            user.PrimarySmtpAddress,
                            archiveAddress,
                            response.ErrorCode,
                            response.ErrorMessage
                        });
                    }
                }
                else
                {
                    ElcEwsClientHelper.Tracer.TraceError <SmtpAddress, SmtpAddress, Exception>(0L, "Unable to autodiscover EWS endpoint for {0}/{1}, exception {2}.", user.PrimarySmtpAddress, archiveAddress, arg);
                }
            }
            finally
            {
                ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Remove(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ElcEwsClientHelper.CertificateErrorHandler));
            }
            if (!string.IsNullOrEmpty(text))
            {
                result = new Uri(text);
            }
            return(result);
        }
Example #21
0
        /// <summary>
        /// Creates a new Notification subscription for the desired user and starts listening. Automatically assigns subscriptions to adequate CAS connections. Uses AutoDiscover to determine User's EWS Url.
        /// </summary>
        /// <param name="userMailAddress">The desired user's mail address. Used for AutoDiscover</param>
        /// <param name="folderIds">The Exchange folders under observation</param>
        /// <param name="eventTypes">Notifications will be received for these eventTypes</param>
        public void AddSubscription(MailAddress userMailAddress, IEnumerable<FolderId> folderIds, IEnumerable<EventType> eventTypes)
        {
            AutodiscoverService autodiscoverService = new AutodiscoverService(this._exchangeVersion);
            autodiscoverService.Credentials = this._credentials;
            autodiscoverService.RedirectionUrlValidationCallback = x => true;
            //only on o365!
            autodiscoverService.EnableScpLookup = false;

            var exchangeService = new ExchangeService(this._exchangeVersion) { Credentials = this._credentials };

            Debug.WriteLine("Autodiscover EWS Url for Subscription User...");
            //exchangeService.AutodiscoverUrl(userMailAddress.ToString(), x => true);

            var response = autodiscoverService.GetUserSettings(userMailAddress.ToString(), UserSettingName.GroupingInformation, UserSettingName.ExternalEwsUrl);
            string extUrl = "";
            string groupInfo = "";
            response.TryGetSettingValue<string>(UserSettingName.ExternalEwsUrl, out extUrl);
            response.TryGetSettingValue<string>(UserSettingName.GroupingInformation, out groupInfo);

            var ewsUrl = new Uri(extUrl);
            exchangeService.Url = ewsUrl;
            var collection = FindOrCreateSubscriptionCollection(exchangeService, new GroupIdentifier(groupInfo, ewsUrl));
            collection.Add(userMailAddress.ToString(), folderIds, eventTypes.ToArray());
            if (_subscriptionCollections.Contains(collection) == false)
                this._subscriptionCollections.Add(collection);
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var                deviceId           = "";
            var                deviceSettings     = default(AutodiscoverResult);
            CameraStatus       cameraStatus       = CameraStatus.NotInstalled;
            GroveBaseHatStatus groveBaseHatStatus = GroveBaseHatStatus.NotInstalled;

            #region Set up device autodiscovery
            //keep autodiscovering until we get a connection string
            while (string.IsNullOrEmpty(deviceSettings?.ConnectionString) == true)
            {
                try
                {
                    deviceId       = DeviceIdService.GetDeviceId();
                    deviceSettings = AutodiscoverService.GetDeviceSettings(deviceId);

                    LoggingService.Log($"Device settings retrieved for DeviceId:{deviceId}");
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Autodiscovery failed", ex);
                    Thread.Sleep(30000);
                }
            }
            #endregion

            #region Set up IoT Hub Connection
            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(deviceSettings.ConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub connection failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Report device startup
            SendPayloadToIoTHub(new DeviceEvent()
            {
                ApplicationStarted = true
            });
            #endregion

            #region Retrieve device twin
            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device twin configuration retrieval failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Report device properties
            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device twin configuration retrieval failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Wire up device reboot command handler
            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device method handler configuration failed", ex);
                return;
            }
            #endregion

            #region Set up Grove Base Hat for RPI if installed
            if (deviceTwin.Properties.Desired.Contains("GroveBaseHatForRPIInstalled"))
            {
                groveBaseHatStatus = GroveBaseHatStatus.Installed;

                try
                {
                    if (deviceTwin.Properties.Desired["GroveBaseHatForRPIInstalled"].value == true)
                    {
                        GroveBaseHatAnalogPorts = new AnalogPorts();
                        GroveBaseHatAnalogPorts.Initialise();
                        LoggingService.Log($"Grove Base Hat for RPI Firmware version:{GroveBaseHatAnalogPorts.Version()}");

                        bme280Sensor = new BME280(0x76);

                        // Wire up the sensor update handler
                        azureIoTHubClient.SetMethodHandlerAsync("SensorUpdate", SensorUpdateAsync, deviceId);

                        // If the SensorUpdatePeriod greater than 0 start timer
                        int sensorUpdatePeriod = deviceTwin.Properties.Desired["SensorUpdatePeriod"].value;
                        LoggingService.Log($"Sensor update period:{sensorUpdatePeriod} seconds");
                        if (sensorUpdatePeriod > 0)
                        {
                            sensorUpdateTimer  = new Timer(SensorUpdateTimerCallback, deviceId, SensorUpdateDuePeriod, new TimeSpan(0, 0, sensorUpdatePeriod));
                            groveBaseHatStatus = GroveBaseHatStatus.Automatic;
                        }
                        else
                        {
                            groveBaseHatStatus = GroveBaseHatStatus.Enabled;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Grove Base Hat for RPI sensor configuration failed", ex);
                    return;
                }
            }
            SendPayloadToIoTHub(new DeviceStatus()
            {
                GroveBaseHatStatus = groveBaseHatStatus
            });
            #endregion

            #region Set up Camera if installed
            if (deviceTwin.Properties.Desired.Contains("CameraInstalled"))
            {
                cameraStatus = CameraStatus.Installed;

                try
                {
                    if (deviceTwin.Properties.Desired["CameraInstalled"].value == true)
                    {
                        mediaCapture = new MediaCapture();
                        mediaCapture.InitializeAsync().AsTask().Wait();

                        // Wire up the image update handler
                        azureIoTHubClient.SetMethodHandlerAsync("ImageUpdate", ImageUpdateAsync, deviceId);

                        // If the CameraUpdatePeriod greater than 0 start timer
                        int imageUpdatePeriod = deviceTwin.Properties.Desired["ImageUpdatePeriod"].value;
                        LoggingService.Log($"Image update period:{imageUpdatePeriod} seconds");
                        if (imageUpdatePeriod > 0)
                        {
                            ImageUpdatetimer = new Timer(ImageUpdateTimerCallback, deviceId, ImageUpdateDueDefault, new TimeSpan(0, 0, imageUpdatePeriod));
                            cameraStatus     = CameraStatus.Automatic;
                        }
                        else
                        {
                            cameraStatus = CameraStatus.Enabled;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Image capture configuration failed", ex);
                }
            }
            SendPayloadToIoTHub(new DeviceStatus()
            {
                CameraStatus = cameraStatus
            });
            #endregion

            //enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Example #23
0
 private string GetExchangeServerVersion(string domain, string email, string pass)
 {            
     try
     {
         AutodiscoverService adAutoDiscoverService = new AutodiscoverService();
         adAutoDiscoverService.Url = new Uri(" https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc");
         adAutoDiscoverService.Credentials = new NetworkCredential(email, pass);
         adAutoDiscoverService.EnableScpLookup = false;
         adAutoDiscoverService.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
         adAutoDiscoverService.PreAuthenticate = true;
         adAutoDiscoverService.TraceEnabled = true;
         adAutoDiscoverService.KeepAlive = false;
         GetUserSettingsResponse adResponse = adAutoDiscoverService.GetUserSettings(email, (new UserSettingName[1] { UserSettingName.EwsSupportedSchemas }));
         string schema = adResponse.Settings[UserSettingName.EwsSupportedSchemas].ToString();
         return schema;
     }
     catch (Exception ex)
     {
         Log(string.Format("GetExchangeServerVersion: {0}", ex.Message));
     }
     return "";
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetDomainSettingsRequest"/> class.
 /// </summary>
 /// <param name="service">Autodiscover service associated with this request.</param>
 /// <param name="url">URL of Autodiscover service.</param>
 internal GetDomainSettingsRequest(AutodiscoverService service, Uri url)
     : base(service, url)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AutodiscoverRequest"/> class.
 /// </summary>
 /// <param name="service">Autodiscover service associated with this request.</param>
 /// <param name="url">URL of Autodiscover service.</param>
 internal AutodiscoverRequest(AutodiscoverService service, Uri url)
 {
     this.service = service;
     this.url     = url;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AutodiscoverRequest"/> class.
 /// </summary>
 /// <param name="service">Autodiscover service associated with this request.</param>
 /// <param name="url">URL of Autodiscover service.</param>
 internal AutodiscoverRequest(AutodiscoverService service, Uri url)
 {
     this.service = service;
     this.url = url;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetUserSettingsRequest"/> class.
 /// </summary>
 /// <param name="service">Autodiscover service associated with this request.</param>
 /// <param name="url">URL of Autodiscover service.</param>
 internal GetUserSettingsRequest(AutodiscoverService service, Uri url)
     : this(service, url, false)
 {
 }
        public string AutodiscoverGetUserSettings(ref AutodiscoverService service, string sUserSmtpAddress)
        {
            string sRet = string.Empty;
            GetUserSettingsResponse oResponse = null;
            bool bWasError = false;


            sRet += "+ Calling GetUserSettings for " + sUserSmtpAddress + " - " + DateTime.Now + "\r\n";
            sRet += "\r\n";
            switch (_Version)
            {
            case ExchangeVersion.Exchange2007_SP1:
                try
                {
                    oResponse = service.GetUserSettings(
                        sUserSmtpAddress,
                        UserSettingName.ActiveDirectoryServer,
                        UserSettingName.AlternateMailboxes,
                        UserSettingName.CasVersion,
                        UserSettingName.CrossOrganizationSharingEnabled,
                        UserSettingName.EcpDeliveryReportUrlFragment,
                        UserSettingName.EcpEmailSubscriptionsUrlFragment,
                        UserSettingName.EcpTextMessagingUrlFragment,
                        UserSettingName.EcpVoicemailUrlFragment,
                        UserSettingName.EwsSupportedSchemas,
                        UserSettingName.ExternalEcpDeliveryReportUrl,
                        UserSettingName.ExternalEcpEmailSubscriptionsUrl,
                        UserSettingName.ExternalEcpTextMessagingUrl,
                        UserSettingName.ExternalEcpUrl,
                        UserSettingName.ExternalEcpVoicemailUrl,
                        UserSettingName.ExternalEwsUrl,
                        UserSettingName.ExternalImap4Connections,
                        UserSettingName.ExternalMailboxServer,
                        UserSettingName.ExternalMailboxServerAuthenticationMethods,
                        UserSettingName.ExternalMailboxServerRequiresSSL,
                        UserSettingName.ExternalOABUrl,
                        UserSettingName.ExternalPop3Connections,
                        UserSettingName.ExternalSmtpConnections,
                        UserSettingName.ExternalUMUrl,
                        UserSettingName.ExternalWebClientUrls,
                        UserSettingName.InternalEcpDeliveryReportUrl,
                        UserSettingName.InternalEcpEmailSubscriptionsUrl,
                        UserSettingName.InternalEcpTextMessagingUrl,
                        UserSettingName.InternalEcpUrl,
                        UserSettingName.InternalEcpVoicemailUrl,
                        UserSettingName.InternalEwsUrl,
                        UserSettingName.InternalImap4Connections,
                        UserSettingName.InternalMailboxServer,
                        UserSettingName.InternalMailboxServerDN,
                        UserSettingName.InternalOABUrl,
                        UserSettingName.InternalPop3Connections,
                        UserSettingName.InternalRpcClientServer,
                        UserSettingName.InternalSmtpConnections,
                        UserSettingName.InternalUMUrl,
                        UserSettingName.InternalWebClientUrls,
                        UserSettingName.MailboxDN,
                        UserSettingName.PublicFolderServer,
                        UserSettingName.UserDeploymentId,
                        UserSettingName.UserDisplayName,
                        UserSettingName.UserDN,
                        UserSettingName.MobileMailboxPolicy,
                        UserSettingName.ExternalEwsVersion,
                        UserSettingName.ExchangeRpcUrl

                        );
                }
                catch (Exception ex)
                {
                    sRet     += "\r\n";
                    sRet     += "!! Error: \r\n";
                    sRet     += "    Message: " + ex.Message + "\r\n";
                    sRet     += "    InnerException: " + ex.InnerException + "\r\n";
                    sRet     += "\r\n";
                    sRet     += "    StackTrace: " + ex.StackTrace + "\r\n";
                    sRet     += "\r\n";
                    bWasError = true;
                }
                break;

            case ExchangeVersion.Exchange2010:
                try
                {
                    oResponse = service.GetUserSettings(
                        sUserSmtpAddress,
                        UserSettingName.ActiveDirectoryServer,
                        UserSettingName.AlternateMailboxes,
                        UserSettingName.CasVersion,
                        UserSettingName.EwsSupportedSchemas,
                        UserSettingName.ExternalMailboxServer,
                        UserSettingName.ExternalMailboxServerAuthenticationMethods,
                        UserSettingName.ExternalMailboxServerRequiresSSL,

                        UserSettingName.ExternalEwsUrl,
                        UserSettingName.ExternalPop3Connections,
                        UserSettingName.ExternalSmtpConnections,

                        UserSettingName.ExternalWebClientUrls,
                        UserSettingName.InternalEwsUrl,
                        UserSettingName.InternalMailboxServer,
                        UserSettingName.InternalMailboxServerDN,
                        UserSettingName.InternalWebClientUrls,
                        UserSettingName.MailboxDN,
                        UserSettingName.PublicFolderServer,
                        UserSettingName.UserDeploymentId,
                        UserSettingName.UserDisplayName,
                        UserSettingName.UserDN,
                        UserSettingName.MobileMailboxPolicy,
                        UserSettingName.ExternalEwsVersion,
                        UserSettingName.ExchangeRpcUrl


                        );
                }
                catch (Exception ex)
                {
                    sRet     += "\r\n";
                    sRet     += "!! Error: \r\n";
                    sRet     += "    Message: " + ex.Message + "\r\n";
                    sRet     += "    InnerException: " + ex.InnerException + "\r\n";
                    sRet     += "\r\n";
                    sRet     += "    StackTrace: " + ex.StackTrace + "\r\n";
                    sRet     += "\r\n";
                    bWasError = true;
                }
                break;

            case ExchangeVersion.Exchange2010_SP1:
                try
                {
                    oResponse = service.GetUserSettings(
                        sUserSmtpAddress,
                        UserSettingName.ActiveDirectoryServer,
                        UserSettingName.AlternateMailboxes,
                        UserSettingName.CasVersion,
                        UserSettingName.EwsSupportedSchemas,
                        UserSettingName.ExternalMailboxServer,
                        UserSettingName.ExternalMailboxServerAuthenticationMethods,
                        UserSettingName.ExternalMailboxServerRequiresSSL,

                        UserSettingName.ExternalEwsUrl,
                        UserSettingName.ExternalPop3Connections,
                        UserSettingName.ExternalSmtpConnections,

                        UserSettingName.ExternalWebClientUrls,
                        UserSettingName.InternalEwsUrl,
                        UserSettingName.InternalMailboxServer,
                        UserSettingName.InternalMailboxServerDN,
                        UserSettingName.InternalWebClientUrls,
                        UserSettingName.MailboxDN,
                        UserSettingName.PublicFolderServer,
                        UserSettingName.UserDeploymentId,
                        UserSettingName.UserDisplayName,
                        UserSettingName.UserDN,
                        UserSettingName.MobileMailboxPolicy,
                        UserSettingName.ExternalEwsVersion,
                        UserSettingName.ExchangeRpcUrl
                        );
                }
                catch (Exception ex)
                {
                    sRet     += "\r\n";
                    sRet     += "!! Error: \r\n";
                    sRet     += "    Message: " + ex.Message + "\r\n";
                    sRet     += "    InnerException: " + ex.InnerException + "\r\n";
                    sRet     += "\r\n";
                    sRet     += "    StackTrace: " + ex.StackTrace + "\r\n";
                    sRet     += "\r\n";
                    bWasError = true;
                }
                break;

            case ExchangeVersion.Exchange2010_SP2:
                try
                {
                    oResponse = service.GetUserSettings(
                        sUserSmtpAddress,
                        UserSettingName.ActiveDirectoryServer,
                        UserSettingName.AlternateMailboxes,
                        UserSettingName.CasVersion,
                        UserSettingName.EwsSupportedSchemas,
                        UserSettingName.ExternalMailboxServer,
                        UserSettingName.ExternalMailboxServerAuthenticationMethods,
                        UserSettingName.ExternalMailboxServerRequiresSSL,

                        UserSettingName.ExternalEwsUrl,
                        UserSettingName.ExternalPop3Connections,
                        UserSettingName.ExternalSmtpConnections,

                        UserSettingName.ExternalWebClientUrls,
                        UserSettingName.InternalEwsUrl,
                        UserSettingName.InternalMailboxServer,
                        UserSettingName.InternalMailboxServerDN,
                        UserSettingName.InternalWebClientUrls,
                        UserSettingName.MailboxDN,
                        UserSettingName.PublicFolderServer,
                        UserSettingName.UserDeploymentId,
                        UserSettingName.UserDisplayName,
                        UserSettingName.UserDN,
                        UserSettingName.MobileMailboxPolicy,
                        UserSettingName.ExternalEwsVersion,
                        UserSettingName.ExchangeRpcUrl
                        );
                }
                catch (Exception ex)
                {
                    sRet     += "\r\n";
                    sRet     += "!! Error: \r\n";
                    sRet     += "    Message: " + ex.Message + "\r\n";
                    sRet     += "    InnerException: " + ex.InnerException + "\r\n";
                    sRet     += "\r\n";
                    sRet     += "    StackTrace: " + ex.StackTrace + "\r\n";
                    sRet     += "\r\n";
                    bWasError = true;
                }
                break;

            case ExchangeVersion.Exchange2013:
                try
                {
                    oResponse = service.GetUserSettings(
                        sUserSmtpAddress,
                        UserSettingName.ActiveDirectoryServer,
                        UserSettingName.AlternateMailboxes,
                        UserSettingName.CasVersion,
                        UserSettingName.EwsSupportedSchemas,
                        UserSettingName.ExternalMailboxServer,
                        UserSettingName.ExternalMailboxServerAuthenticationMethods,
                        UserSettingName.ExternalMailboxServerRequiresSSL,

                        UserSettingName.ExternalEwsUrl,
                        UserSettingName.ExternalPop3Connections,
                        UserSettingName.ExternalSmtpConnections,

                        UserSettingName.ExternalWebClientUrls,
                        UserSettingName.InternalEwsUrl,
                        UserSettingName.InternalMailboxServer,
                        UserSettingName.InternalMailboxServerDN,
                        UserSettingName.InternalWebClientUrls,
                        UserSettingName.MailboxDN,
                        UserSettingName.PublicFolderServer,
                        UserSettingName.UserDeploymentId,
                        UserSettingName.UserDisplayName,
                        UserSettingName.UserDN,
                        UserSettingName.MobileMailboxPolicy,
                        UserSettingName.ExternalEwsVersion,
                        UserSettingName.ExchangeRpcUrl
                        );
                }
                catch (Exception ex)
                {
                    sRet += "\r\n";

                    sRet     += "!! Error: \r\n";
                    sRet     += "    Message: " + ex.Message + "\r\n";
                    sRet     += "    InnerException: " + ex.InnerException + "\r\n";
                    sRet     += "\r\n";
                    sRet     += "    StackTrace: " + ex.StackTrace + "\r\n";
                    sRet     += "\r\n";
                    bWasError = true;
                }
                break;
            }

            if (bWasError == false)
            {
                try
                {
                    string sLine = string.Empty;

                    // Display each retrieved value. The settings are part of a key value pair.
                    string sValue = string.Empty;
                    string sType  = string.Empty;
                    foreach (KeyValuePair <UserSettingName, Object> usersetting in oResponse.Settings)
                    {
                        sValue = string.Empty;

                        sLine = string.Format("{0}:\r\n", usersetting.Key.ToString());

                        sType = usersetting.Value.ToString();
                        switch (sType)
                        {
                        case ("Microsoft.Exchange.WebServices.Autodiscover.WebClientUrlCollection"):
                            Microsoft.Exchange.WebServices.Autodiscover.WebClientUrlCollection oCollection1;
                            oCollection1 = (Microsoft.Exchange.WebServices.Autodiscover.WebClientUrlCollection)usersetting.Value;
                            foreach (WebClientUrl oUrl in oCollection1.Urls)
                            {
                                sValue += string.Format("    Url: {0} - Authentication: {1}\r\n", oUrl.Url, oUrl.AuthenticationMethods);
                            }
                            break;

                        case ("Microsoft.Exchange.WebServices.Autodiscover.ProtocolConnectionCollection"):
                            Microsoft.Exchange.WebServices.Autodiscover.ProtocolConnectionCollection oCollection2;
                            oCollection2 = (Microsoft.Exchange.WebServices.Autodiscover.ProtocolConnectionCollection)usersetting.Value;
                            foreach (ProtocolConnection oProtocolConnection in oCollection2.Connections)
                            {
                                sValue += string.Format("    Hostname: {0} - Port: {1} - EncryptionMethod: {2}\r\n", oProtocolConnection.Hostname, oProtocolConnection.Port, oProtocolConnection.EncryptionMethod);
                            }

                            break;

                        default:
                            sValue = string.Format("    {0}\r\n", usersetting.Value.ToString());
                            break;
                        }
                        sLine += sValue;
                        //sLine = string.Format("{0}:\r\n    {1}", usersetting.Key.ToString(), sValue);

                        sRet += sLine;
                    }

                    sRet += "\r\n";
                    sRet += "+ Response Information\r\n";
                    sRet += "    Response Redirect Target: " + oResponse.RedirectTarget + "\r\n";
                    sRet += "    Response Errors: \r\n";
                    sRet += "       ErrorCode: " + oResponse.ErrorCode + "\r\n";
                    sRet += "       ErrorMessage: " + oResponse.ErrorMessage + "\r\n";
                    if (oResponse.UserSettingErrors.Count > 0)
                    {
                        sRet += "       Per user setting errors:  \r\n";

                        foreach (UserSettingError oError in oResponse.UserSettingErrors)
                        {
                            sRet += "         Setting: " + oError.SettingName + "\r\n";
                            sRet += "           ErrorCode: " + oError.ErrorCode + "\r\n";
                            sRet += "           ErrorMessage: " + oError.ErrorMessage + "\r\n";
                            sRet += "\r\n";
                        }
                    }
                    sRet += "- Response Information\r\n";
                }
                catch (Exception ex)
                {
                    sRet += "\r\n";
                    sRet += "!! Error: \r\n";
                    sRet += "    Message: " + ex.Message + "\r\n";
                    sRet += "    InnerException: " + ex.InnerException + "\r\n";
                    sRet += "\r\n";
                    sRet += "    StackTrace: " + ex.StackTrace + "\r\n";
                    sRet += "\r\n";
                }
            }
            sRet += "\r\n";
            sRet += "- Calling GetUserSettings for " + sUserSmtpAddress + " - " + DateTime.Now + "\r\n";

            return(sRet);
        }
Example #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AutodiscoverDnsClient"/> class.
 /// </summary>
 /// <param name="service">The service.</param>
 internal AutodiscoverDnsClient(AutodiscoverService service)
 {
     this.service = service;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetDomainSettingsRequest"/> class.
 /// </summary>
 /// <param name="service">Autodiscover service associated with this request.</param>
 /// <param name="url">URL of Autodiscover service.</param>
 internal GetDomainSettingsRequest(AutodiscoverService service, Uri url)
     : base(service, url)
 {
 }
 private string GetExchangeServerVersion()
 {
     AutodiscoverService adAutoDiscoverService = new AutodiscoverService();
     adAutoDiscoverService.Credentials = new WebCredentials(username, password);
     adAutoDiscoverService.EnableScpLookup = true;
     adAutoDiscoverService.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
     adAutoDiscoverService.PreAuthenticate = true;
     adAutoDiscoverService.TraceEnabled = true;
     adAutoDiscoverService.KeepAlive = false;
     try
     {
         GetUserSettingsResponse adResponse = adAutoDiscoverService.GetUserSettings(username, (new UserSettingName[1] { UserSettingName.EwsSupportedSchemas }));
         string schema = adResponse.Settings[UserSettingName.EwsSupportedSchemas].ToString();
         return schema;
     }
     catch (Exception ex)
     {
         return "";
     }
 }
Example #32
0
        public static int Send(string subject, string body)
        {
            string logFile      = "errLog.txt";
            string errorSection = "Read Console Arguments";

            try
            {
                /*
                 * string sender = args[0];
                 * string user = args[1];
                 * string pass = args[2];
                 * string msg = args[3];
                 * if (args.Length > 4)
                 *  logFile = args[4];//*/
                sender       = System.DirectoryServices.AccountManagement.UserPrincipal.Current.EmailAddress;
                errorSection = "Validate Certificate";
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

                string domain             = sender.Substring(sender.IndexOf('@') + 1);
                AutodiscoverService adSrv = new AutodiscoverService(domain);

                ExchangeService service = new ExchangeService(adSrv.RequestedServerVersion);

                // For debug only!!!!
                //service.TraceEnabled = true;
                service.TraceFlags = TraceFlags.All;
                // ------------------ end of debug

                errorSection = "Create Credentials";

                //WebCredentials Cred = new WebCredentials(user, pass);
                //service.Credentials = Cred;
                service.UseDefaultCredentials = true;

                errorSection = "Autodiscover URL";
                //String [] byPassList = null;
                //service.WebProxy = new WebProxy("https://webmailext.phoenixgroup.eu");
                //service.Url = new Uri("https://webmailext.phoenixgroup.eu/");
                //service.Url = new Uri("DENU1XMAIL02.phoenix.loc", UriKind.Relative);
                service.AutodiscoverUrl(sender, RedirectionUrlValidationCallback);

                //service.Url = new Uri("https://webmail.phoenixgroup.eu/EWS/Exchange.asmx");
                //service.Url = new Uri("https://denu1xcasint.phoenix.loc/EWS/Exchange.asmx"); // old exchange server
                //service.Url = new Uri("https://denu02ms0015.phoenix.loc/EWS/Exchange.asmx"); // new server

                //Console.WriteLine("service.Url="+service.Url.ToString());

                EmailMessage email = new EmailMessage(service);

                errorSection = "Read message file";
                MessageBody msgBody = new MessageBody();
                msgBody.BodyType = BodyType.HTML;
                msgBody.Text     = body.Replace("\r\n", "<br />");
                email.Subject    = subject;
                email.ToRecipients.Add(receiver);
                email.Body = msgBody;

                errorSection = "Send message";
                email.Send();
            }
            catch (Exception e)
            {
                if (!File.Exists(logFile))
                {
                    using (StreamWriter writer = File.CreateText(logFile))
                    {
                        writer.WriteLine(DateTime.Now.ToString("dd.MM.yy HH:mm:ss") + "   " + errorSection);
                        writer.WriteLine("Error: " + e.Message);
                    }
                }
                else
                {
                    StreamWriter writer = new StreamWriter(logFile, true);
                    using (writer)
                    {
                        writer.WriteLine(DateTime.Now.ToString("dd.MM.yy HH:mm:ss") + "   " + errorSection);
                        writer.WriteLine("Error: " + e.Message);
                    }
                }

                return(1);
            }
            return(0);
        }
        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;
        }
 // Token: 0x06000170 RID: 368 RVA: 0x00009C70 File Offset: 0x00007E70
 internal void Synchronize(object argument)
 {
     try
     {
         ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(CertificateValidation.CertificateErrorHandler));
         Guid b = (Guid)argument;
         SearchEventLogger.Instance.LogSyncDiscoveryHoldToExchangeOnlineStartEvent(b.ToString());
         DiscoverySearchDataProvider discoverySearchDataProvider = new DiscoverySearchDataProvider(OrganizationId.ForestWideOrgId);
         if (discoverySearchDataProvider.ObjectGuid == b)
         {
             Dictionary <string, MailboxDiscoverySearch> dictionary = new Dictionary <string, MailboxDiscoverySearch>();
             SmtpAddress discoveryHolds = DiscoveryHoldSynchronizer.GetDiscoveryHolds(discoverySearchDataProvider, dictionary);
             SearchEventLogger.Instance.LogSyncDiscoveryHoldToExchangeOnlineDetailsEvent(dictionary.Count, discoveryHolds.ToString());
             if (discoveryHolds != SmtpAddress.Empty)
             {
                 Uri    uri = null;
                 string str = string.Empty;
                 EndPointDiscoveryInfo endPointDiscoveryInfo;
                 bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(OrganizationId.ForestWideOrgId, discoveryHolds.Domain, null, null, null, out uri, out endPointDiscoveryInfo);
                 if (endPointDiscoveryInfo != null && endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success)
                 {
                     str = endPointDiscoveryInfo.Message;
                     DiscoveryHoldSynchronizer.Tracer.TraceDebug <EndPointDiscoveryInfo.DiscoveryStatus, string>((long)this.GetHashCode(), "Getting autodiscover url encountered problem with status {0}. {1}", endPointDiscoveryInfo.Status, endPointDiscoveryInfo.Message);
                 }
                 if (flag && uri != null)
                 {
                     uri = EwsWsSecurityUrl.FixForAnonymous(uri);
                     AutodiscoverService autodiscoverService = new AutodiscoverService(uri, 4);
                     OAuthCredentials    credentials         = new OAuthCredentials(OAuthCredentials.GetOAuthCredentialsForAppToken(OrganizationId.ForestWideOrgId, discoveryHolds.Domain));
                     autodiscoverService.Credentials = credentials;
                     GetUserSettingsResponse userSettings = autodiscoverService.GetUserSettings(discoveryHolds.ToString(), new UserSettingName[]
                     {
                         58
                     });
                     if (userSettings != null && userSettings.ErrorCode == null && userSettings.Settings != null && userSettings.Settings.ContainsKey(58))
                     {
                         string          uriString       = userSettings.Settings[58].ToString();
                         ExchangeService exchangeService = new ExchangeService(4);
                         exchangeService.Credentials     = credentials;
                         exchangeService.Url             = new Uri(uriString);
                         exchangeService.ManagementRoles = new ManagementRoles(null, "LegalHoldApplication");
                         GetDiscoverySearchConfigurationResponse discoverySearchConfiguration = exchangeService.GetDiscoverySearchConfiguration(null, false, true);
                         if (discoverySearchConfiguration.Result == 2)
                         {
                             SearchEventLogger.Instance.LogFailedToSyncDiscoveryHoldToExchangeOnlineEvent(string.Format("ErrorCode={0}&ErrorMessage={1}", discoverySearchConfiguration.ErrorCode, discoverySearchConfiguration.ErrorMessage));
                             goto IL_402;
                         }
                         foreach (DiscoverySearchConfiguration discoverySearchConfiguration2 in discoverySearchConfiguration.DiscoverySearchConfigurations)
                         {
                             MailboxDiscoverySearch mailboxDiscoverySearch = null;
                             if (dictionary.TryGetValue(discoverySearchConfiguration2.InPlaceHoldIdentity, out mailboxDiscoverySearch))
                             {
                                 if (mailboxDiscoverySearch.Name != discoverySearchConfiguration2.SearchId)
                                 {
                                     if (DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, discoverySearchConfiguration2.SearchId, 2, discoverySearchConfiguration2.SearchQuery, discoverySearchConfiguration2.InPlaceHoldIdentity, null))
                                     {
                                         DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, mailboxDiscoverySearch.Name, 0, mailboxDiscoverySearch.CalculatedQuery, mailboxDiscoverySearch.InPlaceHoldIdentity, mailboxDiscoverySearch.ItemHoldPeriod.ToString());
                                     }
                                 }
                                 else
                                 {
                                     DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, mailboxDiscoverySearch.Name, 1, mailboxDiscoverySearch.CalculatedQuery, mailboxDiscoverySearch.InPlaceHoldIdentity, mailboxDiscoverySearch.ItemHoldPeriod.ToString());
                                 }
                                 dictionary.Remove(discoverySearchConfiguration2.InPlaceHoldIdentity);
                             }
                             else if (discoverySearchConfiguration2.ManagedByOrganization == "b5d6efcd-1aee-42b9-b168-6fef285fe613")
                             {
                                 DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, discoverySearchConfiguration2.SearchId, 2, discoverySearchConfiguration2.SearchQuery, discoverySearchConfiguration2.InPlaceHoldIdentity, null);
                             }
                         }
                         using (Dictionary <string, MailboxDiscoverySearch> .ValueCollection.Enumerator enumerator = dictionary.Values.GetEnumerator())
                         {
                             while (enumerator.MoveNext())
                             {
                                 MailboxDiscoverySearch mailboxDiscoverySearch2 = enumerator.Current;
                                 DiscoveryHoldSynchronizer.CallSetHoldOnMailboxes(exchangeService, mailboxDiscoverySearch2.Name, 0, mailboxDiscoverySearch2.CalculatedQuery, mailboxDiscoverySearch2.InPlaceHoldIdentity, mailboxDiscoverySearch2.ItemHoldPeriod.ToString());
                             }
                             goto IL_402;
                         }
                     }
                     string str2 = string.Empty;
                     if (userSettings != null && userSettings.ErrorCode != null)
                     {
                         str2 = string.Format("ErrorCode={0}&ErrorMessage={1}", userSettings.ErrorCode, userSettings.ErrorMessage);
                     }
                     SearchEventLogger.Instance.LogFailedToSyncDiscoveryHoldToExchangeOnlineEvent("Failed to get autodiscover settings. " + str2);
                 }
                 else
                 {
                     SearchEventLogger.Instance.LogFailedToSyncDiscoveryHoldToExchangeOnlineEvent("Failed to get autodiscover URL. " + str);
                 }
             }
         }
         IL_402 :;
     }
     finally
     {
         ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Remove(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(CertificateValidation.CertificateErrorHandler));
     }
 }
        public void AutodiscoverGetUserSettings(ref AutodiscoverService service, string sUserSmtpAddress)
        {
            string sRet = string.Empty;

            lvItems.Items.Clear();
            txtResults.Text = string.Empty;

            try
            {
                GetUserSettingsResponse response = service.GetUserSettings(
                    sUserSmtpAddress,
                    System.Enum.GetValues(typeof(UserSettingName)) as UserSettingName[]);


                if (response.ErrorCode == AutodiscoverErrorCode.NoError)
                {
                    string sLine = string.Empty;
                    sLine += "Finished.  \r\n";
                    sLine += "Response Redirect Target: " + response.RedirectTarget + "\r\n";
                    sLine += "\r\n";

                    // Display each retrieved value. The settings are part of a key value pair.
                    string sValue     = string.Empty;
                    string sType      = string.Empty;
                    int    ValueCount = 0;
                    foreach (KeyValuePair <UserSettingName, Object> usersetting in response.Settings)
                    {
                        sValue = string.Empty;

                        ValueCount = 0;
                        sType      = usersetting.Value.ToString();
                        switch (sType)
                        {
                        case ("Microsoft.Exchange.WebServices.Autodiscover.WebClientUrlCollection"):
                            Microsoft.Exchange.WebServices.Autodiscover.WebClientUrlCollection oCollection1;
                            oCollection1 = (Microsoft.Exchange.WebServices.Autodiscover.WebClientUrlCollection)usersetting.Value;
                            foreach (WebClientUrl oUrl in oCollection1.Urls)
                            {
                                sValue += string.Format("Url: {0} \r\n" +
                                                        "Authentication: {1}\r\n",
                                                        oUrl.Url,
                                                        oUrl.AuthenticationMethods);
                                ValueCount++;
                            }
                            break;

                        case ("Microsoft.Exchange.WebServices.Autodiscover.ProtocolConnectionCollection"):
                            Microsoft.Exchange.WebServices.Autodiscover.ProtocolConnectionCollection oCollection2;
                            oCollection2 = (Microsoft.Exchange.WebServices.Autodiscover.ProtocolConnectionCollection)usersetting.Value;
                            foreach (ProtocolConnection oProtocolConnection in oCollection2.Connections)
                            {
                                sValue += string.Format("Hostname: {0} \r\n" +
                                                        "Port: {1}\r\n" +
                                                        "EncryptionMethod: {2}\r\n",
                                                        oProtocolConnection.Hostname,
                                                        oProtocolConnection.Port,
                                                        oProtocolConnection.EncryptionMethod);
                                ValueCount++;
                            }
                            break;

                        case ("Microsoft.Exchange.WebServices.Autodiscover.AlternateMailboxCollection"):
                            Microsoft.Exchange.WebServices.Autodiscover.AlternateMailboxCollection oCollection3;
                            oCollection3 = (Microsoft.Exchange.WebServices.Autodiscover.AlternateMailboxCollection)usersetting.Value;
                            foreach (AlternateMailbox oAlternativeMailbox in oCollection3.Entries)
                            {
                                sValue += string.Format(
                                    "Type: {0} \r\n" +
                                    "DisplayName: {1} \r\n" +
                                    "LegacyDN: {2} \r\n" +
                                    "Server: {3} \r\n" +
                                    "SmtpAddress: {4} \r\n" +
                                    "OwnerSmtpAddress: {5} \r\n" +
                                    "\r\n",

                                    oAlternativeMailbox.Type,
                                    oAlternativeMailbox.DisplayName,
                                    oAlternativeMailbox.LegacyDN,
                                    oAlternativeMailbox.Server,
                                    oAlternativeMailbox.SmtpAddress,
                                    oAlternativeMailbox.OwnerSmtpAddress

                                    );
                                ValueCount++;
                            }
                            break;

                        default:
                            sValue = string.Format("{0}\r\n", usersetting.Value.ToString());
                            break;
                        }
                        ListViewItem oItem             = new ListViewItem(usersetting.Key.ToString());
                        ListViewItem.ListViewSubItem o = oItem.SubItems.Add(sValue);
                        if (ValueCount > 1)
                        {
                            o.ForeColor = System.Drawing.Color.DarkBlue;
                        }
                        lvItems.Items.Add(oItem); // Add to grid


                        //sLine = string.Format("{0}:               {1}", usersetting.Key.ToString(), sValue);

                        //sRet += sLine;
                    }

                    //sRet += "\r\n\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n\r\n";
                    //sRet += "Response Information: \r\n\r\n";
                    //sRet += "  Response Redirect Target: " + response.RedirectTarget + "\r\n";
                    //sRet += "  Response Errors: \r\n";
                    //sRet += "     ErrorCode: " + response.ErrorCode + "\r\n";
                    //sRet += "     ErrorMessage: " + response.ErrorMessage + "\r\n";
                    //sRet += "     Error on settings not returned:  \r\n";
                    //sRet += "\r\n";
                    //foreach (UserSettingError oError in response.UserSettingErrors)
                    //{
                    //    sRet += "Setting: " + oError.SettingName + "\r\n";
                    //    sRet += "   ErrorCode: " + oError.ErrorCode + "\r\n";
                    //    sRet += "   ErrorCode: " + oError.ErrorMessage + "\r\n";
                    //    sRet += "\r\n--\r\n";
                    //}
                }
                else
                {
                    sRet += "Response Error:\r\n\r\n";
                    sRet += "    AutodiscoverErrorCode : " + response.ErrorCode.ToString() + "\r\n";
                    sRet += "    Error Message:          " + response.ErrorMessage + "\r\n";
                }
            }
            catch (AutodiscoverLocalException oAutodiscoverLocalException)
            {
                sRet += "Caught AutodiscoverLocalException Exception:\r\n\r\n";
                sRet += "    Error Message: " + oAutodiscoverLocalException.Message + "\r\n";
                sRet += "    Inner Error Message: " + oAutodiscoverLocalException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + oAutodiscoverLocalException.StackTrace + "\r\n";
                sRet += "    See: " + oAutodiscoverLocalException.HelpLink + "\r\n";
            }

            catch (AutodiscoverRemoteException oAutodiscoverRemoteException)
            {
                sRet += "Caught AutodiscoverRemoteException Exception:\r\n\r\n";
                sRet += "    Error Message: " + oAutodiscoverRemoteException.Message + "\r\n";
                sRet += "    Inner Error Message: " + oAutodiscoverRemoteException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + oAutodiscoverRemoteException.StackTrace + "\r\n";
                sRet += "    See: " + oAutodiscoverRemoteException.HelpLink + "\r\n";
            }
            catch (AutodiscoverResponseException oAutodiscoverResponseException)
            {
                sRet += "Caught AutodiscoverResponseException Exception:\r\n\r\n";
                sRet += "    Error Message: " + oAutodiscoverResponseException.Message + "\r\n";
                sRet += "    Inner Error Message: " + oAutodiscoverResponseException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + oAutodiscoverResponseException.StackTrace + "\r\n";
                sRet += "    See: " + oAutodiscoverResponseException.HelpLink + "\r\n";
            }
            catch (ServerBusyException srBusyException)  // 2013+
            {
                Console.WriteLine(srBusyException);
                sRet += "Caught ServerBusyException Exception:\r\n\r\n";
                sRet += "    BackOffMilliseconds: " + srBusyException.BackOffMilliseconds.ToString() + "\r\n";
                sRet += "    Error Message: " + srBusyException.Message + "\r\n";
                sRet += "    Inner Error Message: " + srBusyException.InnerException + "\r\n";
                sRet += "    Stack Trace: " + srBusyException.StackTrace + "\r\n";
                sRet += "    See: " + srBusyException.HelpLink + "\r\n";
            }
            catch (Exception ex)
            {
                sRet += "Caught Exception:\r\n\r\n";
                sRet += "    Error Message: " + ex.Message + "\r\n";
                sRet += "    Inner Error Message: " + ex.InnerException + "\r\n";
                sRet += "    Stack Trace: " + ex.StackTrace + "\r\n";
                sRet += "    See: " + ex.HelpLink + "\r\n";
            }

            txtResults.Text = sRet;
        }
 private string GetExchangeServerVersion()
 {
     AutodiscoverService adAutoDiscoverService = new AutodiscoverService();
     adAutoDiscoverService.Credentials = new WebCredentials(username, password);
     adAutoDiscoverService.EnableScpLookup = true;
     adAutoDiscoverService.RedirectionUrlValidationCallback = RedirectionUrlValidationCallback;
     adAutoDiscoverService.PreAuthenticate = true;
     adAutoDiscoverService.TraceEnabled = true;
     adAutoDiscoverService.KeepAlive = false;
     try
     {
         GetUserSettingsResponse adResponse = adAutoDiscoverService.GetUserSettings(username, (new UserSettingName[1] { UserSettingName.EwsSupportedSchemas }));
         string schema = adResponse.Settings[UserSettingName.EwsSupportedSchemas].ToString();
         return schema;
     }
     catch (Exception ex)
     {
         NotifyDownloadStatus(DownloadStatus.INFORM, CMController.Properties.Resources.turn_off_two_step_verification);
     }
     return "";
 }