internal static ThrottlingPolicy ReadThrottlingPolicyFromAD(IConfigurationSession session, object id, Func <IConfigurationSession, object, ThrottlingPolicy> getPolicy)
        {
            ThrottlingPolicy  policy            = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                session.SessionSettings.IsSharedConfigChecked = true;
                policy = getPolicy(session, id);
            });

            if (!adoperationResult.Succeeded && adoperationResult.Exception != null)
            {
                ThrottlingPolicyCache.Tracer.TraceError <string, string, object>(0L, "Encountered exception reading throttling policy.  Exception Class: {0}, Message: {1}, Key: {2}", adoperationResult.Exception.GetType().FullName, adoperationResult.Exception.Message, id);
            }
            if (policy != null)
            {
                ValidationError[] array = policy.Validate();
                if (array != null && array.Length > 0)
                {
                    Globals.LogEvent(DirectoryEventLogConstants.Tuple_FailedToReadThrottlingPolicy, id.ToString(), new object[]
                    {
                        id,
                        array[0].Description
                    });
                    policy = null;
                }
            }
            return(policy);
        }
 internal static bool RemoveMserveEntry(string address, int value)
 {
     try
     {
         if (MServDirectorySession.RemoveMserveEntryWithExactValue(address, value))
         {
             return(true);
         }
     }
     catch (MServPermanentException)
     {
         ExTraceGlobals.MServTracer.TraceWarning <string, int>(0L, "Could not remove {0} with PartnerId {1}, will read the actual value now", address, value);
         value = MServDirectorySession.ReadMservEntry(address);
         if (value == -1)
         {
             ExTraceGlobals.MServTracer.TraceWarning <string>(0L, "Entry {0} does not exist, no need to remove", address);
             return(true);
         }
     }
     if (!MServDirectorySession.RemoveMserveEntryWithExactValue(address, value))
     {
         Globals.LogEvent(DirectoryEventLogConstants.Tuple_CannotDeleteMServEntry, address, new object[]
         {
             address
         });
         return(false);
     }
     return(true);
 }
Esempio n. 3
0
 internal ADSessionSettings GetTenantScopedADSessionSettingsServiceOnly()
 {
     if (this.externalDirectoryOrganizationId != null)
     {
         ExTraceGlobals.GetConnectionTracer.TraceDebug <string>(0L, "FromTenantPartitionHint(): Partition hint '{0}' has externalDirectoryOrganizationId initialized, no need to lookup", this.ToString());
         if (this.externalDirectoryOrganizationId == TenantPartitionHint.ExternalDirectoryOrganizationIdForRootOrg)
         {
             return(ADSessionSettings.FromRootOrgScopeSet());
         }
         return(ADSessionSettings.FromExternalDirectoryOrganizationId(this.externalDirectoryOrganizationId.Value));
     }
     else
     {
         ADSessionSettings           sessionSettings            = ADSessionSettings.FromAllTenantsPartitionId(this.partitionId);
         ITenantConfigurationSession tenantConfigurationSession = DirectorySessionFactory.Default.CreateTenantConfigurationSession(ConsistencyMode.PartiallyConsistent, sessionSettings, 442, "GetTenantScopedADSessionSettingsServiceOnly", "f:\\15.00.1497\\sources\\dev\\data\\src\\directory\\TenantPartitionHint.cs");
         ExTraceGlobals.GetConnectionTracer.TraceDebug <TenantPartitionHint>(0L, "FromTenantPartitionHint(): Partition hint '{0}' has externalDirectoryOrganizationId not initialized, need to read this property from AD, looking up", this);
         ExchangeConfigurationUnit exchangeConfigurationUnitByName = tenantConfigurationSession.GetExchangeConfigurationUnitByName(this.tenantName);
         if (exchangeConfigurationUnitByName != null)
         {
             ExTraceGlobals.GetConnectionTracer.TraceDebug <TenantPartitionHint>(0L, "FromTenantPartitionHint(): Partition hint '{0}' has PartitionId and tenantName initialized, reading this OrganizationId property from CU", this);
             return(ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(exchangeConfigurationUnitByName.OrganizationId));
         }
         ExTraceGlobals.GetConnectionTracer.TraceDebug <TenantPartitionHint>(0L, "FromTenantPartitionHint(): Partition hint '{0}' has partitionId and tenantName initialized, but failed to find this tenant's CU", this);
         Globals.LogEvent(DirectoryEventLogConstants.Tuple_CannotResolveExternalDirectoryOrganizationId, this.tenantName, new object[]
         {
             DirectoryStrings.CannotResolveTenantName(this.tenantName),
             Environment.StackTrace
         });
         throw new CannotResolveExternalDirectoryOrganizationIdException(DirectoryStrings.CannotResolveTenantName(this.tenantName));
     }
 }
Esempio n. 4
0
        // Token: 0x0600035F RID: 863 RVA: 0x000125A0 File Offset: 0x000107A0
        public static bool TryReadConfiguration <T>(ADConfigurationReader <T> configurationReader, out T result, int retryCount, out ADOperationResult operationStatus)
        {
            if (configurationReader == null)
            {
                throw new ArgumentNullException("configurationReader");
            }
            if (retryCount < 0)
            {
                throw new ArgumentOutOfRangeException("retryCount", "Number of retries must be equal to or larger than zero.");
            }
            result = default(T);
            T objectReturned = result;

            operationStatus = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                objectReturned = configurationReader();
            }, retryCount);
            result = objectReturned;
            if (operationStatus.Succeeded)
            {
                return(result != null);
            }
            if (operationStatus.Exception is ComputerNameNotCurrentlyAvailableException)
            {
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_FIND_LOCAL_SERVER_FAILED, Environment.MachineName, new object[]
                {
                    operationStatus.Exception.Message,
                    Environment.MachineName
                });
            }
            return(false);
        }
