private MserveTargetConnection.TenantSyncControl GetTenantSyncControlSettingFromAD(ADObjectId tenantCUId, string key)
        {
            ExchangeConfigurationUnit tenantCU      = null;
            int               tryCount              = 0;
            string            savedDomainController = this.ConfigSession.DomainController;
            ADOperationResult adoperationResult     = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                if (tryCount++ == 0)
                {
                    this.ConfigSession.DomainController = this.sourceConnection.Fqdn;
                }
                else
                {
                    this.ConfigSession.DomainController = savedDomainController;
                }
                tenantCU = this.ConfigSession.Read <ExchangeConfigurationUnit>(tenantCUId);
            }, 2);

            this.ConfigSession.DomainController = savedDomainController;
            if (!adoperationResult.Succeeded)
            {
                throw new ExDirectoryException(string.Format("Failed to read user's ExchangeConfigurationUnit {0}", tenantCUId.DistinguishedName), adoperationResult.Exception);
            }
            if (tenantCU == null)
            {
                throw new ExDirectoryException(string.Format("Failed to read user's ExchangeConfigurationUnit {0} because AD returns null", tenantCUId.DistinguishedName), null);
            }
            base.LogSession.LogEvent(EdgeSyncLoggingLevel.High, EdgeSyncEvent.TargetConnection, tenantCUId.DistinguishedName, "OrgStatus:" + tenantCU.OrganizationStatus);
            if (!tenantCU.IsOrganizationReadyForMservSync)
            {
                throw new ExDirectoryException(string.Format("Warning: ExchangeConfigurationUnit {0} with OrgStatus {1} is not ready for Mserv Sync yet.", tenantCUId.DistinguishedName, tenantCU.OrganizationStatus), null);
            }
            return(new MserveTargetConnection.TenantSyncControl(tenantCU.SyncMEUSMTPToMServ, tenantCU.SyncMBXAndDLToMServ));
        }
        // Token: 0x0600001C RID: 28 RVA: 0x00002F60 File Offset: 0x00001160
        private bool RegisterConfigurationChangeHandlers(out ADOperationResult opResult)
        {
            ExTraceGlobals.ServiceTracer.TraceDebug(0L, "TransportService register configuration change notifications");
            Server server;

            if (ADNotificationAdapter.TryReadConfiguration <Server>(delegate()
            {
                Server result;
                try
                {
                    result = TransportService.adConfigurationSession.FindLocalServer();
                }
                catch (LocalServerNotFoundException)
                {
                    result = null;
                }
                return(result);
            }, out server, out opResult))
            {
                opResult = ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    if (this.receiveConnectorNotificationCookie == null)
                    {
                        this.receiveConnectorNotificationCookie = TransportADNotificationAdapter.Instance.RegisterForLocalServerReceiveConnectorNotifications(server.Id, new ADNotificationCallback(this.ConnectorsConfigUpdate));
                        ExTraceGlobals.ServiceTracer.TraceDebug <ADObjectId>(0L, "TransportService registered for Receive Connector configuration change notifications (server id={0})", server.Id);
                    }
                    this.serverNotificationCookie = TransportADNotificationAdapter.Instance.RegisterForExchangeServerNotifications(server.Id, new ADNotificationCallback(this.ServerConfigUpdate));
                    ExTraceGlobals.ServiceTracer.TraceDebug <ADObjectId>(0L, "TransportService registered for Server configuration change notifications (server id={0})", server.Id);
                });
                return(opResult.Succeeded);
            }
            ExTraceGlobals.ServiceTracer.TraceDebug(0L, "TransportService failed to get local server. Failed to register for configuration change notifications.");
            return(false);
        }
        internal void ReadConfiguration()
        {
            StateType state = default(StateType);

            this.PreAdOperation(ref state);
            base.CheckDisposed();
            this.TryRegisterForADNotifications();
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                this.AdOperation(ref state);
            }, 2);

            if (adoperationResult.Succeeded)
            {
                if (this.adNotificationCookie != null)
                {
                    this.UpdateTimer(this.periodicReadInterval);
                }
            }
            else
            {
                this.LogFailure(ADConfigurationLoader <ADConfigType, StateType> .FailureLocation.ADConfigurationLoading, adoperationResult.Exception);
                if (this.adNotificationCookie != null)
                {
                    this.UpdateTimer(this.failureRetryInterval);
                }
            }
            this.PostAdOperation(state, adoperationResult.Succeeded);
        }
        // Token: 0x0600108F RID: 4239 RVA: 0x00060D40 File Offset: 0x0005EF40
        private ADOperationResult TryRunPerGroupADOperation(ADOperation adOperation, string groupDN)
        {
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(adOperation, 3);

            switch (adoperationResult.ErrorCode)
            {
            case ADOperationErrorCode.RetryableError:
                GroupMetricsGenerator.EventLogger.LogEvent(InfoWorkerEventLogConstants.Tuple_GroupExpansionHaltedWarning, this.GetOrganizationIdString(), new object[]
                {
                    adoperationResult.Exception.GetType().Name,
                    groupDN,
                    adoperationResult.Exception
                });
                break;

            case ADOperationErrorCode.PermanentError:
                GroupMetricsGenerator.EventLogger.LogEvent(InfoWorkerEventLogConstants.Tuple_GroupExpansionHaltedError, this.GetOrganizationIdString(), new object[]
                {
                    adoperationResult.Exception.GetType().Name,
                    groupDN,
                    adoperationResult.Exception
                });
                break;
            }
            return(adoperationResult);
        }
