public ICredentials GetCredentials(IConfigurationSession configurationSession, ADUser actAsUser = null) { ArgumentValidator.ThrowIfNull("configurationSession", configurationSession); ICredentials credentials = null; string organizationIdKey = this.GetOrganizationIdKey(configurationSession); if (!string.IsNullOrEmpty(organizationIdKey)) { string stringFromConfigFile = this.GetStringFromConfigFile("UP_TenantAdminCred_" + organizationIdKey); int num = stringFromConfigFile.IndexOf(':'); if (num > 0) { credentials = new NetworkCredential(stringFromConfigFile.Substring(0, num), stringFromConfigFile.Substring(num + 1)); } } if (credentials == null) { Organization orgContainer = configurationSession.GetOrgContainer(); if (orgContainer != null && orgContainer.OrganizationId != null) { if (actAsUser != null) { credentials = OAuthCredentials.GetOAuthCredentialsForAppActAsToken(orgContainer.OrganizationId, actAsUser, null); } else { credentials = OAuthCredentials.GetOAuthCredentialsForAppToken(orgContainer.OrganizationId, "PlaceHolder"); } } } return(credentials); }
private static ICredentials GetAppCredentials(OrganizationId organizationId) { ICredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(organizationId, "dummyRealm"); AADClientFactory.Tracer.TraceDebug <OrganizationId, ICredentials>(0L, "Created app credentials for {0}: {1}", organizationId, oauthCredentialsForAppToken); return(oauthCredentialsForAppToken); }
public override ExchangeServiceBinding CreateServiceBinding(Uri serviceUrl) { Tracer.TraceInformation("ServerToServerEwsCallingContext.CreateServiceBinding", new object[0]); ExchangeServiceBinding exchangeServiceBinding = base.CreateServiceBinding(serviceUrl); if (this.remoteUrls.ContainsKey(serviceUrl)) { OAuthCredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(OrganizationId.ForestWideOrgId, this.remoteUrls[serviceUrl]); exchangeServiceBinding.UseDefaultCredentials = false; exchangeServiceBinding.Credentials = oauthCredentialsForAppToken; exchangeServiceBinding.ManagementRole = new ManagementRoleType { ApplicationRoles = new string[] { "MailboxSearchApplication" } }; } else { exchangeServiceBinding.UseDefaultCredentials = true; exchangeServiceBinding.Disposed += delegate(object param0, EventArgs param1) { ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Remove(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ServerToServerEwsCallingContext.CertificateErrorHandler)); }; ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ServerToServerEwsCallingContext.CertificateErrorHandler)); } return(exchangeServiceBinding); }
private void Authenticate() { switch (this.groupId.GroupType) { case GroupType.CrossServer: this.service.OnSerializeCustomSoapHeaders += new CustomXmlSerializationDelegate(this.OnSerializeCustomSoapHeaders); return; case GroupType.CrossPremise: this.service.ManagementRoles = new ManagementRoles(null, DiscoveryEwsClient.MailboxSearchApplicationRole); this.service.Credentials = new OAuthCredentials(OAuthCredentials.GetOAuthCredentialsForAppToken(this.callerInfo.OrganizationId, this.mailboxes[0].GetDomain())); return; default: return; } }
public static OAuthCredentials CreateAsApp(InternalClientContext clientContext, RequestLogger requestLogger) { ArgumentValidator.ThrowIfNull("clientContext", clientContext); OrganizationId organizationId = clientContext.OrganizationId; string domain = clientContext.ADUser.PrimarySmtpAddress.Domain; string text = FaultInjection.TraceTest <string>((FaultInjection.LIDs) 2743479613U); if (!string.IsNullOrEmpty(text)) { domain = SmtpAddress.Parse(text).Domain; organizationId = OrganizationId.FromAcceptedDomain(domain); } OAuthCredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(organizationId, domain); OAuthCredentialsFactory.SetCredentialsProperties(oauthCredentialsForAppToken, clientContext, requestLogger); return(oauthCredentialsForAppToken); }
public ExchangeProxy(ISearchPolicy policy, GroupId groupId) { Recorder.Trace(5L, TraceType.InfoTrace, new object[] { "ExchangeProxy.ctor GroupId:", groupId, "GroupType:", groupId.GroupType, "Uri:", groupId.Uri }); this.groupId = groupId; this.policy = policy; ExchangeCredentials credentials; if (this.groupId.GroupType == GroupType.CrossPremise) { credentials = new OAuthCredentials(OAuthCredentials.GetOAuthCredentialsForAppToken(this.policy.CallerInfo.OrganizationId, groupId.Domain)); } else { credentials = new WebCredentials(); } string text = string.Format("{0}&FOUT=true", policy.CallerInfo.UserAgent); this.InitializeExchangeProxy(credentials, groupId.Uri, (long)groupId.ServerVersion); this.exchangeService.HttpHeaders[CertificateValidationManager.ComponentIdHeaderName] = typeof(IEwsClient).FullName; this.exchangeService.ClientRequestId = this.policy.CallerInfo.QueryCorrelationId.ToString(); this.exchangeService.Timeout = (int)TimeSpan.FromMinutes(this.policy.ThrottlingSettings.DiscoverySearchTimeoutPeriod).TotalMilliseconds; if (this.groupId.GroupType == GroupType.CrossPremise) { this.exchangeService.UserAgent = text; this.exchangeService.ManagementRoles = new ManagementRoles(null, ExchangeProxy.mailboxSearchApplicationRole); return; } this.exchangeService.UserAgent = WellKnownUserAgent.GetEwsNegoAuthUserAgent(string.Format("{0}-{1}", ExchangeProxy.crossServerUserAgent, text)); if (this.policy.CallerInfo.CommonAccessToken != null && !this.policy.CallerInfo.IsOpenAsAdmin) { this.exchangeService.HttpHeaders["X-CommonAccessToken"] = this.policy.CallerInfo.CommonAccessToken.Serialize(); if (this.policy.CallerInfo.UserRoles != null || this.policy.CallerInfo.ApplicationRoles != null) { this.exchangeService.ManagementRoles = new ManagementRoles(this.policy.CallerInfo.UserRoles, this.policy.CallerInfo.ApplicationRoles); } } }
public override DefaultBinding_Autodiscover CreateServiceBinding(Uri serviceUrl) { Tracer.TraceInformation("ServerToServerEwsCallingContext.CreateServiceBinding", new object[0]); DefaultBinding_Autodiscover defaultBinding_Autodiscover = base.CreateServiceBinding(serviceUrl); if (this.remoteUrls.ContainsKey(serviceUrl)) { OAuthCredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(OrganizationId.ForestWideOrgId, this.remoteUrls[serviceUrl]); defaultBinding_Autodiscover.UseDefaultCredentials = false; defaultBinding_Autodiscover.Credentials = oauthCredentialsForAppToken; } else { defaultBinding_Autodiscover.UseDefaultCredentials = true; defaultBinding_Autodiscover.Disposed += delegate(object param0, EventArgs param1) { ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Remove(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ServerToServerEwsCallingContext.CertificateErrorHandler)); }; ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(ServerToServerEwsCallingContext.CertificateErrorHandler)); } return(defaultBinding_Autodiscover); }
internal static ICredentials GetICredentials(bool appOnly, ADUser user, string domain) { ICredentials result; if (appOnly) { OrganizationId organizationId = OrganizationId.FromAcceptedDomain(domain); result = OAuthCredentials.GetOAuthCredentialsForAppToken(organizationId, domain); } else { if (user == null) { throw new Exception(Strings.NullUserError); } OrganizationId organizationId = user.OrganizationId; if (organizationId == null) { throw new Exception(Strings.NullOrgIdException(user.Name)); } result = OAuthCredentials.GetOAuthCredentialsForAppActAsToken(organizationId, user, domain); } return(result); }
internal static ICredentials GetCredentialAndConfigureClientContext(ADRawEntry actAsUser, OrganizationId actAsUserOrgId, ClientContext context, bool createAppTokenOnly, out bool isOAuthCredential) { if (!createAppTokenOnly && actAsUser == null) { throw new ArgumentNullException("actAsUser"); } if (actAsUserOrgId == null) { throw new ArgumentNullException("actAsUserOrgId"); } int num = 0; isOAuthCredential = true; RegistryKey registryKey = null; try { registryKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\MSExchangeRPC\\ParametersSystem", RegistryKeyPermissionCheck.ReadSubTree); if (registryKey != null) { num = (int)registryKey.GetValue("TMPublishHttpDebugEnabled", 0); if ((int)registryKey.GetValue("TMOAuthEnabled", 1) == 0) { isOAuthCredential = false; return(null); } } } catch (SecurityException) { return(null); } catch (IOException) { return(null); } catch (UnauthorizedAccessException) { return(null); } finally { if (registryKey != null) { registryKey.Close(); } } ICredentials credentials; if (createAppTokenOnly) { credentials = OAuthCredentials.GetOAuthCredentialsForAppToken(actAsUserOrgId, "PlaceHolder"); } else { ADObjectId id = actAsUser.Id; ADSessionSettings sessionSettings = ADSessionSettings.FromAllTenantsOrRootOrgAutoDetect(id); IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(true, ConsistencyMode.IgnoreInvalid, sessionSettings, 552, "GetCredentialAndConfigureClientContext", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\RecipientTasks\\TeamMailbox\\TeamMailboxHelper.cs"); ADUser aduser = tenantOrRootOrgRecipientSession.FindADUserByObjectId(id); credentials = OAuthCredentials.GetOAuthCredentialsForAppActAsToken(actAsUserOrgId, aduser, null); } if (context != null) { context.Credentials = credentials; context.FormDigestHandlingEnabled = false; context.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs args) { args.WebRequestExecutor.RequestHeaders.Add(HttpRequestHeader.Authorization, "Bearer"); args.WebRequestExecutor.RequestHeaders.Add("client-request-id", Guid.NewGuid().ToString()); args.WebRequestExecutor.RequestHeaders.Add("return-client-request-id", "true"); args.WebRequestExecutor.WebRequest.PreAuthenticate = true; args.WebRequestExecutor.WebRequest.UserAgent = Utils.GetUserAgentStringForSiteMailboxRequests(); }; if (num == 1) { context.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs args) { args.WebRequestExecutor.WebRequest.Proxy = new WebProxy("127.0.0.1", 8888); }; } } return(credentials); }
private void TryNotifySharePointForExchangeResources(MailboxUrls mailboxUrls) { OrganizationId orgId = this.groupADUser.OrganizationId; string externalDirectoryObjectId = this.groupADUser.ExternalDirectoryObjectId; Guid activityId = this.activityId; Stopwatch timer = Stopwatch.StartNew(); Task.Factory.StartNew(delegate() { ICredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(orgId, "dummyRealm"); using (SharePointNotification sharePointNotification = new SharePointNotification(SharePointNotification.NotificationType.Update, externalDirectoryObjectId, orgId, oauthCredentialsForAppToken, activityId)) { foreach (KeyValuePair <string, string> keyValuePair in mailboxUrls.ToExchangeResourcesDictionary()) { sharePointNotification.SetResourceValue(keyValuePair.Key, keyValuePair.Value, false); } sharePointNotification.Execute(); string value = string.Format("Success;Group={0};Org={1};ElapsedTime={2}", externalDirectoryObjectId, orgId, timer.ElapsedMilliseconds); FederatedDirectoryLogger.AppendToLog(new SchemaBasedLogEvent <FederatedDirectoryLogSchema.TraceTag> { { FederatedDirectoryLogSchema.TraceTag.TaskName, "UpdateSiteCollectionTask" }, { FederatedDirectoryLogSchema.TraceTag.ActivityId, activityId }, { FederatedDirectoryLogSchema.TraceTag.CurrentAction, "SharePointSetMailboxUrls" }, { FederatedDirectoryLogSchema.TraceTag.Message, value } }); } }).ContinueWith(delegate(Task t) { Exception ex = null; if (t.Exception != null) { ex = t.Exception.InnerException; } string value = string.Format("Failed;Group={0};Org={1};ElapsedTime={2}", externalDirectoryObjectId, orgId, timer.ElapsedMilliseconds); FederatedDirectoryLogger.AppendToLog(new SchemaBasedLogEvent <FederatedDirectoryLogSchema.ExceptionTag> { { FederatedDirectoryLogSchema.ExceptionTag.TaskName, "UpdateSiteCollectionTask" }, { FederatedDirectoryLogSchema.ExceptionTag.ActivityId, activityId }, { FederatedDirectoryLogSchema.ExceptionTag.CurrentAction, "SharePointSetMailboxUrls" }, { FederatedDirectoryLogSchema.ExceptionTag.ExceptionType, (ex != null) ? ex.GetType().ToString() : "Unknown" }, { FederatedDirectoryLogSchema.ExceptionTag.ExceptionDetail, ex }, { FederatedDirectoryLogSchema.ExceptionTag.Message, value } }); }, TaskContinuationOptions.OnlyOnFaulted); }
public Dictionary <GroupId, List <MailboxInfo> > FindEwsEndpoints(out long localDiscoverTime, out long autoDiscoverTime) { Stopwatch stopwatch = new Stopwatch(); localDiscoverTime = 0L; autoDiscoverTime = 0L; stopwatch.Start(); List <MailboxInfo> list; string text; this.FilterLocalForestMailboxes(out list, out text); stopwatch.Stop(); localDiscoverTime = stopwatch.ElapsedMilliseconds; Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, long>((long)this.GetHashCode(), "Correlation Id:{0}. Mapping local mailboxes to servers took {1}ms", this.callerInfo.QueryCorrelationId, localDiscoverTime); if (list == null || list.Count == 0) { return(this.mailboxGroups); } string searchId = string.Empty; Match match = Regex.Match(this.callerInfo.UserAgent, "SID=([a-fA-F0-9\\-]*)"); if (match.Success && match.Groups != null && match.Groups.Count > 1) { searchId = match.Groups[1].Value; } Uri url = null; EndPointDiscoveryInfo endPointDiscoveryInfo; bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(this.orgId, text, this.GetOrgIdCacheValue, this.GetIntraOrganizationConnector, this.GetOrganizationRelationShip, out url, out endPointDiscoveryInfo); if (endPointDiscoveryInfo != null && endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success) { SearchEventLogger.Instance.LogSearchErrorEvent(searchId, endPointDiscoveryInfo.Message); } if (!flag) { Factory.Current.MailboxGroupGeneratorTracer.TraceDebug <Guid, string>((long)this.GetHashCode(), "Correlation Id:{0}. Unable to find the discovery end point for domain {1}", this.callerInfo.QueryCorrelationId, text); GroupId key = new GroupId(new MultiMailboxSearchException(Strings.CouldNotFindOrgRelationship(text))); this.mailboxGroups.Add(key, list); return(this.mailboxGroups); } Factory.Current.MailboxGroupGeneratorTracer.TraceDebug <Guid, string, Uri>((long)this.GetHashCode(), "Correlation Id:{0}. EWS endpoint for domain {1} is {2}", this.callerInfo.QueryCorrelationId, text, EwsWsSecurityUrl.FixForAnonymous(url)); OAuthCredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(this.orgId, text); stopwatch.Restart(); List <MailboxInfo> list2 = (from mailboxInfo in list where mailboxInfo.IsArchive select mailboxInfo).ToList <MailboxInfo>(); List <MailboxInfo> list3 = (from mailboxInfo in list where !mailboxInfo.IsArchive select mailboxInfo).ToList <MailboxInfo>(); if (list2.Count > 0) { Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover started for cross premise archive mailboxes.", this.callerInfo.QueryCorrelationId, list2.Count); this.DoAutodiscover(list2, EwsWsSecurityUrl.FixForAnonymous(url), oauthCredentialsForAppToken); Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover completed for cross premise archive mailboxes.", this.callerInfo.QueryCorrelationId, list2.Count); } if (list3.Count > 0) { Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover started for cross premise primary mailboxes.", this.callerInfo.QueryCorrelationId, list3.Count); this.DoAutodiscover(list3, EwsWsSecurityUrl.FixForAnonymous(url), oauthCredentialsForAppToken); Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, int>((long)this.GetHashCode(), "Correlation Id:{0}. Mbx Count:{1}. Autodiscover completed for cross premise primary mailboxes.", this.callerInfo.QueryCorrelationId, list3.Count); } stopwatch.Stop(); autoDiscoverTime = stopwatch.ElapsedMilliseconds; Factory.Current.MailboxGroupGeneratorTracer.TracePerformance <Guid, long>((long)this.GetHashCode(), "Correlation Id:{0}. Autodiscover call took {1}ms", this.callerInfo.QueryCorrelationId, autoDiscoverTime); return(this.mailboxGroups); }
// 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 ICredentials Get(OrganizationId organizationId) { return(OAuthCredentials.GetOAuthCredentialsForAppToken(organizationId, "PlaceHolder")); }
public IList <ISource> ValidateAndGetFinalSourceMailboxes(string searchQuery, IList <string> sourceMailboxes, IList <string> notFoundMailboxes, IList <string> versionSkippedMailboxes, IList <string> rbacDeniedMailboxes, IList <string> crossPremiseFailedMailboxes, IDictionary <Uri, string> crossPremiseUrls) { Util.ThrowIfNullOrEmpty(searchQuery, "Search query cannot be empty."); Util.ThrowIfNull(sourceMailboxes, "sourceMailboxes"); Util.ThrowIfNull(notFoundMailboxes, "notFoundMailboxes"); Util.ThrowIfNull(versionSkippedMailboxes, "versionSkippedMailboxes"); Util.ThrowIfNull(rbacDeniedMailboxes, "rbacDeniedMailboxes"); Util.ThrowIfNull(crossPremiseFailedMailboxes, "crossPremiseFailedMailboxes"); Util.ThrowIfNull(crossPremiseUrls, "crossPremiseUrls"); List <ISource> list = new List <ISource>(); Dictionary <MiniRecipient, MailboxInfo> dictionary = new Dictionary <MiniRecipient, MailboxInfo>(); int num = 0; if (sourceMailboxes.Count == 0) { AndFilter filter = new AndFilter(new QueryFilter[] { new OrFilter(new QueryFilter[] { Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.UserMailbox), Util.CreateRecipientTypeDetailsValueFilter((RecipientTypeDetails)((ulong)int.MinValue)), Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteRoomMailbox), Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteEquipmentMailbox), Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteSharedMailbox), Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.RemoteTeamMailbox) }), new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.ArbitrationMailbox)), new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.MonitoringMailbox)), new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.AuditLogMailbox)), new NotFilter(Util.CreateRecipientTypeDetailsValueFilter(RecipientTypeDetails.MailboxPlan)) }); this.CheckRecipientSessionIsNotNull(); ADPagedReader <StorageMiniRecipient> adpagedReader = this.recipientSession.FindPagedMiniRecipient <StorageMiniRecipient>(null, QueryScope.SubTree, filter, null, 1000, SearchMailboxCriteria.RecipientTypeDetailsProperty); using (IEnumerator <StorageMiniRecipient> enumerator = adpagedReader.GetEnumerator()) { while (enumerator.MoveNext()) { StorageMiniRecipient storageMiniRecipient = enumerator.Current; if (!storageMiniRecipient.LegacyExchangeDN.Equals(this.SearchObject.Target, StringComparison.OrdinalIgnoreCase)) { if ((long)(++num) > (long)((ulong)this.MaxMailboxesToSearch)) { throw new SearchTooManyMailboxesException((int)this.MaxMailboxesToSearch); } this.ValidateAndAddToFinalSourceMailboxes(searchQuery, storageMiniRecipient, list, versionSkippedMailboxes, rbacDeniedMailboxes, dictionary); } } goto IL_2B6; } } foreach (ADObjectId adobjectId in this.ExpandGroupMembers(sourceMailboxes, this.DiscoverySystemMailboxUser.OrganizationId, notFoundMailboxes)) { if ((this.SearchObject.Target == null || !adobjectId.Equals(this.TargetMailboxUser.Id)) && !adobjectId.Equals(this.DiscoverySystemMailboxUser.Id)) { this.CheckRecipientSessionIsNotNull(); StorageMiniRecipient storageMiniRecipient2 = this.recipientSession.ReadMiniRecipient <StorageMiniRecipient>(adobjectId, SearchMailboxCriteria.RecipientTypeDetailsProperty); if (storageMiniRecipient2 != null) { if ((long)(++num) > (long)((ulong)this.MaxMailboxesToSearch)) { throw new SearchTooManyMailboxesException((int)this.MaxMailboxesToSearch); } this.ValidateAndAddToFinalSourceMailboxes(searchQuery, storageMiniRecipient2, list, versionSkippedMailboxes, rbacDeniedMailboxes, dictionary); } else { Util.Tracer.TraceError <string>((long)this.GetHashCode(), "Unable to find mailbox: {0}", adobjectId.Name); } } } IL_2B6: if (dictionary.Count > 0) { string domain = dictionary.First <KeyValuePair <MiniRecipient, MailboxInfo> >().Value.GetDomain(); Util.Tracer.TraceDebug <string>((long)this.GetHashCode(), "Before autodiscover for cross premise domain: {0}", domain); Uri uri = null; EndPointDiscoveryInfo endPointDiscoveryInfo; bool flag = RemoteDiscoveryEndPoint.TryGetDiscoveryEndPoint(this.SearchDataProvider.OrganizationId, domain, null, null, null, out uri, out endPointDiscoveryInfo); if (endPointDiscoveryInfo != null) { ScenarioData.Current["IOC"] = ((int)endPointDiscoveryInfo.Status).ToString(); if (endPointDiscoveryInfo.Status != EndPointDiscoveryInfo.DiscoveryStatus.Success) { SearchEventLogger.Instance.LogSearchErrorEvent(ScenarioData.Current["SID"], endPointDiscoveryInfo.Message); } } if (flag) { Util.Tracer.TraceDebug <Uri>((long)this.GetHashCode(), "Auto discover Url : {1}", uri); ICredentials oauthCredentialsForAppToken = OAuthCredentials.GetOAuthCredentialsForAppToken(this.SearchDataProvider.OrganizationId, domain); List <MailboxInfo> list2 = new List <MailboxInfo>(dictionary.Count); foreach (KeyValuePair <MiniRecipient, MailboxInfo> keyValuePair in dictionary) { list2.Add(keyValuePair.Value); } IAutodiscoveryClient autodiscoveryClient = Factory.Current.CreateUserSettingAutoDiscoveryClient(list2, EwsWsSecurityUrl.FixForAnonymous(uri), oauthCredentialsForAppToken, new CallerInfo(true, null, null, string.Empty, null, null, null)); IAsyncResult result = autodiscoveryClient.BeginAutodiscover(null, null); Dictionary <GroupId, List <MailboxInfo> > dictionary2 = autodiscoveryClient.EndAutodiscover(result); if (dictionary2 != null) { using (Dictionary <GroupId, List <MailboxInfo> > .Enumerator enumerator4 = dictionary2.GetEnumerator()) { while (enumerator4.MoveNext()) { KeyValuePair <GroupId, List <MailboxInfo> > keyValuePair2 = enumerator4.Current; if (keyValuePair2.Key.GroupType == GroupType.CrossPremise) { if (!crossPremiseUrls.ContainsKey(keyValuePair2.Key.Uri)) { crossPremiseUrls.Add(keyValuePair2.Key.Uri, domain); } using (List <ISource> .Enumerator enumerator5 = list.GetEnumerator()) { while (enumerator5.MoveNext()) { ISource source = enumerator5.Current; SourceMailbox sourceMailbox = (SourceMailbox)source; foreach (MailboxInfo mailboxInfo in keyValuePair2.Value) { if (string.Compare(sourceMailbox.LegacyExchangeDN, mailboxInfo.LegacyExchangeDN, StringComparison.OrdinalIgnoreCase) == 0) { sourceMailbox.ServiceEndpoint = keyValuePair2.Key.Uri; break; } } } continue; } } if (keyValuePair2.Key.GroupType == GroupType.SkippedError) { foreach (MailboxInfo mailboxInfo2 in keyValuePair2.Value) { Util.Tracer.TraceError <SmtpAddress>((long)this.GetHashCode(), "Auto discover skipped error for mailbox: {0}", mailboxInfo2.PrimarySmtpAddress); crossPremiseFailedMailboxes.Add(mailboxInfo2.LegacyExchangeDN); } } } goto IL_5F2; } } Util.Tracer.TraceError <string>((long)this.GetHashCode(), "Auto discover results is null for domain: {0}", domain); } else { Util.Tracer.TraceError <string>((long)this.GetHashCode(), "Organization relationship is not set up for domain: {0}", domain); foreach (KeyValuePair <MiniRecipient, MailboxInfo> keyValuePair3 in dictionary) { crossPremiseFailedMailboxes.Add(keyValuePair3.Value.LegacyExchangeDN); } } } IL_5F2: if (crossPremiseFailedMailboxes.Count > 0) { foreach (string b in crossPremiseFailedMailboxes) { for (int i = list.Count - 1; i >= 0; i--) { ISource source2 = list[i]; if (source2.LegacyExchangeDN == b) { list.RemoveAt(i); } } } } return(list); }