Esempio n. 5
0
 private void UpdateConstraintDictionary(List <ADPropertyDefinition> propertiesToRead)
 {
     if (propertiesToRead.Count > 0)
     {
         this.ReadPropertiesFromAD(propertiesToRead, false);
         Dictionary <ADSchemaDataProvider.PropertyKey, PropertyDefinitionConstraint[]> dictionary = new Dictionary <ADSchemaDataProvider.PropertyKey, PropertyDefinitionConstraint[]>(propertiesToRead.Count);
         for (int i = 0; i < propertiesToRead.Count; i++)
         {
             ADPropertyDefinition    adpropertyDefinition = propertiesToRead[i];
             ADSchemaAttributeObject schemaObject;
             if (this.schemaAttributeObjectDictionary.TryGetValue(adpropertyDefinition.LdapDisplayName, out schemaObject))
             {
                 PropertyDefinitionConstraint[] value = this.GeneratePropertyConstraints(schemaObject, adpropertyDefinition);
                 dictionary[ADSchemaDataProvider.PropertyKey.GetPropertyKey(adpropertyDefinition)] = value;
             }
             else
             {
                 Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_CONSTRAINT_READ_FAILED, null, new object[]
                 {
                     adpropertyDefinition.ToString(),
                     adpropertyDefinition.LdapDisplayName
                 });
             }
         }
         lock (this.constraintDictionary)
         {
             Dictionary <ADSchemaDataProvider.PropertyKey, PropertyDefinitionConstraint[]> dictionary2 = new Dictionary <ADSchemaDataProvider.PropertyKey, PropertyDefinitionConstraint[]>(this.constraintDictionary);
             foreach (KeyValuePair <ADSchemaDataProvider.PropertyKey, PropertyDefinitionConstraint[]> keyValuePair in dictionary)
             {
                 dictionary2[keyValuePair.Key] = keyValuePair.Value;
             }
             this.constraintDictionary = dictionary2;
         }
     }
 }
        // Token: 0x06000DCB RID: 3531 RVA: 0x0003F978 File Offset: 0x0003DB78
        internal static PooledLdapConnection CreateOneTimeConnection(NetworkCredential networkCredential, ADServerInfo serverInfo, LocatorFlags connectionFlags = LocatorFlags.None)
        {
            string arg = "<null>\\<null>";

            if (networkCredential != null)
            {
                arg = networkCredential.Domain + "\\" + networkCredential.UserName;
            }
            else
            {
                using (WindowsIdentity current = WindowsIdentity.GetCurrent())
                {
                    if (current.ImpersonationLevel == TokenImpersonationLevel.Delegation || current.ImpersonationLevel == TokenImpersonationLevel.Impersonation)
                    {
                        arg = current.Name;
                    }
                }
            }
            ExTraceGlobals.ConnectionTracer.TraceDebug <string, string>(0L, "LdapConnectionPool::CreateOneTimeConnection - opening new ONE-TIME PooledLdapConnection to {0} as {1}", serverInfo.FqdnPlusPort, arg);
            ADProviderPerf.AddDCInstance(serverInfo.Fqdn);
            ADServerRole         role = (serverInfo.Port == 389) ? ADServerRole.DomainController : ADServerRole.GlobalCatalog;
            bool                 flag = false;
            PooledLdapConnection pooledLdapConnection = null;
            PooledLdapConnection result;

            try
            {
                pooledLdapConnection = new PooledLdapConnection(serverInfo, role, false, networkCredential);
                if (LocatorFlags.None != connectionFlags)
                {
                    pooledLdapConnection.SessionOptions.LocatorFlag |= connectionFlags;
                }
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_NEW_CONNECTION, null, new object[]
                {
                    serverInfo.Fqdn,
                    serverInfo.Port,
                    string.Empty
                });
                pooledLdapConnection.BindWithRetry(3);
                pooledLdapConnection.SetNamingContexts();
                flag   = true;
                result = pooledLdapConnection;
            }
            catch (LdapException ex)
            {
                throw new ADTransientException(DirectoryStrings.ExceptionCreateLdapConnection(serverInfo.FqdnPlusPort, ex.Message, (uint)ex.ErrorCode), ex);
            }
            finally
            {
                if (!flag && pooledLdapConnection != null)
                {
                    pooledLdapConnection.ReturnToPool();
                }
            }
            return(result);
        }
Esempio n. 7
0
 private void LogRootDSEReadFailureAndThrow(string attribute, string server)
 {
     ExTraceGlobals.ADTopologyTracer.TraceError <string, string>(0L, "Could not read {0} from root DSE of {1}", attribute, server);
     Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_ROOTDSE_READ_FAILED, attribute, new object[]
     {
         attribute,
         server
     });
     throw new ADTransientException(DirectoryStrings.ExceptionRootDSE(attribute, server));
 }
Esempio n. 8
0
        private static NativeMethods.InteropDsRolePrimaryDomainInfoBasic GetPrimaryDomainInformation(string serverFqdn = null)
        {
            SafeDsRolePrimaryDomainInfoLevelHandle safeDsRolePrimaryDomainInfoLevelHandle = null;
            int num = 0;

            NativeMethods.InteropDsRolePrimaryDomainInfoBasic result;
            try
            {
                int num2;
                for (;;)
                {
                    num2 = NativeMethods.DsRoleGetPrimaryDomainInformation(serverFqdn, NativeMethods.DsRolePrimaryDomainInfoBasic, out safeDsRolePrimaryDomainInfoLevelHandle);
                    if (num2 == 0)
                    {
                        goto IL_8A;
                    }
                    if (num2 != 1723)
                    {
                        goto IL_73;
                    }
                    if (num >= NativeHelpers.MaxCallRetry)
                    {
                        break;
                    }
                    num++;
                    Thread.Sleep(num * NativeHelpers.CallRetryBaseSleepTime);
                }
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_RPC_SERVER_TOO_BUSY, "DsRoleGetPrimaryDomainInformation", new object[]
                {
                    "DsRoleGetPrimaryDomainInformation",
                    1723
                });
                throw new ADTransientException(DirectoryStrings.ExceptionDomainInfoRpcTooBusy);
IL_73:
                throw new CannotGetDomainInfoException(DirectoryStrings.CannotGetDomainInfo(num2.ToString("X")));
IL_8A:
                NativeMethods.InteropDsRolePrimaryDomainInfoBasic interopDsRolePrimaryDomainInfoBasic = new NativeMethods.InteropDsRolePrimaryDomainInfoBasic();
                Marshal.PtrToStructure(safeDsRolePrimaryDomainInfoLevelHandle.DangerousGetHandle(), interopDsRolePrimaryDomainInfoBasic);
                if (string.IsNullOrEmpty(interopDsRolePrimaryDomainInfoBasic.domainNameDns))
                {
                    throw new CannotGetDomainInfoException(DirectoryStrings.CannotGetUsefulDomainInfo);
                }
                result = interopDsRolePrimaryDomainInfoBasic;
            }
            finally
            {
                if (safeDsRolePrimaryDomainInfoLevelHandle != null)
                {
                    safeDsRolePrimaryDomainInfoLevelHandle.Dispose();
                }
            }
            return(result);
        }
        private static ADServerInfo FindDirectoryServerForForestOrDomain(string domainOrForestFqdn, NetworkCredential credential, bool requireGCs = false)
        {
            StringCollection stringCollection = requireGCs ? NativeHelpers.FindAllGlobalCatalogs(domainOrForestFqdn, null) : NativeHelpers.FindAllDomainControllers(domainOrForestFqdn, null);
            LocalizedString  value            = LocalizedString.Empty;
            LocalizedString  empty            = LocalizedString.Empty;
            string           writableNC       = null;
            string           siteName         = null;

            foreach (string text in stringCollection)
            {
                if (SuitabilityVerifier.IsServerSuitableIgnoreExceptions(text, requireGCs, credential, out writableNC, out siteName, out empty))
                {
                    if (!requireGCs)
                    {
                        Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_GET_DC_FROM_DOMAIN, domainOrForestFqdn, new object[]
                        {
                            domainOrForestFqdn,
                            text
                        });
                    }
                    return(new ADServerInfo(text, domainOrForestFqdn, requireGCs ? 3268 : 389, writableNC, 100, AuthType.Kerberos, true)
                    {
                        SiteName = siteName
                    });
                }
                ExTraceGlobals.TopologyProviderTracer.TraceError(0L, "{0} {1} {2} was found not suitable. Will try to find another {1} in the forest\\domain. Error message: {3}", new object[]
                {
                    domainOrForestFqdn,
                    requireGCs ? "Global Catalog" : "Domain Controller",
                    text,
                    empty
                });
                value = DirectoryStrings.AppendLocalizedStrings(value, empty);
            }
            if (requireGCs)
            {
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_ALL_GC_DOWN, string.Empty, new object[]
                {
                    domainOrForestFqdn,
                    string.Empty
                });
                throw new NoSuitableServerFoundException(DirectoryStrings.ErrorNoSuitableGCInForest(domainOrForestFqdn, value));
            }
            Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_GET_DC_FROM_DOMAIN_FAILED, domainOrForestFqdn, new object[]
            {
                domainOrForestFqdn
            });
            throw new NoSuitableServerFoundException(DirectoryStrings.ErrorNoSuitableDCInDomain(domainOrForestFqdn, value));
        }