Пример #5
0
        private TransportService GetDefaultTransportServiceRole()
        {
            ITopologyConfigurationSession session = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 258, "GetDefaultTransportServiceRole", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\transport\\AgentLog\\GetAgentLog.cs");
            Server            localServer         = null;
            ADOperationResult adoperationResult   = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                localServer = session.FindLocalServer();
            });

            if (!adoperationResult.Succeeded)
            {
                base.WriteError(adoperationResult.Exception, ErrorCategory.ReadError, null);
            }
            ServerRole currentServerRole = localServer.CurrentServerRole;

            if ((currentServerRole & ServerRole.HubTransport) != ServerRole.None)
            {
                return(TransportService.Hub);
            }
            if ((currentServerRole & ServerRole.Edge) != ServerRole.None)
            {
                return(TransportService.Edge);
            }
            if ((currentServerRole & ServerRole.FrontendTransport) != ServerRole.None)
            {
                return(TransportService.FrontEnd);
            }
            if ((currentServerRole & ServerRole.Mailbox) != ServerRole.None)
            {
                return(TransportService.MailboxDelivery);
            }
            return(TransportService.Hub);
        }
Пример #6
0
        private IList <Guid> FindLocalDatabasesFromAD()
        {
            MailboxDatabase[] databases         = null;
            IList <Guid>      list              = new List <Guid>();
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                databases = this.GetLocalServer().GetMailboxDatabases();
            });

            if (adoperationResult.ErrorCode != ADOperationErrorCode.Success || databases == null)
            {
                return(list);
            }
            foreach (MailboxDatabase mailboxDatabase in databases)
            {
                bool flag = mailboxDatabase.IsValid && mailboxDatabase.Mounted != null && mailboxDatabase.Mounted.Value;
                if (flag)
                {
                    list.Add(mailboxDatabase.Guid);
                }
                else
                {
                    this.logger.LogOneEntry("NotificationLoader", string.Empty, ExecutionLog.EventType.Verbose, string.Format("FindLocalDatabasesFromAD: skip offline database {0}", mailboxDatabase.Guid), null);
                }
            }
            this.logger.LogOneEntry("NotificationLoader", string.Empty, ExecutionLog.EventType.Verbose, string.Format("FindLocalDatabasesFromAD: found {0} database on local server", list.Count), null);
            return(list);
        }
Пример #7
0
        private static IEnumerable <ADRawEntry> ReadDkmAdObjects(IRootOrganizationRecipientSession session, string dkmContainerName, string rootDomain, StringBuilder detailStatus)
        {
            string dkmContainerDN = TestDataCenterDKMAccess.CreateDkmContainerDN(dkmContainerName, rootDomain);

            ADRawEntry[]      dkmObjects        = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                dkmObjects = session.Find(new ADObjectId(dkmContainerDN), QueryScope.SubTree, new CustomLdapFilter("(objectClass=contact)"), null, -1, new ADPropertyDefinition[]
                {
                    ADObjectSchema.Name
                });
            });

            if (!adoperationResult.Succeeded)
            {
                detailStatus.AppendFormat("Failed to read DKM objects under DN {0} with exception {1}", dkmContainerDN, (adoperationResult.Exception == null) ? "N/A" : adoperationResult.Exception.Message);
                return(null);
            }
            if (dkmObjects.Length == 0)
            {
                detailStatus.AppendFormat("Failed to find any DKM objects under DN {0}. Examine the ACL settings on DKM objects to ensure the Exchange Servers group is allowed.", dkmContainerDN);
                return(null);
            }
            return(dkmObjects);
        }
Пример #8
0
        private bool TryReadCookie(IConfigurationSession session, out Cookie cookie)
        {
            ADObjectId cookieContainerId = null;
            Container  cookieContainer   = null;

            cookie = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                cookieContainerId = this.GetCookieContainerId(session);
                cookieContainer   = session.Read <Container>(cookieContainerId);
            }, 3);

            if (adoperationResult.Succeeded)
            {
                using (MultiValuedProperty <byte[]> .Enumerator enumerator = cookieContainer.EdgeSyncCookies.GetEnumerator())
                {
                    if (enumerator.MoveNext())
                    {
                        byte[] bytes = enumerator.Current;
                        cookie = Cookie.Deserialize(Encoding.ASCII.GetString(bytes));
                    }
                }
            }
            return(adoperationResult.Succeeded);
        }
