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."); }
/// <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 GetUserSettingsResponse GetUserSettings(string Mailbox) { // Attempt autodiscover, with maximum of 10 hops // As per MSDN: http://msdn.microsoft.com/en-us/library/office/microsoft.exchange.webservices.autodiscover.autodiscoverservice.getusersettings(v=exchg.80).aspx Uri url = null; GetUserSettingsResponse response = null; for (int attempt = 0; attempt < 10; attempt++) { _autodiscover.Url = url; _autodiscover.EnableScpLookup = (attempt < 2); response = _autodiscover.GetUserSettings(Mailbox, UserSettingName.InternalEwsUrl, UserSettingName.ExternalEwsUrl, UserSettingName.GroupingInformation); if (response.ErrorCode == AutodiscoverErrorCode.RedirectAddress) { return(GetUserSettings(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."); }
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(""); }
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 }
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, ex.Message); } return ""; }
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 ""; }
public bool AddMailbox(string SMTPAddress, string AutodiscoverURL = "") { // Perform autodiscover for the mailbox and store the information if (_mailboxes.ContainsKey(SMTPAddress)) { // We already have autodiscover information for this mailbox, if it is recent enough we don't bother retrieving it again if (_mailboxes[SMTPAddress].IsStale) { _mailboxes.Remove(SMTPAddress); } else { return(true); } } MailboxInfo info = null; // Retrieve the autodiscover information _logger.Log($"Retrieving user settings for {SMTPAddress}"); GetUserSettingsResponse userSettings = null; if (!String.IsNullOrEmpty(AutodiscoverURL)) { // Use the supplied Autodiscover URL try { _autodiscover.Url = new Uri(AutodiscoverURL); userSettings = _autodiscover.GetUserSettings(SMTPAddress, UserSettingName.InternalEwsUrl, UserSettingName.ExternalEwsUrl, UserSettingName.GroupingInformation); } catch { } } if (userSettings == null) { try { // Try full autodiscover userSettings = GetUserSettings(SMTPAddress); } catch (Exception ex) { _logger.Log(String.Format("Failed to autodiscover for {0}: {1}", SMTPAddress, ex.Message)); return(false); } } // Store the autodiscover result, and check that we have what we need for subscriptions info = new MailboxInfo(SMTPAddress, userSettings); if (!info.HaveSubscriptionInformation) { _logger.Log(String.Format("Autodiscover succeeded, but EWS Url was not returned for {0}", SMTPAddress)); return(false); } // Add the mailbox to our list, and if it will be part of a new group add that to the group list (with this mailbox as the primary mailbox) _mailboxes.Add(info.SMTPAddress, info); return(true); }
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; }
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); }
/// <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 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); }
// 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); }
// 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)); } }