Esempio n. 10
0
 internal static void LogBadNumber(string regKeyName, int minAllowed, int maxAllowed, int actual, int defaultValue)
 {
     if (string.IsNullOrEmpty(regKeyName))
     {
         throw new ArgumentNullException("regKeyName");
     }
     Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_REG_BAD_DWORD, null, new object[]
     {
         regKeyName,
         minAllowed,
         maxAllowed,
         actual,
         defaultValue
     });
 }
Esempio n. 11
0
 private void UnlockBucket()
 {
     lock (this.instanceLock)
     {
         this.locked   = false;
         this.lockedAt = DateTime.MinValue;
     }
     ExTraceGlobals.ClientThrottlingTracer.TraceDebug((long)this.GetHashCode(), "[TokenBucket.UnlockBucket] Bucket is now unlocked. Resetting state.");
     if (Globals.ProcessInstanceType != InstanceType.NotInitialized)
     {
         Globals.LogEvent(DirectoryEventLogConstants.Tuple_UserNoLongerLockedOutThrottling, string.Empty, new object[]
         {
             this.BudgetKey
         });
     }
 }
        private static CachableThrottlingPolicyItem ResolveThrottlingPolicy(object obj, OrgAndObjectId orgAndObjectId)
        {
            ThrottlingPolicy throttlingPolicy = null;

            if (orgAndObjectId.Id.IsDeleted)
            {
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_DeletedThrottlingPolicyReferenced, orgAndObjectId.ToString(), new object[]
                {
                    orgAndObjectId
                });
            }
            else
            {
                throttlingPolicy = ThrottlingPolicyCache.ReadThrottlingPolicyFromAD(ThrottlingPolicyCache.GetSession(orgAndObjectId.OrganizationId), orgAndObjectId.Id, (IConfigurationSession session1, object id) => session1.Read <ThrottlingPolicy>((ADObjectId)id));
            }
            return(new CachableThrottlingPolicyItem((throttlingPolicy == null) ? ThrottlingPolicyCache.Singleton.Get(orgAndObjectId.OrganizationId) : throttlingPolicy.GetEffectiveThrottlingPolicy(true)));
        }