Пример #9
0
 private static void HandleConfigurationChange(ADNotificationEventArgs args)
 {
     try
     {
         if (Interlocked.Increment(ref RmsClientManagerLog.notificationHandlerCount) == 1)
         {
             Server            localServer       = null;
             ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
             {
                 ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 1191, "HandleConfigurationChange", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\rightsmanagement\\RmsClientManagerLog.cs");
                 localServer = topologyConfigurationSession.FindLocalServer();
             });
             if (!adoperationResult.Succeeded)
             {
                 RmsClientManagerLog.Tracer.TraceError <Exception>(0L, "Failed to get the local server.  Unable to reload the log configuration. Error {0}", adoperationResult.Exception);
             }
             else
             {
                 RmsClientManagerLog.Configure(localServer);
             }
         }
     }
     finally
     {
         Interlocked.Decrement(ref RmsClientManagerLog.notificationHandlerCount);
     }
 }
        protected virtual void UpdateRecipientSyncStateValueInAD(RecipientSyncOperation operation)
        {
            if (this.updateConnection == null)
            {
                ADObjectId        rootId            = null;
                ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    PooledLdapConnection readConnection = this.ConfigSession.GetReadConnection(this.sourceConnection.Fqdn, ref rootId);
                    this.updateConnection = new Connection(readConnection, EdgeSyncSvc.EdgeSync.AppConfig);
                }, 3);
                if (!adoperationResult.Succeeded)
                {
                    ExTraceGlobals.TargetConnectionTracer.TraceError <string>((long)this.GetHashCode(), "Failed to get AD connection to update SyncState because of {0}", adoperationResult.Exception.Message);
                    throw new ExDirectoryException("Failed to get AD connection to update SyncState", adoperationResult.Exception);
                }
            }
            byte[]        array   = RecipientSyncState.SerializeRecipientSyncState(operation.RecipientSyncState);
            ModifyRequest request = new ModifyRequest(operation.DistinguishedName, DirectoryAttributeOperation.Replace, "msExchExternalSyncState", new object[]
            {
                array
            });

            this.updateConnection.SendRequest(request);
            ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>((long)this.GetHashCode(), "Successfully updated SyncState in AD for {0}", operation.DistinguishedName);
            base.LogSession.LogEvent(EdgeSyncLoggingLevel.Low, EdgeSyncEvent.TargetConnection, operation.DistinguishedName, "Successfully synced to MSERV and updated SyncState");
        }
Пример #11
0
        private bool TrySetExternalOrgId(OrganizationId orgId)
        {
            if (orgId.Equals(OrganizationId.ForestWideOrgId))
            {
                this.externalOrganizationIdString = string.Empty;
                return(true);
            }
            ExchangeConfigurationUnit configUnitPassedToDelegate = null;
            Guid empty = Guid.Empty;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                IConfigurationSession configurationSession = DirectorySessionFactory.Default.CreateTenantConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(orgId), 241, "TrySetExternalOrgId", "f:\\15.00.1497\\sources\\dev\\infoworker\\src\\common\\MessageTracking\\DirectoryContext.cs");
                configUnitPassedToDelegate = configurationSession.Read <ExchangeConfigurationUnit>(orgId.ConfigurationUnit);
            });

            if (!adoperationResult.Succeeded)
            {
                TraceWrapper.SearchLibraryTracer.TraceDebug <string, Exception>(0, "Failed to get ExternalOrgId from AD. {0} Error: {1}", (adoperationResult.ErrorCode == ADOperationErrorCode.PermanentError) ? "Permanent" : "Retriable", adoperationResult.Exception);
                return(false);
            }
            if (configUnitPassedToDelegate == null || !Guid.TryParse(configUnitPassedToDelegate.ExternalDirectoryOrganizationId, out empty))
            {
                TraceWrapper.SearchLibraryTracer.TraceDebug(0, "Failed read ExternalOrgId from AD Session", new object[0]);
                return(false);
            }
            this.externalOrganizationIdString = empty.ToString();
            return(true);
        }
Пример #12
0
        protected void InternalRead(IConfigurationSession session, bool force = false)
        {
            T newData = default(T);
            OrganizationProperties organizationProperties;

            if (!OrganizationPropertyCache.TryGetOrganizationProperties(this.organizationId, out organizationProperties) || force || !organizationProperties.TryGetValue <T>(out newData))
            {
                int retryCount = 3;
                ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    newData = this.Read(session);
                }, retryCount);
                if (adoperationResult.Exception != null)
                {
                    CachedOrganizationConfiguration.Logger.LogEvent(InfoWorkerEventLogConstants.Tuple_UnableToReadConfigurationFromAD, adoperationResult.Exception.GetType().FullName, new object[]
                    {
                        typeof(T).Name,
                        adoperationResult.Exception.GetType().FullName,
                        adoperationResult.Exception.Message
                    });
                    throw adoperationResult.Exception;
                }
                if (adoperationResult.Succeeded && organizationProperties != null)
                {
                    organizationProperties.SetValue <T>(newData);
                }
            }
            this.data = newData;
        }
