private GetUserSettingsResponse GetUserSettings(string Mailbox, string startUrl = "") { // Attempt autodiscover, with maximum of 10 hops // As per docs: https://docs.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.autodiscover.autodiscoverservice.getusersettings?view=exchange-ews-api Uri url = null; GetUserSettingsResponse response = null; if (!String.IsNullOrEmpty(startUrl)) { url = new Uri(startUrl); } if (!_credentialHandler.ApplyCredentialsToAutodiscoverService(_autodiscover)) { throw new Exception("Failed to apply credentials to Autodiscover service"); } for (int attempt = 0; attempt < 10; attempt++) { if (url != null) { _autodiscover.Url = url; } _autodiscover.EnableScpLookup = false;// (attempt < 2); response = _autodiscover.GetUserSettings(Mailbox, UserSettingName.InternalEwsUrl, UserSettingName.ExternalEwsUrl, UserSettingName.GroupingInformation); if (response.ErrorCode == AutodiscoverErrorCode.RedirectAddress) { // Redirecting to different mail address (can occur in hybrid) return(GetUserSettings(response.RedirectTarget)); } else if (response.ErrorCode == AutodiscoverErrorCode.RedirectUrl) { // Redirecting to another AutoDiscover Url url = new Uri(response.RedirectTarget); } else { _logger.Log($"Autodiscover Url: {_autodiscover.Url}"); return(response); } } throw new Exception("No suitable Autodiscover endpoint was found."); }
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); } }