Esempio n. 13
0
 public static void Initialize(BudgetType budgetType, int?massOverBudgetPercent, bool allowReinitialize)
 {
     if (ThrottlingPerfCounterWrapper.PerfCountersInitialized && !allowReinitialize)
     {
         throw new InvalidOperationException(string.Format("ThrottlingPerformanceCounters were already initialized with budget type of '{0}'.", ThrottlingPerfCounterWrapper.budgetType));
     }
     if (massOverBudgetPercent != null && (massOverBudgetPercent.Value < 0 || massOverBudgetPercent.Value > 100))
     {
         throw new ArgumentOutOfRangeException("massOverBudgetPercent", massOverBudgetPercent.Value, "massOverBudgetPercent must be between 0 and 100 inclusive");
     }
     ThrottlingPerfCounterWrapper.budgetType = budgetType;
     ThrottlingPerfCounterWrapper.massiveNumberOfUsersOverBudgetPercent = ((massOverBudgetPercent != null) ? massOverBudgetPercent.Value : DefaultThrottlingAlertValues.MassUserOverBudgetPercent(budgetType));
     try
     {
         string instanceName = ThrottlingPerfCounterWrapper.GetInstanceName(budgetType.ToString());
         ThrottlingPerfCounterWrapper.throttlingPerfCounters     = MSExchangeThrottling.GetInstance(instanceName);
         ThrottlingPerfCounterWrapper.userThrottlingPerfCounters = MSExchangeUserThrottling.GetInstance(instanceName);
         ThrottlingPerfCounterWrapper.PerfCountersInitialized    = true;
     }
     catch (Exception ex)
     {
         ThrottlingPerfCounterWrapper.PerfCountersInitialized = false;
         Globals.LogEvent(DirectoryEventLogConstants.Tuple_InitializePerformanceCountersFailed, string.Empty, new object[]
         {
             ex.ToString()
         });
         ExTraceGlobals.ClientThrottlingTracer.TraceError <string, string>(0L, "[ThrottlingPerfCounterWrapper.Initialize] Perf counter initialization failed with exception type: {0}, Messsage: {1}", ex.GetType().FullName, ex.Message);
     }
     ThrottlingPerfCounterWrapper.budgetsMicroDelayed = new ExactTimeoutCache <BudgetKey, BudgetKey>(delegate(BudgetKey key, BudgetKey value, RemoveReason reason)
     {
         ThrottlingPerfCounterWrapper.UpdateBudgetsMicroDelayed();
     }, null, null, 1000000, false, CacheFullBehavior.ExpireExisting);
     ThrottlingPerfCounterWrapper.budgetsAtMaximumDelay = new ExactTimeoutCache <BudgetKey, BudgetKey>(delegate(BudgetKey key, BudgetKey value, RemoveReason reason)
     {
         ThrottlingPerfCounterWrapper.UpdateBudgetsAtMaxDelay();
     }, null, null, 1000000, false, CacheFullBehavior.ExpireExisting);
     ThrottlingPerfCounterWrapper.budgetsLockedOut = new ExactTimeoutCache <BudgetKey, BudgetKey>(delegate(BudgetKey key, BudgetKey value, RemoveReason reason)
     {
         ThrottlingPerfCounterWrapper.UpdateBudgetsLockedOut();
     }, null, null, 1000000, false, CacheFullBehavior.ExpireExisting);
     ThrottlingPerfCounterWrapper.budgetsOverBudget = new ExactTimeoutCache <BudgetKey, BudgetKey>(delegate(BudgetKey key, BudgetKey value, RemoveReason reason)
     {
         ThrottlingPerfCounterWrapper.UpdateOverBudget();
     }, null, null, 1000000, false, CacheFullBehavior.ExpireExisting);
     ThrottlingPerfCounterWrapper.budgetsAtMaxConcurrency = new HashSet <BudgetKey>();
 }
        // Token: 0x0600031C RID: 796 RVA: 0x00010CEC File Offset: 0x0000EEEC
        public static PartitionId GetPartitionIdByExternalDirectoryOrganizationId(Guid externalDirectoryOrganizationId, out string tenantContainerCN)
        {
            tenantContainerCN = null;
            TenantPartitionCacheItem tenantPartitionCacheItem = ADAccountPartitionLocator.FindTenantInfoByExternalOrgId(externalDirectoryOrganizationId);

            if (tenantPartitionCacheItem != null)
            {
                ADAccountPartitionLocator.EnsureAllowedCallerForUnregisteredAccountPartition(tenantPartitionCacheItem);
                tenantContainerCN = tenantPartitionCacheItem.TenantName;
                return(tenantPartitionCacheItem.AccountPartitionId);
            }
            Globals.LogEvent(DirectoryEventLogConstants.Tuple_CannotResolveExternalDirectoryOrganizationId, externalDirectoryOrganizationId.ToString(), new object[]
            {
                DirectoryStrings.CannotResolveTenantNameByExternalDirectoryId(externalDirectoryOrganizationId.ToString()),
                Environment.StackTrace
            });
            throw new CannotResolveExternalDirectoryOrganizationIdException(DirectoryStrings.CannotResolveTenantNameByExternalDirectoryId(externalDirectoryOrganizationId.ToString()));
        }
 // Token: 0x06000B42 RID: 2882 RVA: 0x00033948 File Offset: 0x00031B48
 protected override void LogCallServiceError(Exception error, string priodicKey, string debugMessage, int numberOfRetries)
 {
     if (Globals.ProcessInstanceType != InstanceType.NotInitialized)
     {
         string text = error.ToString();
         if (error is FaultException <TopologyServiceFault> )
         {
             text = ((FaultException <TopologyServiceFault>)error).Detail.ToString();
         }
         Globals.LogEvent(this.errorEvent, priodicKey, new object[]
         {
             debugMessage,
             base.TargetInfo,
             numberOfRetries,
             text
         });
     }
 }
        // Token: 0x06000B44 RID: 2884 RVA: 0x00033A08 File Offset: 0x00031C08
        private static ChannelFactory <TClient> CreateChannelFactory(string endpointName, EndpointAddress endpointAddress, Binding defaultBinding, Trace tracer)
        {
            ArgumentValidator.ThrowIfNull("endpointName", endpointName);
            ArgumentValidator.ThrowIfNull("endpointAddress", endpointAddress);
            ArgumentValidator.ThrowIfNull("defaultBinding", endpointAddress);
            ArgumentValidator.ThrowIfNull("tracer", tracer);
            ChannelFactory <TClient> channelFactory = null;

            try
            {
                channelFactory = WcfUtils.TryCreateChannelFactoryFromConfig <TClient>(endpointName);
            }
            catch (Exception ex)
            {
                tracer.TraceError <string, string>(0L, "ServiceProxyPool - Error Creating channel factory from config file for {0}. Details {1}", endpointName, ex.ToString());
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_WcfClientConfigError, endpointName, new object[]
                {
                    endpointName,
                    ex.Message
                });
            }
            if (channelFactory != null)
            {
                string host = endpointAddress.Uri.Host;
                Uri    uri  = channelFactory.Endpoint.Address.Uri;
                string uri2 = string.Format("{0}://{1}:{2}{3}", new object[]
                {
                    uri.Scheme,
                    host,
                    uri.Port,
                    uri.PathAndQuery
                });
                channelFactory.Endpoint.Address = new EndpointAddress(uri2);
            }
            else
            {
                tracer.TraceDebug <string>(0L, "ServiceProxyPool - Creating channel factory for {0} using default configuration", endpointName);
                channelFactory = new ChannelFactory <TClient>(defaultBinding, endpointAddress);
            }
            DirectoryServiceProxyPool <TClient> .ConfigWCFServicePointManager();

            return(channelFactory);
        }
        // Token: 0x06000B45 RID: 2885 RVA: 0x00033B28 File Offset: 0x00031D28
        private static ChannelFactory <TClient> CreateChannelFactory(string endpointName, ServiceEndpoint serviceEndpoint, Binding defaultBinding, Trace tracer)
        {
            ArgumentValidator.ThrowIfNull("endpointName", endpointName);
            ArgumentValidator.ThrowIfNull("serviceEndpoint", serviceEndpoint);
            ArgumentValidator.ThrowIfNull("defaultBinding", defaultBinding);
            ArgumentValidator.ThrowIfNull("tracer", tracer);
            ChannelFactory <TClient> channelFactory = null;

            try
            {
                channelFactory = WcfUtils.TryCreateChannelFactoryFromConfig <TClient>(endpointName);
            }
            catch (Exception ex)
            {
                tracer.TraceError <string, string>(0L, "ServiceProxyPool - Error Creating channel factory from config file for {0}. Details {1}", endpointName, ex.ToString());
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_WcfClientConfigError, endpointName, new object[]
                {
                    endpointName,
                    ex.Message
                });
            }
            if (channelFactory == null)
            {
                channelFactory = new ChannelFactory <TClient>(defaultBinding, serviceEndpoint.Uri.ToString());
            }
            WSHttpBinding wshttpBinding = defaultBinding as WSHttpBinding;

            if (wshttpBinding != null && wshttpBinding.Security.Transport.ClientCredentialType == HttpClientCredentialType.Certificate)
            {
                try
                {
                    channelFactory.Credentials.ClientCertificate.Certificate = TlsCertificateInfo.FindFirstCertWithSubjectDistinguishedName(serviceEndpoint.CertificateSubject);
                }
                catch (ArgumentException ex2)
                {
                    throw new GlsPermanentException(DirectoryStrings.PermanentGlsError(ex2.Message));
                }
            }
            DirectoryServiceProxyPool <TClient> .ConfigWCFServicePointManager();

            return(channelFactory);
        }
        // Token: 0x0600031D RID: 797 RVA: 0x00010D74 File Offset: 0x0000EF74
        public static PartitionId GetPartitionIdByMSAUserNetID(string msaUserNetID, out string tenantContainerCN, out Guid externalDirectoryOrganizationId)
        {
            tenantContainerCN = null;
            externalDirectoryOrganizationId = Guid.Empty;
            TenantPartitionCacheItem tenantPartitionCacheItem = ADAccountPartitionLocator.FindTenantInfoByMSAUserNetID(msaUserNetID);

            if (tenantPartitionCacheItem != null)
            {
                ADAccountPartitionLocator.EnsureAllowedCallerForUnregisteredAccountPartition(tenantPartitionCacheItem);
                tenantContainerCN = tenantPartitionCacheItem.TenantName;
                externalDirectoryOrganizationId = tenantPartitionCacheItem.ExternalOrgId;
                return(tenantPartitionCacheItem.AccountPartitionId);
            }
            Globals.LogEvent(DirectoryEventLogConstants.Tuple_CannotResolveMSAUserNetID, msaUserNetID, new object[]
            {
                DirectoryStrings.CannotFindTenantByMSAUserNetID(msaUserNetID),
                Environment.StackTrace
            });
            throw new CannotResolveMSAUserNetIDException(DirectoryStrings.CannotFindTenantByMSAUserNetID(msaUserNetID));
        }
        // Token: 0x06000DBB RID: 3515 RVA: 0x0003EA50 File Offset: 0x0003CC50
        private bool OpenNewConnection(ConnectionInfo info)
        {
            ArgumentValidator.ThrowIfNull("info", info);
            if (info.ConnectionState != ConnectionState.Empty)
            {
                return(false);
            }
            if (!info.TryMakeConnecting())
            {
                return(false);
            }
            bool result = false;

            try
            {
                ExTraceGlobals.ConnectionTracer.TraceDebug <string>((long)this.GetHashCode(), "LdapConnectionPool::OpenNewConnection - opening new PooledLdapConnection to {0}", info.ADServerInfo.FqdnPlusPort);
                if (info.TryCreatePooledLdapConnection(LdapConnectionPool.RoleFromConnectionPoolType(this.type), this.type == ConnectionPoolType.ConfigDCNotifyPool, this.credential))
                {
                    Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_NEW_CONNECTION, null, new object[]
                    {
                        info.ADServerInfo.Fqdn,
                        info.ADServerInfo.Port,
                        this.type
                    });
                    if (info.TryBindWithRetry(3) && info.TrySetNamingContexts())
                    {
                        info.MakeConnected();
                        result = true;
                        Interlocked.Increment(ref this.connectedCount);
                    }
                }
            }
            finally
            {
                if (info.ConnectionState == ConnectionState.Connecting)
                {
                    info.MakeDisconnected();
                }
            }
            return(result);
        }
Esempio n. 20
0
 // Token: 0x0600036F RID: 879 RVA: 0x00012C08 File Offset: 0x00010E08
 private void RunCallback(ADNotificationEventArgs args, bool timedOut)
 {
     if (!timedOut)
     {
         lock (this)
         {
             this.hasQueuedRun = false;
         }
         try
         {
             try
             {
                 this.callback(args);
             }
             catch (ADInvalidCredentialException)
             {
                 ExTraceGlobals.ADNotificationsTracer.TraceError(0L, "Some component's AD Notification callback didn't catch ADInvalidCredentialException.");
             }
             catch (ADTransientException)
             {
                 ExTraceGlobals.ADNotificationsTracer.TraceError(0L, "Some component's AD Notification callback didn't catch ADTransientException.");
             }
             catch (DataValidationException)
             {
                 ExTraceGlobals.ADNotificationsTracer.TraceError(0L, "Some component's AD Notification callback didn't catch DataValidationException.");
             }
             return;
         }
         finally
         {
             this.waitHandle.Set();
         }
     }
     Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_AD_NOTIFICATION_CALLBACK_TIMED_OUT, args.Type.Name, new object[]
     {
         args.Type.Name
     });
     ExTraceGlobals.ADNotificationsTracer.TraceError(0L, "Some component's AD Notification callback hasn't returned after 10 minutes. config. change notifications ARE NO LONGER BEING DELIVERED TO SUCH COMPONENT.");
 }