Пример #13
0
        public static ADRawEntry GetSender(IRecipientSession session, ProxyAddress sendingAs, ADPropertyDefinition[] properties)
        {
            ADRawEntry        sender            = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                sender = session.FindByProxyAddress(sendingAs, properties);
            });

            if (!adoperationResult.Succeeded)
            {
                if (adoperationResult.Exception is NonUniqueRecipientException)
                {
                    string message = Strings.descMailTipsSenderNotUnique(sendingAs.ToString());
                    throw new SenderNotUniqueException(message);
                }
                throw adoperationResult.Exception;
            }
            else
            {
                if (sender == null)
                {
                    string message2 = Strings.descMailTipsSenderNotFound(sendingAs.ToString());
                    throw new SenderNotFoundException(message2);
                }
                return(sender);
            }
        }
        // Token: 0x060000BA RID: 186 RVA: 0x0000843C File Offset: 0x0000663C
        private bool CleanUpMangledDevices(List <MobileDevice> mobileDevices, out int noOfDevicesRemoved)
        {
            noOfDevicesRemoved = 0;
            ExDateTime utcNow = ExDateTime.UtcNow;

            for (int i = mobileDevices.Count - 1; i >= 0; i--)
            {
                MobileDevice device = mobileDevices[i];
                if (ADDeviceManager.DnIsMangled(device.Name) || ADDeviceManager.DnIsMangled(device.DeviceId))
                {
                    ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                    {
                        this.session.Delete(device);
                    });
                    if (!adoperationResult.Succeeded)
                    {
                        AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, null, "Exception occurred during AD Operation during . Message:{0}", adoperationResult.Exception.Message);
                    }
                    noOfDevicesRemoved++;
                    mobileDevices.RemoveAt(i);
                }
                TimeSpan t = ExDateTime.UtcNow.Subtract(utcNow);
                if (t >= GlobalSettings.MaxCleanUpExecutionTime)
                {
                    AirSyncDiagnostics.TraceDebug <int, double>(ExTraceGlobals.RequestsTracer, null, "Done Cleaning up stale devices. DevicesCleaned:{0}, ExecutionTime(in ms):{1}", noOfDevicesRemoved, t.TotalMilliseconds);
                    return(false);
                }
            }
            return(true);
        }
        // Token: 0x06000007 RID: 7 RVA: 0x0000254C File Offset: 0x0000074C
        protected override bool TryReadServerConfig()
        {
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                TransportADNotificationAdapter.Instance.RegisterForMsExchangeTransportServiceDeletedEvents();
            }, 0);

            if (!adoperationResult.Succeeded)
            {
                TransportService.logger.LogEvent(TransportEventLogConstants.Tuple_FailedToRegisterForDeletedObjectsNotification, null, new object[]
                {
                    adoperationResult.Exception
                });
                ExTraceGlobals.ServiceTracer.TraceError <Exception>(0L, "Failed to register for Deleted object notifications. Details {0}", adoperationResult.Exception);
                ProcessManagerService.StopService();
            }
            this.readingConfigOnStart = true;
            ADOperationResult adoperationResult2;
            bool flag = this.ReadServerConfig(out adoperationResult2);

            this.readingConfigOnStart = false;
            if (!flag)
            {
                this.GenerateConfigFailureEventLog(adoperationResult2.Exception);
                return(false);
            }
            return(true);
        }
        private static PolicyData LoadDefaultPolicySetting(IConfigurationSession scopedSession, ProtocolLogger protocolLogger)
        {
            MobileMailboxPolicy[] mobileMaiboxPolicies = null;
            ADOperationResult     adoperationResult    = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                mobileMaiboxPolicies = scopedSession.Find <MobileMailboxPolicy>(scopedSession.GetOrgContainerId().GetDescendantId(new ADObjectId("CN=Mobile Mailbox Policies")), QueryScope.OneLevel, ADNotificationManager.filter, ADNotificationManager.sortBy, 3);
            });

            if (!adoperationResult.Succeeded)
            {
                AirSyncDiagnostics.TraceDebug <ADObjectId, string>(ExTraceGlobals.RequestsTracer, null, "Exception occurred during AD Operation during LoadDefaultPolicySettings for OrgID {0}. Message - {1}", scopedSession.GetOrgContainerId(), adoperationResult.Exception.Message);
                throw adoperationResult.Exception;
            }
            protocolLogger.SetValue(ProtocolLoggerData.DomainController, scopedSession.LastUsedDc);
            if (mobileMaiboxPolicies == null || mobileMaiboxPolicies.Length == 0)
            {
                AirSyncDiagnostics.TraceInfo <ADObjectId>(ExTraceGlobals.RequestsTracer, null, "no default policy setting found for OrgId {0}", scopedSession.GetOrgContainerId());
                return(null);
            }
            AirSyncDiagnostics.TraceInfo <ADObjectId>(ExTraceGlobals.RequestsTracer, null, "LoadDefaultPolicySetting from AD.Policy Id {0}", mobileMaiboxPolicies[0].Id);
            if (mobileMaiboxPolicies.Length > 1)
            {
                ADNotificationManager.HandleMultipleDefaultPolicies(mobileMaiboxPolicies, scopedSession.GetOrgContainerId(), protocolLogger);
                protocolLogger.SetValue(ProtocolLoggerData.DomainController, scopedSession.LastUsedDc);
            }
            return(ADNotificationManager.AddPolicyToCache(mobileMaiboxPolicies[0], scopedSession.SessionSettings.CurrentOrganizationId.PartitionId));
        }
        private bool PopulateCache()
        {
            OrganizationBaseCache.Tracer.TraceDebug <OrganizationId>((long)this.GetHashCode(), "Searching for AcceptedDomain instances associated with OrganizationId '{0}'", base.OrganizationId);
            AcceptedDomain[]  acceptedDomains   = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                acceptedDomains = ((ITenantConfigurationSession)this.Session).FindAllAcceptedDomainsInOrg(this.OrganizationId.ConfigurationUnit);
            });

            if (!adoperationResult.Succeeded)
            {
                OrganizationBaseCache.Tracer.TraceError <OrganizationId, Exception>((long)this.GetHashCode(), "Unable to find AcceptedDomain instances associated with the OrganizationId '{0}' due to exception: {1}", base.OrganizationId, adoperationResult.Exception);
                throw adoperationResult.Exception;
            }
            if (acceptedDomains == null || acceptedDomains.Length == 0)
            {
                OrganizationBaseCache.Tracer.TraceError <OrganizationId>((long)this.GetHashCode(), "Unable to find any AcceptedDomain associated with the OrganizationId '{0}'", base.OrganizationId);
                return(adoperationResult.Succeeded);
            }
            Dictionary <string, AuthenticationType> dictionary = new Dictionary <string, AuthenticationType>(acceptedDomains.Length, StringComparer.OrdinalIgnoreCase);

            for (int i = 0; i < acceptedDomains.Length; i++)
            {
                dictionary[acceptedDomains[i].DomainName.Domain] = acceptedDomains[i].RawAuthenticationType;
            }
            this.namespaceAuthenticationTypeHash = dictionary;
            OrganizationBaseCache.Tracer.TraceDebug <EnumerableTracer <string> >((long)this.GetHashCode(), "Found the following Accepted Domains: {0}", new EnumerableTracer <string>(this.namespaceAuthenticationTypeHash.Keys));
            return(adoperationResult.Succeeded);
        }
 protected override void InternalDispose(bool disposing)
 {
     if (disposing)
     {
         if (this.periodicTimer != null)
         {
             this.periodicTimer.Dispose(true);
             lock (this.periodicTimerLock)
             {
                 this.periodicTimer = null;
             }
         }
         lock (this.notificationLock)
         {
             if (this.adNotificationCookie != null)
             {
                 ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                 {
                     ADNotificationAdapter.UnregisterChangeNotification(this.adNotificationCookie);
                 }, 2);
                 if (!adoperationResult.Succeeded)
                 {
                     this.LogFailure(ADConfigurationLoader <ADConfigType, StateType> .FailureLocation.ADNotificationRegistration, adoperationResult.Exception);
                 }
                 this.adNotificationCookie = null;
             }
             this.hasUnregisteredNotification = true;
         }
     }
 }
        private void ProcessAllFederationTrusts()
        {
            FederationTrust[] federationTrusts = null;
            this.Context.Logger.Log(MigrationEventType.Information, "Retrieving Federation Trust Configuration", new object[0]);
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                ADObjectId orgContainerId = this.session.GetOrgContainerId();
                ADObjectId descendantId   = orgContainerId.GetDescendantId(FederationTrust.FederationTrustsContainer);
                federationTrusts          = this.session.Find <FederationTrust>(descendantId, QueryScope.SubTree, null, null, ADGenericPagedReader <FederationTrust> .DefaultPageSize);
            });

            if (adoperationResult != ADOperationResult.Success)
            {
                this.Context.Logger.Log(MigrationEventType.Warning, "Unable to read Federation Trusts, result = {0}", new object[]
                {
                    adoperationResult.ErrorCode.ToString()
                });
                if (adoperationResult.Exception != null && adoperationResult.Exception is TransientException)
                {
                    throw adoperationResult.Exception;
                }
                return;
            }
            else
            {
                if (federationTrusts == null)
                {
                    this.Context.Logger.Log(MigrationEventType.Information, "No Federation Trusts found", new object[0]);
                    return;
                }
                foreach (FederationTrust federationTrust in federationTrusts)
                {
                    if (this.StopEvent.WaitOne(0, false))
                    {
                        return;
                    }
                    this.Context.Logger.Log(MigrationEventType.Information, "Processing Federation Trust {0}", new object[]
                    {
                        federationTrust.Name
                    });
                    if (federationTrust.TokenIssuerMetadataEpr == null)
                    {
                        this.Context.Logger.LogTerseEvent(MigrationEventType.Error, MSExchangeAuthAdminEventLogConstants.Tuple_InvalidTrustedIssuerConfiguration, new string[]
                        {
                            federationTrust.Name
                        });
                    }
                    else if (this.ProcessFederationTrust(federationTrust))
                    {
                        this.session.Save(federationTrust);
                        this.Context.Logger.LogTerseEvent(MigrationEventType.Information, MSExchangeAuthAdminEventLogConstants.Tuple_TrustedIssuerUpdated, new string[]
                        {
                            federationTrust.Name
                        });
                    }
                }
                return;
            }
        }