Esempio n. 21
0
        private static void LogEventsIfNecessary()
        {
            int num  = 0;
            int num2 = 0;
            int num3 = 0;

            lock (ThrottlingPerfCounterWrapper.staticLock)
            {
                int budgetCount = ThrottlingPerfCounterWrapper.GetBudgetCount();
                num3 = ((budgetCount > 0) ? (100 * ThrottlingPerfCounterWrapper.budgetsOverBudget.Count / budgetCount) : 0);
            }
            if (num3 > ThrottlingPerfCounterWrapper.massiveNumberOfUsersOverBudgetPercent && ThrottlingPerfCounterWrapper.budgetsOverBudget.Count > ThrottlingPerfCounterWrapper.minUniqueBudgetsForMassiveOverBudgetAlert)
            {
                bool flag2 = false;
                lock (ThrottlingPerfCounterWrapper.staticLock)
                {
                    if (ThrottlingPerfCounterWrapper.budgetsOverBudget.Count > ThrottlingPerfCounterWrapper.minUniqueBudgetsForMassiveOverBudgetAlert)
                    {
                        flag2 = true;
                        num   = ThrottlingPerfCounterWrapper.GetBudgetCount();
                        num2  = ThrottlingPerfCounterWrapper.budgetsOverBudget.Count;
                    }
                }
                if (flag2)
                {
                    if (ThrottlingPerfCounterWrapper.OnLogMassiveNumberOfUsersOverBudgetDelegate != null)
                    {
                        ThrottlingPerfCounterWrapper.OnLogMassiveNumberOfUsersOverBudgetDelegate(num, num3);
                    }
                    Globals.LogEvent(DirectoryEventLogConstants.Tuple_ExcessiveMassUserThrottling, ThrottlingPerfCounterWrapper.budgetType.ToString(), new object[]
                    {
                        num2,
                        ThrottlingPerfCounterWrapper.budgetType,
                        num,
                        num3
                    });
                }
            }
        }
Esempio n. 22
0
        private void LockBucket()
        {
            lock (this.instanceLock)
            {
                this.locked   = true;
                this.lockedAt = TimeProvider.UtcNow;
            }
            DateTime value = this.LockedUntilUtcNonUpdating.Value;

            ThrottlingPerfCounterWrapper.IncrementBudgetsLockedOut(this.BudgetKey, value - TimeProvider.UtcNow);
            if (Globals.ProcessInstanceType != InstanceType.NotInitialized)
            {
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_UserLockedOutThrottling, string.Empty, new object[]
                {
                    this.BudgetKey,
                    value,
                    this.GetTraceInt(this.MaximumBalance),
                    this.GetTraceInt(this.RechargeRate),
                    this.GetTraceInt(this.MinimumBalance)
                });
            }
            ExTraceGlobals.ClientThrottlingTracer.TraceDebug <DateTime, int>((long)this.GetHashCode(), "[TokenBucket.LockBucket] Bucket locked until {0}.  Current Pending charges: {1}", value, this.PendingCharges);
        }
Esempio n. 23
0
        private static void LogEventProcessADContextChanged()
        {
            string text  = "<null>";
            string text2 = text;
            string text3 = text;
            string text4 = text;

            if (ADSessionSettings.processContext != null)
            {
                ADServerSettings serverSettings = ADSessionSettings.processContext.ServerSettings;
                string           text5          = serverSettings.PreferredGlobalCatalog(TopologyProvider.LocalForestFqdn);
                if (!string.IsNullOrEmpty(text5))
                {
                    text3 = text5;
                }
                text5 = serverSettings.ConfigurationDomainController(TopologyProvider.LocalForestFqdn);
                if (!string.IsNullOrEmpty(text5))
                {
                    text4 = text5;
                }
                if (serverSettings.PreferredDomainControllers.Count > 0)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (Fqdn fqdn in serverSettings.PreferredDomainControllers)
                    {
                        stringBuilder.AppendLine(fqdn);
                    }
                    text2 = stringBuilder.ToString();
                }
            }
            Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_PREFERRED_TOPOLOGY, null, new object[]
            {
                text2,
                text3,
                text4
            });
        }
Esempio n. 24
0
        // Token: 0x060071E5 RID: 29157 RVA: 0x001794F8 File Offset: 0x001776F8
        internal void CheckLeakedActions()
        {
            DateTime          utcNow        = TimeProvider.UtcNow;
            StringBuilder     stringBuilder = null;
            List <CostHandle> list          = null;

            if (utcNow - this.lastLeakDetectionUtc >= Budget.LeakDetectionCheckInterval && this.OutstandingActionsCount > 0)
            {
                lock (this.syncRoot)
                {
                    if (utcNow - this.lastLeakDetectionUtc >= Budget.LeakDetectionCheckInterval && this.OutstandingActionsCount > 0)
                    {
                        this.lastLeakDetectionUtc = utcNow;
                        foreach (KeyValuePair <long, CostHandle> keyValuePair in this.outstandingActions)
                        {
                            CostHandle value    = keyValuePair.Value;
                            TimeSpan   timeSpan = utcNow - value.StartTime;
                            if (value.CostType == CostType.CAS && timeSpan > value.MaxLiveTime && !value.LeakLogged)
                            {
                                if (Budget.OnLeakDetectionForTest != null)
                                {
                                    Budget.OnLeakDetectionForTest(this, value, timeSpan, value.MaxLiveTime);
                                }
                                if (Budget.OnLeakDetectionForTest == null || Budget.OnLeakWatsonInfoForTest != null)
                                {
                                    if (stringBuilder == null)
                                    {
                                        stringBuilder = new StringBuilder();
                                    }
                                    stringBuilder.AppendLine(string.Format("CostType: {0}, Key: {1}, Limit: {2}, Elapsed: {3}, Actions: {4}, Description: {5}, Snapshot: {6}", new object[]
                                    {
                                        value.CostType,
                                        keyValuePair.Key,
                                        value.MaxLiveTime,
                                        timeSpan,
                                        this.OutstandingActionsCount,
                                        value.Description,
                                        this
                                    }));
                                }
                                value.LeakLogged = true;
                                if (list == null)
                                {
                                    list = new List <CostHandle>();
                                }
                                list.Add(value);
                            }
                        }
                    }
                }
            }
            if (Budget.OnLeakWatsonInfoForTest != null)
            {
                Budget.OnLeakWatsonInfoForTest(stringBuilder);
            }
            else if (stringBuilder != null)
            {
                try
                {
                    throw new LongRunningCostHandleException();
                }
                catch (LongRunningCostHandleException exception)
                {
                    ExWatson.SendReport(exception, ReportOptions.None, stringBuilder.ToString());
                }
            }
            if (stringBuilder != null)
            {
                string text = stringBuilder.ToString();
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_BudgetActionExceededExpectedTime, text, new object[]
                {
                    "\n" + text
                });
            }
            if (list != null)
            {
                foreach (CostHandle costHandle in list)
                {
                    costHandle.Dispose();
                }
            }
        }
Esempio n. 25
0
        // Token: 0x060003B5 RID: 949 RVA: 0x00015440 File Offset: 0x00013640
        internal static ADObject CreateAndInitializeRecipientObject <TRecipientObject>(ADPropertyBag propertyBag, ADRawEntry dummyObject, IRecipientSession recipientSession) where TRecipientObject : IConfigurable, new()
        {
            ArgumentValidator.ThrowIfNull("propertyBag", propertyBag);
            ArgumentValidator.ThrowIfNull("dummyObject", dummyObject);
            MultiValuedProperty <string> multiValuedProperty = (MultiValuedProperty <string>)propertyBag[ADObjectSchema.ObjectClass];
            ADObject adobject;

            if (dummyObject is OWAMiniRecipient)
            {
                adobject = new OWAMiniRecipient();
            }
            else if (dummyObject is ActiveSyncMiniRecipient)
            {
                adobject = new ActiveSyncMiniRecipient();
            }
            else if (dummyObject is StorageMiniRecipient)
            {
                adobject = new StorageMiniRecipient();
            }
            else if (dummyObject is TransportMiniRecipient)
            {
                adobject = new TransportMiniRecipient();
            }
            else if (dummyObject is LoadBalancingMiniRecipient)
            {
                adobject = new LoadBalancingMiniRecipient();
            }
            else if (dummyObject is MiniRecipientWithTokenGroups)
            {
                adobject = new MiniRecipientWithTokenGroups();
            }
            else if (dummyObject is FrontEndMiniRecipient)
            {
                adobject = new FrontEndMiniRecipient();
            }
            else if (dummyObject is MiniRecipient)
            {
                adobject = new MiniRecipient();
            }
            else if (dummyObject is RemovedMailbox)
            {
                adobject = new RemovedMailbox();
            }
            else if (dummyObject is DeletedRecipient)
            {
                adobject = new DeletedRecipient();
            }
            else if (multiValuedProperty.Contains(ADComputerRecipient.MostDerivedClass))
            {
                adobject = new ADComputerRecipient();
            }
            else if (multiValuedProperty.Contains(ADUser.MostDerivedClass))
            {
                adobject = new ADUser();
            }
            else if (multiValuedProperty.Contains(ADContact.MostDerivedClass))
            {
                adobject = new ADContact();
            }
            else if (multiValuedProperty.Contains(ADGroup.MostDerivedClass))
            {
                adobject = new ADGroup();
            }
            else if (multiValuedProperty.Contains(ADDynamicGroup.MostDerivedClass))
            {
                adobject = new ADDynamicGroup();
            }
            else if (multiValuedProperty.Contains(ADPublicFolder.MostDerivedClass))
            {
                adobject = new ADPublicFolder();
            }
            else if (multiValuedProperty.Contains(ADSystemAttendantMailbox.MostDerivedClass))
            {
                adobject = new ADSystemAttendantMailbox();
            }
            else if (multiValuedProperty.Contains(ADSystemMailbox.MostDerivedClass))
            {
                adobject = new ADSystemMailbox();
            }
            else if (multiValuedProperty.Contains(ADPublicDatabase.MostDerivedClass))
            {
                adobject = new ADPublicDatabase();
            }
            else
            {
                if (!multiValuedProperty.Contains(ADMicrosoftExchangeRecipient.MostDerivedClass))
                {
                    string objectClass = string.Empty;
                    foreach (string text in multiValuedProperty)
                    {
                        objectClass = text;
                    }
                    ObjectValidationError error = new ObjectValidationError(DirectoryStrings.UnsupportedObjectClass(objectClass), (ADObjectId)propertyBag[ADObjectSchema.Id], string.Empty);
                    ADProviderPerf.UpdateProcessCounter(Counter.ProcessRateCriticalValidationFailures, UpdateType.Update, 1U);
                    Globals.LogEvent(DirectoryEventLogConstants.Tuple_DSC_EVENT_VALIDATION_FAILED_FCO_MODE_RECIPIENT, ((ADObjectId)propertyBag[ADObjectSchema.Id]).ToString(), new object[]
                    {
                        ((ADObjectId)propertyBag[ADObjectSchema.Id]).ToDNString()
                    });
                    throw new DataValidationException(error);
                }
                adobject = new ADMicrosoftExchangeRecipient();
            }
            adobject.m_Session   = recipientSession;
            adobject.propertyBag = propertyBag;
            adobject.Initialize();
            adobject.ResetChangeTracking(true);
            if (recipientSession != null)
            {
                adobject.SetIsReadOnly(recipientSession.ReadOnly);
            }
            ExTraceGlobals.ADReadDetailsTracer.TraceDebug <string, RecipientType>((long)((recipientSession != null) ? recipientSession.GetHashCode() : 0), "ADRecipientObjectSession::CreateObject - Got {0} as {1}", adobject.DistinguishedName, (RecipientType)adobject[ADRecipientSchema.RecipientType]);
            return(adobject);
        }
        protected TResult ExecuteSingleObjectQueryWithFallback <TResult>(Func <TSession, TResult> query, Func <TResult, List <Tuple <string, KeyType> > > getAdditionalKeys = null, IEnumerable <PropertyDefinition> properties = null) where TResult : ADRawEntry, new()
        {
            ArgumentValidator.ThrowIfNull("query", query);
            if (!Configuration.IsCacheEnabled(typeof(TResult)))
            {
                return(query(this.GetSession()));
            }
            Stopwatch stopwatch = Stopwatch.StartNew();

            CachePerformanceTracker.StartLogging();
            CompositeDirectorySession <TSession> .TraceState traceState = CompositeDirectorySession <TSession> .TraceState.None;
            CacheMode          cacheModeForCurrentProcess = Configuration.GetCacheModeForCurrentProcess();
            double             num                = -1.0;
            double             num2               = -1.0;
            double             num3               = -1.0;
            double             num4               = -1.0;
            TResult            tresult            = default(TResult);
            string             text               = string.Empty;
            Guid               guid               = Guid.Empty;
            ADCacheResultState adcacheResultState = ADCacheResultState.Succeed;
            bool               flag               = true;
            int num5 = 0;

            try
            {
                Stopwatch stopwatch2 = null;
                ADObject  adobject   = null;
                try
                {
                    TSession session = this.GetSession();
                    if (session.ActivityScope != null)
                    {
                        TSession session2 = this.GetSession();
                        if (session2.ActivityScope.Status == ActivityContextStatus.ActivityStarted)
                        {
                            TSession session3 = this.GetSession();
                            guid = session3.ActivityScope.ActivityId;
                        }
                    }
                    if (!this.CacheSessionForDeletingOnly && (CacheMode.Read & cacheModeForCurrentProcess) != CacheMode.Disabled)
                    {
                        TSession session4 = this.GetSession();
                        if (!session4.SessionSettings.IncludeSoftDeletedObjectLinks)
                        {
                            if (properties != null || !typeof(TResult).Equals(typeof(ADRawEntry)))
                            {
                                traceState |= CompositeDirectorySession <TSession> .TraceState.CacheRead;
                                stopwatch2  = Stopwatch.StartNew();
                                tresult     = query(this.GetCacheSession());
                                CacheDirectorySession cacheDirectorySession = this.GetCacheSession() as CacheDirectorySession;
                                if (cacheDirectorySession != null)
                                {
                                    adcacheResultState = cacheDirectorySession.ResultState;
                                    flag = cacheDirectorySession.IsNewProxyObject;
                                    num5 = cacheDirectorySession.RetryCount;
                                }
                                stopwatch2.Stop();
                                num = (double)stopwatch2.ElapsedMilliseconds;
                                goto IL_19A;
                            }
                            goto IL_19A;
                        }
                    }
                    if ((CacheMode.Read & cacheModeForCurrentProcess) == CacheMode.Disabled || this.CacheSessionForDeletingOnly)
                    {
                        adcacheResultState = ADCacheResultState.CacheModeIsNotRead;
                    }
                    else
                    {
                        adcacheResultState = ADCacheResultState.SoftDeletedObject;
                    }
IL_19A:
                    if (tresult != null && tresult.Id != null)
                    {
                        TSession session5 = this.GetSession();
                        if (ADSession.ShouldFilterCNFObject(session5.SessionSettings, tresult.Id))
                        {
                            tresult            = default(TResult);
                            adcacheResultState = ADCacheResultState.CNFedObject;
                        }
                        else
                        {
                            TSession session6 = this.GetSession();
                            if (ADSession.ShouldFilterSoftDeleteObject(session6.SessionSettings, tresult.Id))
                            {
                                tresult            = default(TResult);
                                adcacheResultState = ADCacheResultState.SoftDeletedObject;
                            }
                            else
                            {
                                if (tresult.Id != null && tresult.Id.DomainId != null)
                                {
                                    TSession session7 = this.GetSession();
                                    if (!session7.SessionSettings.PartitionId.Equals(tresult.Id.GetPartitionId()))
                                    {
                                        if (ExEnvironment.IsTest)
                                        {
                                            TSession session8 = this.GetSession();
                                            if (session8.SessionSettings.PartitionId.ForestFQDN.EndsWith(tresult.Id.GetPartitionId().ForestFQDN, StringComparison.OrdinalIgnoreCase))
                                            {
                                                goto IL_341;
                                            }
                                        }
                                        ExEventLog.EventTuple tuple_WrongObjectReturned = DirectoryEventLogConstants.Tuple_WrongObjectReturned;
                                        string   name     = typeof(TResult).Name;
                                        object[] array    = new object[2];
                                        object[] array2   = array;
                                        int      num6     = 0;
                                        TSession session9 = this.GetSession();
                                        array2[num6] = session9.SessionSettings.PartitionId.ForestFQDN;
                                        array[1]     = tresult.Id.GetPartitionId().ForestFQDN;
                                        Globals.LogEvent(tuple_WrongObjectReturned, name, array);
                                        tresult            = default(TResult);
                                        adcacheResultState = ADCacheResultState.WrongForest;
                                        goto IL_3E1;
                                    }
                                }
IL_341:
                                TSession session10 = this.GetSession();
                                if (session10.SessionSettings.CurrentOrganizationId != OrganizationId.ForestWideOrgId)
                                {
                                    TSession       session11             = this.GetSession();
                                    OrganizationId currentOrganizationId = session11.SessionSettings.CurrentOrganizationId;
                                    if (!tresult.Id.IsDescendantOf(currentOrganizationId.OrganizationalUnit) && !tresult.Id.IsDescendantOf(currentOrganizationId.ConfigurationUnit.Parent))
                                    {
                                        tresult            = default(TResult);
                                        adcacheResultState = ADCacheResultState.OranizationIdMismatch;
                                    }
                                }
                            }
                        }
                    }
                    else if (tresult != null)
                    {
                        tresult = default(TResult);
                    }
                    else
                    {
                        adcacheResultState = ADCacheResultState.NotFound;
                    }
IL_3E1:
                    adobject = (tresult as ADObject);
                }
                catch (Exception ex)
                {
                    tresult            = default(TResult);
                    adcacheResultState = ADCacheResultState.ExceptionHappened;
                    Globals.LogEvent(DirectoryEventLogConstants.Tuple_CallADCacheServiceFailed, typeof(TResult).Name, new object[]
                    {
                        ex.ToString()
                    });
                    text = ex.ToString();
                }
                if (tresult == null)
                {
                    traceState |= CompositeDirectorySession <TSession> .TraceState.ADRead;
                    stopwatch2  = Stopwatch.StartNew();
                    tresult     = query(this.GetSession());
                    adobject    = (tresult as ADObject);
                    stopwatch2.Stop();
                    num4 = (double)stopwatch2.ElapsedMilliseconds;
                    stopwatch2.Restart();
                    bool flag2 = true;
                    if (adobject != null)
                    {
                        TSession session12 = this.GetSession();
                        if (!session12.ReadOnly && CompositeDirectorySession <TSession> .ExchangeConfigUnitCUType.Equals(adobject.GetType()) && OrganizationId.ForestWideOrgId.Equals(adobject.OrganizationId))
                        {
                            ExTraceGlobals.SessionTracer.TraceWarning <string>((long)this.GetHashCode(), "Newly created ExchangeCU with organizationId equals to RootOrgId, ignored till is fully populated. DN {0}", tresult.GetDistinguishedNameOrName());
                            flag2 = false;
                        }
                    }
                    if (tresult != null && CacheUtils.GetObjectTypeFor(tresult.GetType(), false) == ObjectType.Unknown)
                    {
                        flag2 = false;
                    }
                    if (tresult != null && ((CacheMode.SyncWrite | CacheMode.AsyncWrite) & cacheModeForCurrentProcess) != CacheMode.Disabled && tresult.Id != null && !tresult.Id.IsDeleted && flag2)
                    {
                        traceState |= CompositeDirectorySession <TSession> .TraceState.CacheInsert;
                        if ((CacheMode.SyncWrite & cacheModeForCurrentProcess) != CacheMode.Disabled)
                        {
                            try
                            {
                                this.CacheInsert <TResult>(tresult, getAdditionalKeys, properties);
                                goto IL_5C8;
                            }
                            catch (Exception ex2)
                            {
                                Globals.LogEvent(DirectoryEventLogConstants.Tuple_CallADCacheServiceFailed, "CacheInsert", new object[]
                                {
                                    ex2.ToString()
                                });
                                text += ex2.Message;
                                goto IL_5C8;
                            }
                        }
                        TSession session13 = this.GetSession();
                        if (session13.ReadOnly)
                        {
                            this.AsyncCacheInsert <TResult>(tresult, getAdditionalKeys, properties);
                        }
                        else
                        {
                            adcacheResultState |= ADCacheResultState.WritableSession;
                        }
                    }
IL_5C8:
                    stopwatch2.Stop();
                    num3 = (double)stopwatch2.ElapsedMilliseconds;
                }
                if (adobject != null)
                {
                    adobject.m_Session = this;
                }
            }
            finally
            {
                stopwatch.Stop();
                string   text2                   = CachePerformanceTracker.StopLogging();
                string   operation               = "Read";
                string   dn                      = (tresult != null) ? tresult.GetDistinguishedNameOrName() : "<NULL>";
                DateTime whenReadUTC             = (tresult != null) ? ((tresult.WhenReadUTC != null) ? tresult.WhenReadUTC.Value : DateTime.MinValue) : DateTime.MinValue;
                long     elapsedMilliseconds     = stopwatch.ElapsedMilliseconds;
                long     wcfGetProcessingTime    = (long)num;
                long     wcfRemoveProcessingTime = (long)num2;
                long     wcfPutProcessingTime    = (long)num3;
                long     adProcessingTime        = (long)num4;
                bool     isNewProxyObject        = flag;
                int      retryCount              = num5;
                string   objectType              = (tresult != null) ? tresult.GetType().Name : typeof(TResult).Name;
                string   cachePerformanceTracker = text2;
                Guid     activityId              = guid;
                TSession session14               = this.GetSession();
                CacheProtocolLog.BeginAppend(operation, dn, whenReadUTC, elapsedMilliseconds, wcfGetProcessingTime, wcfRemoveProcessingTime, wcfPutProcessingTime, adProcessingTime, isNewProxyObject, retryCount, objectType, cachePerformanceTracker, activityId, session14.CallerInfo, string.Format("ResultState:{0};{1}", (int)adcacheResultState, text));
                ExTraceGlobals.SessionTracer.TraceDebug((long)this.GetHashCode(), "ExecuteSingleObjectQueryWithFallback. Cache Mode {0}. TraceState {1}. DN {2}. WhenRead {3}. IsCached {4}.", new object[]
                {
                    cacheModeForCurrentProcess,
                    traceState,
                    (tresult != null) ? tresult.GetDistinguishedNameOrName() : "<NULL>",
                    (tresult != null) ? ((tresult.WhenReadUTC != null) ? tresult.WhenReadUTC.Value.ToString() : "<NULL>") : "<NULL>",
                    tresult != null && tresult.IsCached
                });
                ExTraceGlobals.SessionTracer.TracePerformance((long)this.GetHashCode(), "ExecuteSingleObjectQueryWithFallback.  Cache Mode {0}. TraceState {1}. DN {2}. TotalTime {3}. GetCacheTime {4}. RemoveCacheTime {5}. PutCacheTime {6}. ADTime {7}. WCFDetails [{8}]", new object[]
                {
                    cacheModeForCurrentProcess,
                    traceState,
                    (tresult != null) ? tresult.GetDistinguishedNameOrName() : "<NULL>",
                    stopwatch.ElapsedMilliseconds,
                    num,
                    num2,
                    num3,
                    num4,
                    text2
                });
                if (tresult != null)
                {
                    ADProviderPerf.UpdateADDriverCacheHitRate(tresult.IsCached);
                }
            }
            return(tresult);
        }
        private static void LogTransition(string component, string requester, ServiceState state)
        {
            if (state != ServiceState.Active)
            {
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_ServerComponentStateSetOffline, Environment.MachineName, new object[]
                {
                    component,
                    requester,
                    state.ToString()
                });
                return;
            }
            bool flag = false;
            List <ServerComponentStates.ItemEntry> list        = null;
            List <ServerComponentStates.ItemEntry> localStates = ServerComponentStates.GetLocalStates(null, ServerComponentStates.ServerWideOfflineComponentId);

            foreach (ServerComponentStates.ItemEntry itemEntry in localStates)
            {
                if (itemEntry.State != ServiceState.Active && !string.Equals(itemEntry.Requester, requester, StringComparison.OrdinalIgnoreCase))
                {
                    flag = true;
                    break;
                }
            }
            if (!flag && !string.Equals(component, ServerComponentStates.ServerWideOfflineComponentId, StringComparison.OrdinalIgnoreCase))
            {
                list = ServerComponentStates.GetLocalStates(null, component);
                foreach (ServerComponentStates.ItemEntry itemEntry2 in list)
                {
                    if (itemEntry2.State != ServiceState.Active && !string.Equals(itemEntry2.Requester, requester, StringComparison.OrdinalIgnoreCase))
                    {
                        flag = true;
                        break;
                    }
                }
            }
            if (!flag)
            {
                DateTime dateTime = DateTime.UtcNow;
                foreach (ServerComponentStates.ItemEntry itemEntry3 in localStates)
                {
                    if (itemEntry3.State != ServiceState.Active && itemEntry3.Timestamp < dateTime)
                    {
                        dateTime = itemEntry3.Timestamp;
                    }
                }
                if (list != null)
                {
                    foreach (ServerComponentStates.ItemEntry itemEntry4 in list)
                    {
                        if (itemEntry4.State != ServiceState.Active && itemEntry4.Timestamp < dateTime)
                        {
                            dateTime = itemEntry4.Timestamp;
                        }
                    }
                }
                Globals.LogEvent(DirectoryEventLogConstants.Tuple_ServerComponentStateSetOnline, Environment.MachineName, new object[]
                {
                    component,
                    requester,
                    dateTime
                });
            }
        }