Пример #20
0
        public static bool TryLoadLocalSiteTopology(string domainController, out ReplicationTopology topology, out Exception exception)
        {
            topology  = null;
            exception = null;
            ITopologyConfigurationSession session = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(domainController, true, ConsistencyMode.PartiallyConsistent, ADSessionSettings.FromRootOrgScopeSet(), 154, "TryLoadLocalSiteTopology", "f:\\15.00.1497\\sources\\dev\\EdgeSync\\src\\Common\\Validation\\ReplicationTopology.cs");
            ADSite localSite = null;
            EdgeSyncServiceConfig edgeSyncServiceConfig = null;
            ADOperationResult     adoperationResult     = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                localSite = session.GetLocalSite();
                if (localSite == null)
                {
                    throw new ADTransientException(Strings.CannotGetLocalSite);
                }
                edgeSyncServiceConfig = session.Read <EdgeSyncServiceConfig>(localSite.Id.GetChildId("EdgeSyncService"));
            }, 3);

            if (!adoperationResult.Succeeded)
            {
                exception = adoperationResult.Exception;
                return(false);
            }
            if (edgeSyncServiceConfig == null)
            {
                topology = new ReplicationTopology(session, null, localSite, null);
                return(true);
            }
            ReplicationTopology resultTopology = null;

            adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                Server server      = session.FindLocalServer();
                resultTopology     = new ReplicationTopology(session, server, localSite, edgeSyncServiceConfig);
                QueryFilter filter = Util.BuildServerFilterForSite(localSite.Id);
                ADPagedReader <Server> adpagedReader = session.FindPaged <Server>(null, QueryScope.SubTree, filter, null, 0);
                resultTopology.siteEdgeServers.Clear();
                resultTopology.siteHubServers.Clear();
                foreach (Server server2 in adpagedReader)
                {
                    if (server2.IsEdgeServer)
                    {
                        resultTopology.siteEdgeServers.Add(server2);
                    }
                    if (server2.IsHubTransportServer)
                    {
                        resultTopology.siteHubServers.Add(server2);
                    }
                }
            }, 3);
            if (!adoperationResult.Succeeded)
            {
                exception = adoperationResult.Exception;
                return(false);
            }
            topology = resultTopology;
            return(true);
        }
 // Token: 0x06000E4C RID: 3660 RVA: 0x00055DB0 File Offset: 0x00053FB0
 private bool ApplyPolicy(MailboxSession mailboxSession, SharingPolicy policy)
 {
     using (MailboxData mailboxData = new MailboxData(mailboxSession, policy))
     {
         if (mailboxData.MaxAnonymousDetailLevel == 0)
         {
             SharingPolicyAssistant.Tracer.TraceDebug <IExchangePrincipal>((long)this.GetHashCode(), "Anonymous access is disabled. Clearing AD SharingAnonymousIdentities entries for user:{0}", mailboxData.MailboxSession.MailboxOwner);
             ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
             {
                 ADUser aduser = mailboxData.RecipientSession.Read(mailboxData.MailboxSession.MailboxOwner.ObjectId) as ADUser;
                 aduser.SharingAnonymousIdentities.Clear();
                 mailboxData.RecipientSession.Save(aduser);
             }, 3);
             if (!adoperationResult.Succeeded)
             {
                 SharingPolicyAssistant.Tracer.TraceError <IExchangePrincipal, Exception>((long)this.GetHashCode(), "Failed to clear AD SharingAnonymousIdentities entries for user:{0},  Error: {1}", mailboxData.MailboxSession.MailboxOwner, adoperationResult.Exception);
                 return(false);
             }
         }
         using (Folder folder = Folder.Bind(mailboxSession, DefaultFolderType.Configuration))
         {
             using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.DeepTraversal, null, null, SharingPolicyAssistant.FolderQueryProperties))
             {
                 for (;;)
                 {
                     object[][] rows = queryResult.GetRows(64);
                     if (rows == null || rows.Length == 0)
                     {
                         break;
                     }
                     foreach (object[] array2 in rows)
                     {
                         string  arg     = array2[1] as string;
                         StoreId storeId = array2[0] as StoreId;
                         if (storeId == null)
                         {
                             SharingPolicyAssistant.Tracer.TraceError <IExchangePrincipal, object, string>((long)this.GetHashCode(), "{0}: cannot process folder row due unknown id: {1} - {2}", mailboxSession.MailboxOwner, array2[0], arg);
                         }
                         else
                         {
                             using (FolderData folderData = new FolderData(mailboxSession, storeId))
                             {
                                 this.ApplyPolicyForExternalSharing(array2, mailboxData, folderData);
                                 this.ApplyPolicyForAnonymousSharing(array2, mailboxData, folderData);
                                 if (folderData.IsChanged)
                                 {
                                     folderData.Folder.Save();
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return(true);
 }
        private static void LoadAutoBlockThresholds()
        {
            bool flag = false;

            try
            {
                object obj;
                Monitor.Enter(obj = ADNotificationManager.startLock, ref flag);
                DeviceAutoBlockThreshold[] newValues = new DeviceAutoBlockThreshold[Enum.GetValues(typeof(AutoblockThresholdType)).Length];
                bool flag2 = false;
                ActiveSyncDeviceAutoblockThreshold[] thresholds = null;
                try
                {
                    ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                    {
                        thresholds = ADNotificationManager.topoSession.Find <ActiveSyncDeviceAutoblockThreshold>(ADNotificationManager.topoSession.GetOrgContainerId().GetDescendantId(new ADObjectId("CN=Mobile Mailbox Policies")), QueryScope.OneLevel, null, ADNotificationManager.thresholdSortBy, newValues.Length);
                    });
                    if (!adoperationResult.Succeeded)
                    {
                        AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, null, "Exception occurred during AD Operation during LoadAutoBlockThresholds. Exception Message -{0}", adoperationResult.Exception.Message);
                        throw adoperationResult.Exception;
                    }
                    foreach (ActiveSyncDeviceAutoblockThreshold activeSyncDeviceAutoblockThreshold in thresholds)
                    {
                        if (activeSyncDeviceAutoblockThreshold.BehaviorType < (AutoblockThresholdType)newValues.Length)
                        {
                            newValues[(int)activeSyncDeviceAutoblockThreshold.BehaviorType] = new DeviceAutoBlockThreshold(activeSyncDeviceAutoblockThreshold);
                        }
                    }
                    flag2 = true;
                }
                finally
                {
                    if (ADNotificationManager.autoBlockThresholds == null || flag2)
                    {
                        for (int j = 0; j < newValues.Length; j++)
                        {
                            if (newValues[j] == null)
                            {
                                newValues[j] = new DeviceAutoBlockThreshold((AutoblockThresholdType)j);
                            }
                        }
                        ADNotificationManager.autoBlockThresholds = new ADNotificationManager.DeviceAutoblockThresholdInfo(newValues, ExDateTime.UtcNow);
                    }
                }
            }
            finally
            {
                if (flag)
                {
                    object obj;
                    Monitor.Exit(obj);
                }
            }
        }
Пример #23
0
 private bool GetExternalDirectoryOrganizationIdToLog(ADObject instance, out Guid externalDirectoryOrganizationId)
 {
     externalDirectoryOrganizationId = Guid.Empty;
     if (instance != null && instance.OrganizationId != OrganizationId.ForestWideOrgId)
     {
         ADOperationResult externalDirectoryOrganizationId2 = SystemConfigurationTasksHelper.GetExternalDirectoryOrganizationId(this.dataSession, instance.OrganizationId, out externalDirectoryOrganizationId);
         TenantSettingSyncLogGenerator.Instance.AddEventLogOnADException(externalDirectoryOrganizationId2);
         return(externalDirectoryOrganizationId2.Succeeded && externalDirectoryOrganizationId != Guid.Empty);
     }
     return(false);
 }
Пример #24
0
        private LocalLongFullPath GetAgentLogPath(TransportService transportService)
        {
            GetAgentLog.< > c__DisplayClass3 CS$ < > 8__locals1 = new GetAgentLog.< > c__DisplayClass3();
            CS$ < > 8__locals1.session     = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 182, "GetAgentLogPath", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\transport\\AgentLog\\GetAgentLog.cs");
            CS$ < > 8__locals1.localServer = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                CS$ < > 8__locals1.localServer = CS$ < > 8__locals1.session.FindLocalServer();
            });

            if (!adoperationResult.Succeeded)
            {
                base.WriteError(adoperationResult.Exception, ErrorCategory.ReadError, null);
            }
            if (transportService == TransportService.FrontEnd)
            {
                FrontendTransportServer[] feServer = null;
                adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    feServer = (FrontendTransportServer[])CS$ < > 8__locals1.session.Find <FrontendTransportServer>(null, CS$ < > 8__locals1.localServer.Id, true, null);
                });
                if (!adoperationResult.Succeeded)
                {
                    base.WriteError(adoperationResult.Exception, ErrorCategory.ReadError, null);
                }
                if (feServer == null || feServer.Length == 0)
                {
                    base.WriteError(new LocalServerNotFoundException(string.Format("Local server does not contain transport service {0}", new object[0])), ErrorCategory.InvalidOperation, null);
                }
                return(feServer[0].AgentLogPath);
            }
            if (transportService != TransportService.MailboxDelivery && transportService != TransportService.MailboxSubmission)
            {
                return(CS$ < > 8__locals1.localServer.AgentLogPath);
            }
            MailboxTransportServer[] mbxServer = null;
            adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                mbxServer = (MailboxTransportServer[])CS$ < > 8__locals1.session.Find <MailboxTransportServer>(null, CS$ < > 8__locals1.localServer.Id, true, null);
            });
            if (!adoperationResult.Succeeded)
            {
                base.WriteError(adoperationResult.Exception, ErrorCategory.ReadError, null);
            }
            if (mbxServer == null || mbxServer.Length == 0)
            {
                base.WriteError(new LocalServerNotFoundException(string.Format("Local server does not contain transport service {0}", new object[0])), ErrorCategory.InvalidOperation, null);
            }
            if (transportService == TransportService.MailboxDelivery)
            {
                return(mbxServer[0].MailboxDeliveryAgentLogPath);
            }
            return(mbxServer[0].MailboxDeliveryAgentLogPath);
        }
Пример #25
0
        public static ADOperationResult TryRegisterNotifications(Func <ADObjectId> baseDNGetter, ADNotificationCallback callback, TransportADNotificationAdapter.TransportADNotificationRegister registerDelegate, int retryCount, out ADNotificationRequestCookie cookie)
        {
            ADNotificationRequestCookie adCookie = null;
            ADOperationResult           result   = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                ADObjectId root = (baseDNGetter == null) ? null : baseDNGetter();
                adCookie        = registerDelegate(root, callback);
            }, retryCount);

            cookie = adCookie;
            return(result);
        }
Пример #26
0
        private void Initialize()
        {
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                this.localServer = this.rootOrgConfigSession.FindLocalServer();
            }, 3);

            if (adoperationResult.Succeeded)
            {
                this.initialized = true;
            }
        }
Пример #27
0
        // Token: 0x0600018B RID: 395 RVA: 0x00007A68 File Offset: 0x00005C68
        public void Init()
        {
            ExTraceGlobals.DatabaseManagerTracer.TraceDebug <DatabaseManager>((long)this.GetHashCode(), "{0}: Really starting", this);
            AIBreadcrumbs.DatabaseStatusTrail.Drop("Init Starting. Waiting on lock.");
            bool flag = false;

            try
            {
                Monitor.Enter(this, ref flag);
                AIBreadcrumbs.DatabaseStatusTrail.Drop("Init startup progressing. Lock acquired.");
                SecurityIdentifier exchangeServersSid = null;
                ADOperationResult  adoperationResult  = ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    IRootOrganizationRecipientSession rootOrganizationRecipientSession = DirectorySessionFactory.Default.CreateRootOrgRecipientSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 514, "Init", "f:\\15.00.1497\\sources\\dev\\assistants\\src\\Assistants\\DatabaseManager.cs");
                    exchangeServersSid = rootOrganizationRecipientSession.GetExchangeServersUsgSid();
                });
                if (exchangeServersSid == null)
                {
                    AIBreadcrumbs.DatabaseStatusTrail.Drop("Database Manager unable to contact AD.");
                    TransientServerException ex = new TransientServerException(adoperationResult.Exception);
                    ExTraceGlobals.DatabaseManagerTracer.TraceDebug <DatabaseManager, ADOperationErrorCode, TransientServerException>((long)this.GetHashCode(), "{0}: Unable to contact AD. Will not continue to start at this time. Code: {1}, Exception: {2}", this, adoperationResult.ErrorCode, ex);
                    throw ex;
                }
                if (this.startState != DatabaseManager.StartState.Started)
                {
                    ExTraceGlobals.DatabaseManagerTracer.TraceDebug <DatabaseManager, DatabaseManager.StartState>((long)this.GetHashCode(), "{0}: Init when not started: {1}", this, this.startState);
                    return;
                }
                this.performanceCountersTotal = new PerformanceCountersPerDatabaseInstance(this.serviceName + "-Total", null);
                this.performanceCountersTotal.Reset();
                if (this.timeBasedDriverManager != null)
                {
                    this.timeBasedDriverManager.Start(exchangeServersSid);
                }
                this.databaseStatusTimer = new Timer(new TimerCallback(this.CheckDatabaseStatusTimerProc));
                this.databaseStatusTimer.Change(TimeSpan.Zero, DatabaseManager.DatabaseStatusPollingInterval);
                base.TracePfd("PFD AIS {0} {1}: Started", new object[]
                {
                    23383,
                    this
                });
                this.startState = DatabaseManager.StartState.Initialized;
            }
            finally
            {
                if (flag)
                {
                    Monitor.Exit(this);
                }
            }
            AIBreadcrumbs.DatabaseStatusTrail.Drop("Database manager startup completed.");
        }