Esempio n. 28
0
        protected override void ValidateRead(List <ValidationError> errors)
        {
            bool flag = true;

            if (this.OrganizationalUnitRoot != null && this.ConfigurationUnit != null)
            {
                string distinguishedName  = base.Id.DistinguishedName;
                string distinguishedName2 = this.OrganizationalUnitRoot.DistinguishedName;
                string distinguishedName3 = this.ConfigurationUnit.DistinguishedName;
                if (!string.IsNullOrEmpty(distinguishedName3) && !distinguishedName3.ToLower().StartsWith("cn=configuration,"))
                {
                    flag = false;
                    errors.Add(new ObjectValidationError(DirectoryStrings.ErrorInvalidOrganizationId(distinguishedName, distinguishedName2 ?? "<null>", distinguishedName3 ?? "<null>"), this.Identity, string.Empty));
                }
            }
            else if (this.OrganizationalUnitRoot != null || this.ConfigurationUnit != null)
            {
                flag = false;
                errors.Add(new ObjectValidationError(DirectoryStrings.ErrorInvalidOrganizationId(base.Id.ToDNString(), (this.OrganizationalUnitRoot != null) ? this.OrganizationalUnitRoot.ToDNString() : "<null>", (this.ConfigurationUnit != null) ? this.ConfigurationUnit.ToDNString() : "<null>"), this.Identity, string.Empty));
            }
            foreach (ADPropertyDefinition adpropertyDefinition in this.Schema.AllADObjectLinkProperties)
            {
                MultiValuedProperty <ADObjectId> multiValuedProperty = null;
                if (adpropertyDefinition.IsMultivalued)
                {
                    try
                    {
                        multiValuedProperty = (MultiValuedProperty <ADObjectId>) this.propertyBag[adpropertyDefinition];
                        goto IL_16E;
                    }
                    catch (DataValidationException)
                    {
                        goto IL_16E;
                    }
                    goto IL_13E;
                }
                goto IL_13E;
                IL_16E:
                if (multiValuedProperty != null && (multiValuedProperty.Count != 1 || multiValuedProperty[0] != null))
                {
                    foreach (ADObjectId adobjectId in multiValuedProperty)
                    {
                        if (!string.IsNullOrEmpty(adobjectId.DistinguishedName))
                        {
                            if ((base.Id == null || !base.Id.IsDeleted) && adobjectId.IsDeleted)
                            {
                                ExTraceGlobals.ValidationTracer.TraceWarning <string, string, string>(0L, "Object [{0}]. Property [{1}] is set to value [{2}], it is pointing to Deleted Objects container of Active Directory.", this.DistinguishedName.ToString(), adpropertyDefinition.Name, adobjectId.ToString());
                                Globals.LogEvent(DirectoryEventLogConstants.Tuple_DeletedObjectIdLinked, adpropertyDefinition.Name, new object[]
                                {
                                    this.DistinguishedName.ToString(),
                                    adpropertyDefinition.Name,
                                    adobjectId.ToString()
                                });
                            }
                            if (!adpropertyDefinition.IsValidateInSameOrganization || (flag && this.ShouldValidatePropertyLinkInSameOrganization(adpropertyDefinition)))
                            {
                                this.ValidateSingleADObjectLinkValue(adpropertyDefinition, adobjectId, errors);
                            }
                        }
                    }
                    continue;
                }
                continue;
                IL_13E:
                ADObjectId adobjectId2 = null;
                try
                {
                    adobjectId2 = (ADObjectId)this.propertyBag[adpropertyDefinition];
                }
                catch (DataValidationException)
                {
                }
                if (adobjectId2 != null)
                {
                    multiValuedProperty = new MultiValuedProperty <ADObjectId>();
                    multiValuedProperty.Add(adobjectId2);
                    goto IL_16E;
                }
                goto IL_16E;
            }
            base.ValidateRead(errors);
        }