Пример #28
0
        public static Exception RunADOperation(Action adOperation, int retryCount = 2)
        {
            Exception         result            = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                adOperation();
            }, retryCount);

            if (!adoperationResult.Succeeded)
            {
                result = adoperationResult.Exception;
            }
            return(result);
        }
        // Token: 0x06000012 RID: 18 RVA: 0x00002664 File Offset: 0x00000864
        protected override void OnStartInternal(string[] args)
        {
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(new ADOperation(this.OnStartInternalHelper));

            if (!adoperationResult.Succeeded)
            {
                MailboxTransportSubmissionService.StoreDriverTracer.ServiceTracer.TraceFail(MailboxTransportSubmissionService.StoreDriverTracer.MessageProbeActivityId, 0L, ("AD Operation Failed. The Mailbox Transport Submission Service will be stopped." + adoperationResult.Exception == null) ? string.Empty : adoperationResult.Exception.Message);
                MailboxTransportSubmissionEventLogger.LogEvent(MSExchangeSubmissionEventLogConstants.Tuple_SubmissionServiceStartFailure, null, new object[]
                {
                    adoperationResult.Exception
                });
                base.Stop();
            }
        }
Пример #30
0
        private IEnumerable <RecipientData> LookupRecipientsBatchInternal(EmailAddress[] emailAddressArray, int startIndex, int size, ProxyAddress[] proxyAddressArray, List <int> indexList)
        {
            Result <ADRawEntry>[] resultsArray      = null;
            ADOperationResult     adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                resultsArray = this.adRecipientSession.FindByProxyAddresses(proxyAddressArray, this.propertyDefinitionArray);
            });

            if (adoperationResult.Exception == null)
            {
                return(this.ProcessResults(emailAddressArray, startIndex, size, resultsArray, indexList));
            }
            return(this.HandleErrorFromRecipientLookup(adoperationResult.Exception, emailAddressArray, startIndex, proxyAddressArray.Length, 42812U));
        }