コード例 #1
0
        private static bool IsInternal(string domainStringRepresentation, OrganizationId organizationId)
        {
            IConfigurationSession session = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(organizationId), 145, "IsInternal", "f:\\15.00.1497\\sources\\dev\\data\\src\\directory\\EdgeExtensibility\\IsInternalResolver.cs");
            ADPagedReader <Microsoft.Exchange.Data.Directory.SystemConfiguration.AcceptedDomain> acceptedDomains = null;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                acceptedDomains = session.FindAllPaged <Microsoft.Exchange.Data.Directory.SystemConfiguration.AcceptedDomain>();
            }, 3);
            foreach (Microsoft.Exchange.Data.Directory.SystemConfiguration.AcceptedDomain acceptedDomain in acceptedDomains)
            {
                if (acceptedDomain.DomainType != AcceptedDomainType.ExternalRelay)
                {
                    SmtpDomainWithSubdomains smtpDomainWithSubdomains = new SmtpDomainWithSubdomains(acceptedDomain.DomainName.Domain, acceptedDomain.DomainName.IncludeSubDomains || acceptedDomain.MatchSubDomains);
                    if (smtpDomainWithSubdomains.Match(domainStringRepresentation) >= 0)
                    {
                        return(true);
                    }
                }
            }
            ADPagedReader <DomainContentConfig> remoteDomains = null;

            ADNotificationAdapter.TryRunADOperation(delegate()
            {
                remoteDomains = session.FindAllPaged <DomainContentConfig>();
            });
            foreach (DomainContentConfig domainContentConfig in remoteDomains)
            {
                if (domainContentConfig.IsInternal && domainContentConfig.DomainName.Match(domainStringRepresentation) >= 0)
                {
                    return(true);
                }
            }
            return(false);
        }
コード例 #2
0
 public void Start(bool initiallyPaused, ServiceState targetRunningState)
 {
     lock (this.syncObject)
     {
         ADNotificationAdapter.RunADOperation(delegate()
         {
             try
             {
                 StoreDriverDelivery.localIp       = Dns.GetHostEntry("localhost");
                 StoreDriverDelivery.localFqdn     = StoreDriverDelivery.localIp.HostName;
                 StoreDriverDelivery.localDomain   = StoreDriverDelivery.GetDomainNameFromFqdn(StoreDriverDelivery.localFqdn);
                 StoreDriverDelivery.localHostName = StoreDriverDelivery.GetShortNameFromFqdn(StoreDriverDelivery.localFqdn);
             }
             catch (SocketException ex)
             {
                 StoreDriverDeliveryDiagnostics.Diag.TraceError <string>(0L, "Start failed: {0}", ex.ToString());
                 StoreDriverDeliveryDiagnostics.LogEvent(MailboxTransportEventLogConstants.Tuple_StoreDriverGetLocalIPFailure, null, new object[]
                 {
                     ex
                 });
                 throw new TransportComponentLoadFailedException(ex.Message, ex);
             }
             ProcessAccessManager.RegisterComponent(this);
             StoreDriverDeliveryDiagnostics.Diag.TraceDebug(0L, "Start delivery");
         }, 1);
     }
 }
コード例 #3
0
 public void Start(bool initiallyPaused, ServiceState targetRunningState)
 {
     lock (this.syncObject)
     {
         this.paused = initiallyPaused;
         ADNotificationAdapter.RunADOperation(delegate()
         {
             try
             {
                 StoreDriverSubmission.localIp = Dns.GetHostEntry(Dns.GetHostName());
             }
             catch (SocketException ex)
             {
                 this.storeDriverTracer.StoreDriverSubmissionTracer.TraceFail <string>(this.storeDriverTracer.MessageProbeActivityId, 0L, "Start failed: {0}", ex.ToString());
                 StoreDriverSubmission.LogEvent(MSExchangeStoreDriverSubmissionEventLogConstants.Tuple_StoreDriverSubmissionGetLocalIPFailure, null, new object[]
                 {
                     ex
                 });
                 throw new TransportComponentLoadFailedException(ex.Message, ex);
             }
             StoreDriverSubmission.receivedHeaderTcpInfo = StoreDriverSubmission.FormatIPAddress(StoreDriverSubmission.localIp.AddressList[0]);
             this.storeDriverTracer.StoreDriverSubmissionTracer.TracePass(this.storeDriverTracer.MessageProbeActivityId, 0L, "Start submission");
             this.StartSubmission();
         }, 1);
     }
 }
コード例 #4
0
 // Token: 0x06000592 RID: 1426 RVA: 0x00021394 File Offset: 0x0001F594
 private static ActiveSyncDeviceClasses GetActiveSyncDeviceClassContainer(IConfigurationSession scopedSession, OrganizationId orgId)
 {
     ActiveSyncDeviceClasses[] deviceClasses = null;
     ADNotificationAdapter.RunADOperation(delegate()
     {
         deviceClasses = scopedSession.Find <ActiveSyncDeviceClasses>(orgId.ConfigurationUnit, QueryScope.SubTree, DeviceClassCache.deviceClassesFilter, DeviceClassCache.deviceClassesSortOrder, 0);
     });
     DeviceClassCache.UpdateProtocolLogLastUsedDC(scopedSession);
     if (deviceClasses == null)
     {
         AirSyncDiagnostics.TraceDebug <OrganizationId>(ExTraceGlobals.RequestsTracer, null, "Oragnization \"{0}\" has no DeviceClass container in AD.", orgId);
         AirSyncDiagnostics.LogEvent(AirSyncEventLogConstants.Tuple_NoDeviceClassContainer, new string[]
         {
             orgId.ToString()
         });
         return(null);
     }
     AirSyncDiagnostics.TraceDebug <OrganizationId, int>(ExTraceGlobals.RequestsTracer, null, "Oragnization '{0}' has '{1}' DeviceClass container in AD.", orgId, deviceClasses.Length);
     if (deviceClasses.Length == 1)
     {
         return(deviceClasses[0]);
     }
     if (Command.CurrentCommand != null)
     {
         Command.CurrentCommand.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "TooManyDeviceClassContainers");
     }
     return(DeviceClassCache.CleanMangledObjects(scopedSession, deviceClasses, "ExchangeDeviceClasses") as ActiveSyncDeviceClasses);
 }
コード例 #5
0
 // Token: 0x060000AE RID: 174 RVA: 0x0000708C File Offset: 0x0000528C
 internal MobileDevice GetMobileDevice()
 {
     MobileDevice[] devices = null;
     ADNotificationAdapter.RunADOperation(delegate()
     {
         devices = this.session.Find <MobileDevice>(MobileDevice.GetRootId(this.userId), QueryScope.OneLevel, this.defaultDeviceFilter, ADDeviceManager.defaultSortOrder, 50);
     });
     if (this.protocolLogger != null)
     {
         this.protocolLogger.SetValue(ProtocolLoggerData.DomainController, this.session.LastUsedDc);
     }
     if (devices.Length == 1)
     {
         return(devices[0]);
     }
     if (devices.Length == 0)
     {
         return(null);
     }
     AirSyncDiagnostics.TraceDebug <string>(this.tracer, this, "User \"{0}\" has more than one device with same device ID and device type.", this.userName);
     if (this.protocolLogger != null)
     {
         this.protocolLogger.SetValue(ProtocolLoggerData.Error, "UserHasMoreThanOneDeviceWithSameDeviceIDandDeviceType-Cleaned");
     }
     return(this.CleanMangledObjects(devices));
 }
コード例 #6
0
        // Token: 0x060000BB RID: 187 RVA: 0x0000858C File Offset: 0x0000678C
        private void SetActiveSyncDeviceContainerPermissions(ActiveSyncDevices container)
        {
            ADDeviceManager.ReadStaticADData(this.protocolLogger);
            RawSecurityDescriptor rawSecurityDescriptor = null;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                rawSecurityDescriptor = this.session.ReadSecurityDescriptor(container.Id);
            });
            if (rawSecurityDescriptor == null)
            {
                if (this.protocolLogger != null)
                {
                    this.protocolLogger.SetValue(ProtocolLoggerData.Error, "ADObjectWithNoSecurityDescriptor");
                }
                AirSyncPermanentException ex = new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerError, EASServerStrings.NullNTSD(container.Id.DistinguishedName), true);
                throw ex;
            }
            AirSyncDiagnostics.TraceDebug <string>(this.tracer, this, "Setting ACL on device container for user \"{0}\".", this.userName);
            ActiveDirectorySecurity acl = new ActiveDirectorySecurity();

            byte[] array = new byte[rawSecurityDescriptor.BinaryLength];
            rawSecurityDescriptor.GetBinaryForm(array, 0);
            acl.SetSecurityDescriptorBinaryForm(array);
            acl.AddAccessRule(new ActiveDirectoryAccessRule(ADDeviceManager.exchangeServersGroupSid, ActiveDirectoryRights.CreateChild | ActiveDirectoryRights.DeleteChild | ActiveDirectoryRights.ListChildren | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow, ADDeviceManager.activeSyncDeviceClass, ActiveDirectorySecurityInheritance.None));
            acl.AddAccessRule(new ActiveDirectoryAccessRule(ADDeviceManager.exchangeServersGroupSid, ActiveDirectoryRights.Delete | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow, ActiveDirectorySecurityInheritance.Children, ADDeviceManager.activeSyncDeviceClass));
            ADNotificationAdapter.RunADOperation(delegate()
            {
                this.session.SaveSecurityDescriptor(container, new RawSecurityDescriptor(acl.GetSecurityDescriptorBinaryForm(), 0));
            });
        }
        private ADObjectId GetPolicyIdFromAD(OrganizationId key)
        {
            ExTraceGlobals.MobileDevicePolicyTracer.Information <OrganizationId>((long)this.GetHashCode(), "MobileDevicePolicyIdCacheByOrganization.GetPolicyFromAD({0})", key);
            ADSessionSettings     settings = ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(key);
            IConfigurationSession session  = this.GetConfigSession(settings);
            ADObjectId            rootId   = session.GetOrgContainerId();
            QueryFilter           filter   = new BitMaskAndFilter(MobileMailboxPolicySchema.MobileFlags, 4096UL);
            SortBy     sortBy   = new SortBy(ADObjectSchema.WhenChanged, SortOrder.Descending);
            ADObjectId policyId = null;

            try
            {
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    MobileMailboxPolicy[] array = session.Find <MobileMailboxPolicy>(rootId, QueryScope.SubTree, filter, sortBy, 1);
                    if (array != null && array.Length > 0)
                    {
                        policyId = array[0].Id;
                        OrgIdADObjectWrapper key2 = new OrgIdADObjectWrapper(policyId, key);
                        if (!MobileDevicePolicyCache.Instance.Contains(key2))
                        {
                            MobileDevicePolicyData mobileDevicePolicyDataFromMobileMailboxPolicy = MobileDevicePolicyDataFactory.GetMobileDevicePolicyDataFromMobileMailboxPolicy(array[0]);
                            MobileDevicePolicyCache.Instance.TryAdd(key2, ref mobileDevicePolicyDataFromMobileMailboxPolicy);
                        }
                    }
                });
            }
            catch (LocalizedException arg)
            {
                ExTraceGlobals.MobileDevicePolicyTracer.TraceError <OrganizationId, LocalizedException>((long)this.GetHashCode(), "MobileDevicePolicyIdCacheByOrganization.GetPolicyIdFromAD({0}) threw exception: {1}", key, arg);
                throw;
            }
            ExTraceGlobals.MobileDevicePolicyTracer.Information <OrganizationId, ADObjectId>((long)this.GetHashCode(), "MobileDevicePolicyIdCacheByOrganization.GetPolicyFromAD({0}) returned: {1}", key, policyId);
            return(policyId);
        }
コード例 #8
0
        private static void GetLogonUserInfo(SecurityIdentifier sid, string smtpDomain, out string smtpAddress, out string displayName, out string puid)
        {
            string smtpAddressTemporary = sid.ToString();
            string displayNameTemporary = sid.ToString();
            string puidTemporary        = string.Empty;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.RootOrgOrSingleTenantFromAcceptedDomainAutoDetect(smtpDomain), 339, "GetLogonUserInfo", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\attachment\\CachedAttachmentInfo.cs");
                PropertyDefinition[] properties = new PropertyDefinition[]
                {
                    ADRecipientSchema.PrimarySmtpAddress,
                    ADRecipientSchema.LegacyExchangeDN,
                    ADRecipientSchema.DisplayName,
                    ADUserSchema.NetID
                };
                ADRawEntry entry = tenantOrRootOrgRecipientSession.FindADRawEntryBySid(sid, properties);
                try
                {
                    CachedAttachmentInfo.SafeGetValue(entry, ADRecipientSchema.PrimarySmtpAddress, ref smtpAddressTemporary);
                    CachedAttachmentInfo.SafeGetValue(entry, ADRecipientSchema.DisplayName, ref displayNameTemporary);
                    CachedAttachmentInfo.SafeGetValue(entry, ADUserSchema.NetID, ref puidTemporary);
                }
                catch (NotInBagPropertyErrorException)
                {
                }
            });
            smtpAddress = smtpAddressTemporary;
            displayName = displayNameTemporary;
            puid        = puidTemporary;
        }
コード例 #9
0
 public static void DoAdCallAndTranslateExceptions(ADOperation call, bool expectObject, string debugContext)
 {
     Util.ThrowOnNullArgument(call, "call");
     try
     {
         ADNotificationAdapter.RunADOperation(call);
     }
     catch (DataValidationException innerException)
     {
         if (expectObject)
         {
             throw new ObjectNotFoundException(ServerStrings.ADUserNotFound, innerException);
         }
     }
     catch (DataSourceOperationException ex)
     {
         throw StorageGlobals.TranslateDirectoryException(ServerStrings.ADException, ex, null, "MigrationHelperBase::{0}. Failed for [{1}], due to directory exception.", new object[]
         {
             ex,
             debugContext
         });
     }
     catch (DataSourceTransientException ex2)
     {
         throw StorageGlobals.TranslateDirectoryException(ServerStrings.ADException, ex2, null, "MigrationHelperBase::{0}. Failed for [{1}], due to directory exception.", new object[]
         {
             ex2,
             debugContext
         });
     }
 }
コード例 #10
0
        private static ADObjectId GetRootOrgContainerIdForLocalForest()
        {
            ADObjectId rootOrgContainerIdForLocalForest = null;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                rootOrgContainerIdForLocalForest = ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest();
            });
            return(rootOrgContainerIdForLocalForest);
        }
コード例 #11
0
        // Token: 0x06001A8E RID: 6798 RVA: 0x0006F320 File Offset: 0x0006D520
        private Result <TEntry> LookUpRecipientInAD(ProxyAddress proxyAddress, ADPropertyDefinition[] properties)
        {
            if (ADRecipientCache <TEntry> .PerfCounters != null)
            {
                ADRecipientCache <TEntry> .PerfCounters.IndividualAddressLookupsTotal.Increment();

                ADRecipientCache <TEntry> .PerfCounters.RequestsPendingTotal.Increment();

                ADRecipientCache <TEntry> .PerfCounters.AggregateLookupsTotal.Increment();

                this.IncrementQueriesPerCacheCounter();
            }
            ComponentTrace <ADRecipientCacheTags> .TraceDebug <ProxyAddress>(0, -1L, "Lookup recipient {0}", proxyAddress);

            TEntry    entry     = default(TEntry);
            Stopwatch stopwatch = Stopwatch.StartNew();

            try
            {
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    if (typeof(TEntry) == typeof(ADRawEntry))
                    {
                        entry = (TEntry)((object)this.ADSession.FindByProxyAddress(proxyAddress, properties));
                        return;
                    }
                    if (typeof(TEntry) == typeof(TransportMiniRecipient))
                    {
                        entry = (this.ADSession.FindByProxyAddress <TransportMiniRecipient>(proxyAddress) as TEntry);
                        return;
                    }
                    throw new NotSupportedException();
                });
                if (entry == null)
                {
                    return(new Result <TEntry>(default(TEntry), ProviderError.NotFound));
                }
            }
            catch (DataValidationException ex)
            {
                ComponentTrace <ADRecipientCacheTags> .TraceError <DataValidationException>(0, -1L, "DataValidationException: {0}", ex);

                return(new Result <TEntry>(default(TEntry), ex.Error));
            }
            finally
            {
                stopwatch.Stop();
                if (ADRecipientCache <TEntry> .PerfCounters != null)
                {
                    ADRecipientCache <TEntry> .PerfCounters.AverageLookupQueryLatency.IncrementBy(stopwatch.ElapsedMilliseconds);
                }
                ADRecipientCache <TEntry> .DecrementPendingRequestsCounter();
            }
            return(new Result <TEntry>(entry, null));
        }
コード例 #12
0
        // Token: 0x06000204 RID: 516 RVA: 0x00007E54 File Offset: 0x00006054
        private bool TryExecuteWithExistingLogger(RequestDetailsLogger logger, out Dictionary <Guid, string> result)
        {
            Dictionary <Guid, string> paths = null;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                paths = this.ExecuteQuery(logger);
            });
            result = paths;
            return(result != null);
        }
コード例 #13
0
 // Token: 0x060000B6 RID: 182 RVA: 0x000077F0 File Offset: 0x000059F0
 private static void ReadStaticADData(ProtocolLogger logger)
 {
     if (!ADDeviceManager.initialized)
     {
         lock (ADDeviceManager.syncLock)
         {
             if (!ADDeviceManager.initialized)
             {
                 ITopologyConfigurationSession configSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 587, "ReadStaticADData", "f:\\15.00.1497\\sources\\dev\\AirSync\\src\\AirSync\\ADDeviceManager.cs");
                 configSession.UseConfigNC      = false;
                 configSession.UseGlobalCatalog = true;
                 ADGroup exchangeServersGroup = null;
                 ADNotificationAdapter.RunADOperation(delegate()
                 {
                     exchangeServersGroup = configSession.ResolveWellKnownGuid <ADGroup>(WellKnownGuid.ExSWkGuid, configSession.ConfigurationNamingContext);
                 });
                 if (exchangeServersGroup == null)
                 {
                     throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerError, EASServerStrings.FailedToResolveWellKnownGuid(WellKnownGuid.ExSWkGuid.ToString(), "Exchange Server Security Group"), true)
                           {
                               ErrorStringForProtocolLogger = "ExSrvGrpSchemaGuidNotFound"
                           };
                 }
                 ADDeviceManager.exchangeServersGroupSid = exchangeServersGroup.Sid;
                 if (logger != null)
                 {
                     logger.SetValue(ProtocolLoggerData.DomainController, configSession.LastUsedDc);
                 }
                 configSession.UseGlobalCatalog = false;
                 ADSchemaClassObject[] objClass = null;
                 ADNotificationAdapter.RunADOperation(delegate()
                 {
                     objClass = configSession.Find <ADSchemaClassObject>(configSession.SchemaNamingContext, QueryScope.OneLevel, new ComparisonFilter(ComparisonOperator.Equal, ADSchemaObjectSchema.DisplayName, "msExchActiveSyncDevice"), ADDeviceManager.defaultSortOrder, 2);
                 });
                 if (objClass == null || objClass.Length == 0 || objClass[0].SchemaIDGuid == Guid.Empty)
                 {
                     throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerError, EASServerStrings.CannotFindSchemaClassException("msExchActiveSyncDevice", configSession.SchemaNamingContext.DistinguishedName), true);
                 }
                 if (objClass.Length > 1 && logger != null)
                 {
                     logger.SetValue(ProtocolLoggerData.Error, "DisplayNameIsNotUniqueForClassMsExchActiveSyncDevice");
                 }
                 ADDeviceManager.activeSyncDeviceClass = objClass[0].SchemaIDGuid;
                 if (logger != null)
                 {
                     logger.SetValue(ProtocolLoggerData.DomainController, configSession.LastUsedDc);
                 }
                 ADDeviceManager.initialized = true;
             }
         }
     }
 }
コード例 #14
0
        // Token: 0x06000205 RID: 517 RVA: 0x00007F14 File Offset: 0x00006114
        private bool TryExecuteWithNewLogger(out Dictionary <Guid, string> result)
        {
            Dictionary <Guid, string> paths = null;

            SimulatedWebRequestContext.ExecuteWithoutUserContext("WAC.MdbCacheUpdate", delegate(RequestDetailsLogger logger)
            {
                WacUtilities.SetEventId(logger, "WAC.MdbCacheUpdate");
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    paths = this.ExecuteQuery(logger);
                });
            });
            result = paths;
            return(result != null);
        }
コード例 #15
0
 private void RunADOperation(object group, ADOperation adOperation)
 {
     try
     {
         ADNotificationAdapter.RunADOperation(adOperation);
     }
     catch (TransientException e)
     {
         this.RethrowException(group, e);
     }
     catch (DataValidationException e2)
     {
         this.RethrowException(group, e2);
     }
 }
コード例 #16
0
ファイル: ADUserCache.cs プロジェクト: YHZX2013/exchange_diff
 internal static ADSessionSettings GetSessionSettings(OrganizationId orgId, ProtocolLogger logger)
 {
     AirSyncDiagnostics.Assert(orgId != null);
     if (GlobalSettings.IsMultiTenancyEnabled)
     {
         AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, null, "organizationID :{0}", orgId.ToString());
         ADSessionSettings result = null;
         ADNotificationAdapter.RunADOperation(delegate()
         {
             result = ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(orgId);
         });
         return(result);
     }
     return(ADSessionSettings.FromRootOrgScopeSet());
 }
コード例 #17
0
 // Token: 0x06000597 RID: 1431 RVA: 0x00021628 File Offset: 0x0001F828
 private static void DeleteObject(IConfigurationSession scopedSession, ADConfigurationObject adObject)
 {
     try
     {
         ADNotificationAdapter.RunADOperation(delegate()
         {
             scopedSession.Delete(adObject);
         });
         DeviceClassCache.UpdateProtocolLogLastUsedDC(scopedSession);
         AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, null, "Deleted object: {0}", adObject.Id.DistinguishedName);
     }
     catch (LocalizedException ex)
     {
         AirSyncDiagnostics.TraceError <string, string>(ExTraceGlobals.RequestsTracer, null, "Failed to delete object {0} because: {1}", adObject.Id.DistinguishedName, ex.Message);
     }
 }
コード例 #18
0
ファイル: ADUtils.cs プロジェクト: YHZX2013/exchange_diff
 public static string[] GetAllEmailAddresses(string emailAddress, OrganizationId organizationId)
 {
     if (string.IsNullOrEmpty(emailAddress))
     {
         throw new ArgumentNullException("emailAddress");
     }
     if (organizationId == null)
     {
         throw new ArgumentNullException("organizationId");
     }
     if (emailAddress.IndexOf('@') > 0)
     {
         if (!SmtpAddress.IsValidSmtpAddress(emailAddress))
         {
             throw new ArgumentException(string.Format("emailAddress:{0} is not a valid ProxyAddress", emailAddress));
         }
         ProxyAddress      proxyAddress     = new SmtpProxyAddress(emailAddress, false);
         IRecipientSession recipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(organizationId), 345, "GetAllEmailAddresses", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\PolicyTips\\ADUtils.cs");
         ADRawEntry        lookupResult     = null;
         ADNotificationAdapter.RunADOperation(delegate()
         {
             lookupResult = recipientSession.FindByProxyAddress(proxyAddress, ADUtils.PropertiesToGet);
         });
         if (lookupResult != null)
         {
             ProxyAddressCollection proxyAddressCollection = (ProxyAddressCollection)lookupResult[ADRecipientSchema.EmailAddresses];
             if (proxyAddressCollection != null && proxyAddressCollection.Count > 0)
             {
                 string[] array = new string[proxyAddressCollection.Count];
                 int      num   = 0;
                 foreach (ProxyAddress proxyAddress2 in proxyAddressCollection)
                 {
                     array[num++] = proxyAddress2.AddressString;
                 }
                 return(array);
             }
         }
     }
     return(new string[]
     {
         emailAddress
     });
 }
コード例 #19
0
 // Token: 0x060000B0 RID: 176 RVA: 0x0000716C File Offset: 0x0000536C
 internal void UpdateMobileDevice(MobileDevice mobileDevice, GlobalInfo globalInfo)
 {
     if (mobileDevice == null)
     {
         throw new ArgumentNullException("mobileDevice");
     }
     GlobalInfo.CopyValuesFromGlobalInfo(mobileDevice, globalInfo);
     try
     {
         if (this.user != null)
         {
             mobileDevice.UserDisplayName = this.user.ToString();
         }
         ADNotificationAdapter.RunADOperation(delegate()
         {
             this.session.Save(mobileDevice);
         });
         if (this.protocolLogger != null)
         {
             this.protocolLogger.SetValue(ProtocolLoggerData.DomainController, this.session.LastUsedDc);
         }
     }
     catch (ADOperationException ex)
     {
         DirectoryOperationException ex2 = ex.InnerException as DirectoryOperationException;
         if (ex2 != null && ex2.Response != null && ex2.Response.ResultCode == ResultCode.InsufficientAccessRights)
         {
             AirSyncDiagnostics.TraceDebug <string, ADOperationException>(this.tracer, this, "Failed to save MobileDevice data to Active Directory for \"{0}\". \r\nException:\r\n{1}", this.userName, ex);
             AirSyncDiagnostics.LogEvent(this.directoryAccessDeniedEventTuple, new string[]
             {
                 this.userName
             });
             throw new AirSyncPermanentException(HttpStatusCode.Forbidden, StatusCode.AccessDenied, ex, false)
                   {
                       ErrorStringForProtocolLogger = ex2.GetType().FullName + ":ADDeviceSaveAccessDenied"
                   };
         }
         throw;
     }
 }
コード例 #20
0
        private MobileDevicePolicyData GetPolicyFromAD(OrgIdADObjectWrapper key)
        {
            ExTraceGlobals.MobileDevicePolicyTracer.Information <OrgIdADObjectWrapper>(0L, "MobileDevicePolicyCache.GetPolicyFromAD({0})", key);
            ADSessionSettings      settings   = ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(key.OrgId);
            IConfigurationSession  session    = this.GetConfigSession(settings);
            MobileDevicePolicyData policyData = null;

            try
            {
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    policyData = MobileDevicePolicyDataFactory.GetMobileDevicePolicyDataFromAD(session, key.AdObject);
                });
            }
            catch (LocalizedException arg)
            {
                ExTraceGlobals.MobileDevicePolicyTracer.TraceError <OrgIdADObjectWrapper, LocalizedException>((long)this.GetHashCode(), "MobileDevicePolicyCache.GetPolicyFromAD({0}) threw exception: {1}", key, arg);
                throw;
            }
            ExTraceGlobals.MobileDevicePolicyTracer.Information <OrgIdADObjectWrapper, MobileDevicePolicyData>((long)this.GetHashCode(), "MobileDevicePolicyCache.GetPolicyFromAD({0}) returned: {1}", key, policyData);
            return(policyData);
        }
コード例 #21
0
        // Token: 0x060000B4 RID: 180 RVA: 0x00007348 File Offset: 0x00005548
        internal bool DeleteMobileDevice(MobileDevice mobileDevice)
        {
            bool result;

            try
            {
                mobileDevice.SetIsReadOnly(false);
                mobileDevice.SetExchangeVersion(mobileDevice.MaximumSupportedExchangeObjectVersion);
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    this.session.Delete(mobileDevice);
                });
                result = true;
            }
            catch (ADOperationException ex)
            {
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, ex, false)
                      {
                          ErrorStringForProtocolLogger = string.Format("ADOperationException1:Message:{0}-Type:{1}", ex.Message.Replace(" ", "+").Substring(0, 20), ex.GetType())
                      };
            }
            return(result);
        }
コード例 #22
0
 // Token: 0x06000593 RID: 1427 RVA: 0x000214B0 File Offset: 0x0001F6B0
 private static void CreateOrUpdateActiveSyncDeviceClass(IConfigurationSession scopedSession, DeviceClassCache.DeviceClassData deviceClassData, OrganizationId orgId)
 {
     try
     {
         ActiveSyncDeviceClass deviceClass = deviceClassData.ToActiveSyncDeviceClass(scopedSession, orgId);
         deviceClass.LastUpdateTime = new DateTime?(DateTime.UtcNow);
         ADNotificationAdapter.RunADOperation(delegate()
         {
             scopedSession.Save(deviceClass);
         });
         DeviceClassCache.UpdateProtocolLogLastUsedDC(scopedSession);
         AirSyncDiagnostics.TraceDebug <OrganizationId, string, string>(ExTraceGlobals.RequestsTracer, null, "Created DeviceClassData in AD: orgId={0}, deviceType={1}, deviceModel={2}", orgId, deviceClassData.DeviceType, deviceClassData.DeviceModel);
     }
     catch (LocalizedException ex)
     {
         AirSyncDiagnostics.TraceDebug(ExTraceGlobals.RequestsTracer, null, "Failed to create DeviceClassData: orgId={0}, deviceType={1}, deviceModel={2}, exception=\n\r{3}", new object[]
         {
             orgId,
             deviceClassData.DeviceType,
             deviceClassData.DeviceModel,
             ex
         });
     }
 }
コード例 #23
0
 // Token: 0x06000599 RID: 1433 RVA: 0x00021738 File Offset: 0x0001F938
 private void Refresh(object state)
 {
     try
     {
         AirSyncDiagnostics.TraceDebug <ExDateTime>(ExTraceGlobals.RequestsTracer, this, "Refresh is being call at '{0}-UTC'.", ExDateTime.UtcNow);
         AirSyncDiagnostics.TraceDebug <int>(ExTraceGlobals.RequestsTracer, this, "DeviceClassCache contains '{0}' elements.", this.cache.Values.Count);
         List <DeviceClassCache.DeviceClassDataSet> list;
         lock (this.thisLock)
         {
             if (this.cache.Values.Count < 1)
             {
                 return;
             }
             list = new List <DeviceClassCache.DeviceClassDataSet>(this.cache.Values);
         }
         int num = 0;
         foreach (DeviceClassCache.DeviceClassDataSet deviceClassDataSet in list)
         {
             if (this.realTimeRefresh || !(ExDateTime.UtcNow - deviceClassDataSet.StartTime < TimeSpan.FromSeconds((double)GlobalSettings.DeviceClassCachePerOrgRefreshInterval)))
             {
                 if (num >= GlobalSettings.DeviceClassCacheMaxADUploadCount)
                 {
                     AirSyncDiagnostics.TraceDebug <int>(ExTraceGlobals.RequestsTracer, this, "1. Stop updating AD because the cap is reached: adUpdateCount={0}", num);
                     break;
                 }
                 lock (this.thisLock)
                 {
                     if (!this.cache.ContainsKey(deviceClassDataSet.OrganizationId))
                     {
                         AirSyncDiagnostics.TraceDebug <OrganizationId>(ExTraceGlobals.RequestsTracer, this, "Organization {0} is already removed from the cache by another thread", deviceClassDataSet.OrganizationId);
                         continue;
                     }
                     this.cache.Remove(deviceClassDataSet.OrganizationId);
                 }
                 using (deviceClassDataSet)
                 {
                     IConfigurationSession   scopedSession        = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(false, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(deviceClassDataSet.OrganizationId), 930, "Refresh", "f:\\15.00.1497\\sources\\dev\\AirSync\\src\\AirSync\\DeviceClassCache.cs");
                     ActiveSyncDeviceClasses deviceClassContainer = DeviceClassCache.GetActiveSyncDeviceClassContainer(scopedSession, deviceClassDataSet.OrganizationId);
                     if (deviceClassContainer != null)
                     {
                         ADPagedReader <ActiveSyncDeviceClass> deviceClassReader = null;
                         ADNotificationAdapter.RunADOperation(delegate()
                         {
                             deviceClassReader = scopedSession.FindPaged <ActiveSyncDeviceClass>(deviceClassContainer.Id, QueryScope.OneLevel, null, null, 0);
                         });
                         DeviceClassCache.UpdateProtocolLogLastUsedDC(scopedSession);
                         if (deviceClassReader != null)
                         {
                             using (DeviceClassCache.DeviceClassDataSet deviceClassDataSet3 = new DeviceClassCache.DeviceClassDataSet(deviceClassDataSet.OrganizationId))
                             {
                                 foreach (ActiveSyncDeviceClass activeSyncDeviceClass in deviceClassReader)
                                 {
                                     if (!string.IsNullOrEmpty(activeSyncDeviceClass.DeviceType) && !string.IsNullOrEmpty(activeSyncDeviceClass.DeviceModel) && activeSyncDeviceClass.LastUpdateTime != null)
                                     {
                                         string commonName = ActiveSyncDeviceClass.GetCommonName(activeSyncDeviceClass.DeviceType, activeSyncDeviceClass.DeviceModel);
                                         if (DeviceClassCache.DnIsMangled(activeSyncDeviceClass, commonName))
                                         {
                                             AirSyncDiagnostics.TraceDebug <ADObjectId>(ExTraceGlobals.RequestsTracer, this, "Delete the Mangled DeviceClassCache {0}.", activeSyncDeviceClass.Id);
                                             DeviceClassCache.DeleteObject(scopedSession, activeSyncDeviceClass);
                                             num++;
                                         }
                                         else
                                         {
                                             deviceClassDataSet3.Add(new DeviceClassCache.DeviceClassData(activeSyncDeviceClass));
                                         }
                                     }
                                     else
                                     {
                                         AirSyncDiagnostics.TraceDebug <string, string, DateTime?>(ExTraceGlobals.RequestsTracer, this, "Delete the DeviceClassCache. Either DeviceType, DeviceModel or LastupdatTime is null. DeviceType:{0}, DeviceModel:{1}, LastUpdateTime:{2}.", activeSyncDeviceClass.DeviceType, activeSyncDeviceClass.DeviceModel, activeSyncDeviceClass.LastUpdateTime);
                                         DeviceClassCache.DeleteObject(scopedSession, activeSyncDeviceClass);
                                         num++;
                                     }
                                 }
                                 DeviceClassCache.UpdateProtocolLogLastUsedDC(scopedSession);
                                 AirSyncDiagnostics.TraceDebug <int, OrganizationId>(ExTraceGlobals.RequestsTracer, this, "'{0}' device classes are loaded from AD for org '{1}'", deviceClassDataSet3.Count, deviceClassDataSet.OrganizationId);
                                 int perOrgDeleteCount = 0;
                                 DeviceClassCache.ProcessForADCleanup(scopedSession, deviceClassDataSet, deviceClassDataSet3, ref num, ref perOrgDeleteCount);
                                 DeviceClassCache.ProcessForADAdds(scopedSession, deviceClassDataSet, deviceClassDataSet3, ref num, perOrgDeleteCount);
                             }
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         AirSyncUtility.ProcessException(ex);
     }
 }
コード例 #24
0
        // Token: 0x060000B7 RID: 183 RVA: 0x00007A20 File Offset: 0x00005C20
        private ActiveSyncDevices CreateActiveSyncDeviceContainer(bool retryIfFailed)
        {
            ActiveSyncDevices container = new ActiveSyncDevices();

            try
            {
                container.Name = "ExchangeActiveSyncDevices";
                container.SetId(this.userId.GetChildId(container.Name));
                container.OrganizationId = this.organizationId;
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    this.session.Save(container);
                    this.session.DomainController = container.OriginatingServer;
                });
            }
            catch (ADObjectAlreadyExistsException innerException)
            {
                container = this.GetActiveSyncDeviceContainer();
                if (container == null)
                {
                    throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, innerException, false)
                          {
                              ErrorStringForProtocolLogger = "ADObjectAlreadyExistsException:ButDevicesContainerDoesNotExist"
                          };
                }
            }
            catch (ADOperationException ex)
            {
                AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_UnableToCreateADDevicesContainer, container.Name, new string[]
                {
                    this.userId.ToDNString(),
                    ex.Message
                });
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, ex, false)
                      {
                          ErrorStringForProtocolLogger = "ADOperationException1:" + ex.Message
                      };
            }
            bool flag = false;

            try
            {
                this.SetActiveSyncDeviceContainerPermissions(container);
                flag = true;
            }
            catch (ADNoSuchObjectException innerException2)
            {
                if (retryIfFailed)
                {
                    return(this.CreateActiveSyncDeviceContainer(false));
                }
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, innerException2, false)
                      {
                          ErrorStringForProtocolLogger = "ADNoSuchObjectException:OnDevicesContainerPermsSet"
                      };
            }
            catch (ADOperationException ex2)
            {
                AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_UnableToCreateADDevicesContainer, "ExchangeActiveSyncDevices", new string[]
                {
                    this.userId.ToDNString(),
                    ex2.Message
                });
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, ex2, false)
                      {
                          ErrorStringForProtocolLogger = "ADOperationException2:" + ex2.Message
                      };
            }
            finally
            {
                if (!flag)
                {
                    try
                    {
                        ADNotificationAdapter.RunADOperation(delegate()
                        {
                            this.session.Delete(container);
                        });
                    }
                    catch (LocalizedException arg)
                    {
                        AirSyncDiagnostics.TraceError <LocalizedException>(this.tracer, this, "Failed to delete user container {0}", arg);
                    }
                }
            }
            return(container);
        }
コード例 #25
0
        // Token: 0x060000B8 RID: 184 RVA: 0x00007D00 File Offset: 0x00005F00
        private MobileDevice CreateMobileDevice(GlobalInfo globalInfo, ExDateTime syncStorageCreationTime, bool checkForMaxDevices, bool retryIfFailed, MailboxSession mailboxSession)
        {
            ActiveSyncDevices activeSyncDevices = this.GetActiveSyncDeviceContainer();

            if (activeSyncDevices == null)
            {
                activeSyncDevices = this.CreateActiveSyncDeviceContainer(true);
            }
            AirSyncDiagnostics.TraceInfo <MobileClientType, DeviceIdentity, string>(ExTraceGlobals.RequestsTracer, null, "ADDeviceManager::CreateMobileDevice - ClientType: {0}, DeviceIdentity: {1}, mailboxSession from: {2}", this.clientType, this.deviceIdentity, (mailboxSession == null) ? "CurrentCommand" : "parameter");
            this.CleanUpOldDevices(mailboxSession ?? Command.CurrentCommand.MailboxSession);
            MobileDevice      mobileDevice     = this.InternalCreateDevice(globalInfo, syncStorageCreationTime);
            IThrottlingPolicy throttlingPolicy = (this.budget != null) ? this.budget.ThrottlingPolicy : null;

            if (checkForMaxDevices && throttlingPolicy != null)
            {
                if (!throttlingPolicy.EasMaxDevices.IsUnlimited)
                {
                    MobileDevice[] easDevices = null;
                    ADNotificationAdapter.RunADOperation(delegate()
                    {
                        easDevices = this.session.Find <MobileDevice>(MobileDevice.GetRootId(this.userId), QueryScope.OneLevel, new ComparisonFilter(ComparisonOperator.LessThanOrEqual, ADObjectSchema.ExchangeVersion, ExchangeObjectVersion.Exchange2012), null, 0);
                    });
                    if (this.protocolLogger != null)
                    {
                        this.protocolLogger.SetValue(ProtocolLoggerData.DomainController, this.session.LastUsedDc);
                    }
                    if (easDevices != null && (long)easDevices.Length >= (long)((ulong)throttlingPolicy.EasMaxDevices.Value))
                    {
                        this.SendMaxDevicesExceededMailIfNeeded(easDevices.Length, throttlingPolicy.EasMaxDevices.Value);
                        throw new AirSyncPermanentException(HttpStatusCode.Forbidden, StatusCode.MaximumDevicesReached, null, false)
                              {
                                  ErrorStringForProtocolLogger = "MaxDevicesExceeded"
                              };
                    }
                }
                else
                {
                    AirSyncDiagnostics.TraceDebug(this.tracer, this, "throttlingPolicy.EasMaxDevices is unlimited. Skipping max devices check.");
                }
            }
            else
            {
                AirSyncDiagnostics.TraceDebug(this.tracer, this, "No throttling policy is found. Skipping max devices check.");
            }
            switch (mobileDevice.ClientType)
            {
            case MobileClientType.EAS:
                mobileDevice.SetId(activeSyncDevices.Id.GetChildId(ADDeviceManager.EasDeviceCnString(mobileDevice)));
                break;

            case MobileClientType.MOWA:
                mobileDevice.SetId(activeSyncDevices.Id.GetChildId(ADDeviceManager.MowaDeviceCnString(mobileDevice)));
                break;

            default:
                throw new PlatformNotSupportedException("New MobileClientType is not supported.");
            }
            try
            {
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    this.session.Save(mobileDevice);
                });
            }
            catch (ADObjectAlreadyExistsException)
            {
                mobileDevice = this.GetMobileDevice();
                if (mobileDevice == null)
                {
                    throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, EASServerStrings.FailedToCreateNewActiveDevice(this.deviceIdentity.DeviceId, this.deviceIdentity.DeviceType, this.userName), true)
                          {
                              ErrorStringForProtocolLogger = "CreateActiveSyncDevice:ADObjectAlreadyExistsException"
                          };
                }
                if (globalInfo != null)
                {
                    this.UpdateMobileDevice(mobileDevice, globalInfo);
                }
            }
            catch (ADOperationException ex)
            {
                DirectoryOperationException ex2 = ex.InnerException as DirectoryOperationException;
                if (retryIfFailed)
                {
                    if (ex.ErrorCode != 5)
                    {
                        if (ex2 == null || ex2.Response == null || ex2.Response.ResultCode != ResultCode.InsufficientAccessRights)
                        {
                            goto IL_308;
                        }
                    }
                    try
                    {
                        this.SetActiveSyncDeviceContainerPermissions(activeSyncDevices);
                    }
                    catch (ADOperationException ex3)
                    {
                        throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, EASServerStrings.FailedToApplySecurityToContainer(activeSyncDevices.DistinguishedName), ex3, true)
                              {
                                  ErrorStringForProtocolLogger = "SetEASDevContainerPerms:ADOperationException:" + ex3.Message
                              };
                    }
                    return(this.CreateMobileDevice(globalInfo, syncStorageCreationTime, checkForMaxDevices, false, mailboxSession));
                }
IL_308:
                AirSyncDiagnostics.LogEvent(this.unableToCreateADDeviceEventTuple, new string[]
                {
                    mobileDevice.DeviceType,
                    mobileDevice.DeviceId,
                    activeSyncDevices.Id.ToDNString(),
                    ex.Message
                });
                throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerErrorRetryLater, ex, false)
                      {
                          ErrorStringForProtocolLogger = "CreateActiveSyncDevice:ADOperationException" + ex.Message
                      };
            }
            return(mobileDevice);
        }
コード例 #26
0
        // Token: 0x06001A77 RID: 6775 RVA: 0x0006E6D4 File Offset: 0x0006C8D4
        public virtual IList <Result <TEntry> > FindAndCacheRecipients(IList <ProxyAddress> proxyAddressList)
        {
            if (proxyAddressList == null)
            {
                throw new ArgumentNullException("proxyAddressList");
            }
            List <Result <TEntry> > list    = new List <Result <TEntry> >(proxyAddressList.Count);
            List <ProxyAddress>     proxies = new List <ProxyAddress>(proxyAddressList.Count);
            List <int> list2 = new List <int>(proxyAddressList.Count);

            lock (this.dictionaryLock)
            {
                int num = 0;
                foreach (ProxyAddress proxyAddress in proxyAddressList)
                {
                    Result <TEntry> item = new Result <TEntry>(default(TEntry), null);
                    if (null == proxyAddress || this.dictionary.TryGetValue(proxyAddress, out item))
                    {
                        list.Add(item);
                    }
                    else
                    {
                        list.Add(item);
                        proxies.Add(proxyAddress);
                        list2.Add(num);
                    }
                    num++;
                }
            }
            if (ADRecipientCache <TEntry> .PerfCounters != null)
            {
                ADRecipientCache <TEntry> .PerfCounters.AggregateHits_Base.Increment();

                if (list2.Count == 0)
                {
                    ADRecipientCache <TEntry> .PerfCounters.AggregateHits.Increment();
                }
                else
                {
                    int num2 = list2.Count / ADRecipientCache <TEntry> .BatchSize;
                    if (list2.Count % ADRecipientCache <TEntry> .BatchSize != 0)
                    {
                        num2++;
                    }
                    ADRecipientCache <TEntry> .PerfCounters.AggregateMisses.IncrementBy((long)num2);
                }
            }
            if (proxies.Count == 0)
            {
                return(list);
            }
            if (ADRecipientCache <TEntry> .PerfCounters != null)
            {
                ADRecipientCache <TEntry> .PerfCounters.BatchedAddressLookupsTotal.Increment();

                ADRecipientCache <TEntry> .PerfCounters.RequestsPendingTotal.Increment();

                ADRecipientCache <TEntry> .PerfCounters.AggregateLookupsTotal.Increment();

                this.IncrementQueriesPerCacheCounter();
            }
            Result <TEntry>[] rawResults = null;
            Stopwatch         stopwatch  = Stopwatch.StartNew();

            try
            {
                int i;
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    if (typeof(TEntry) == typeof(ADRawEntry))
                    {
                        Result <ADRawEntry>[] source = this.ADSession.FindByProxyAddresses(proxies.ToArray(), this.properties);
                        rawResults = (from i in source
                                      select new Result <TEntry>((TEntry)((object)i.Data), i.Error)).ToArray <Result <TEntry> >();
                        return;
                    }
                    if (typeof(TEntry) == typeof(TransportMiniRecipient))
                    {
                        Result <TransportMiniRecipient>[] source2 = this.ADSession.FindByProxyAddresses <TransportMiniRecipient>(proxies.ToArray());
                        rawResults = (from i in source2
                                      select new Result <TEntry>(i.Data as TEntry, i.Error)).ToArray <Result <TEntry> >();
                        return;
                    }
                    throw new NotSupportedException();
                });
            }
            finally
            {
                stopwatch.Stop();
                if (ADRecipientCache <TEntry> .PerfCounters != null)
                {
                    ADRecipientCache <TEntry> .PerfCounters.AverageLookupQueryLatency.IncrementBy(stopwatch.ElapsedMilliseconds);
                }
                ADRecipientCache <TEntry> .DecrementPendingRequestsCounter();
            }
            for (int i = 0; i < rawResults.Length; i++)
            {
                if (rawResults[i].Data != null)
                {
                    this.PopulateCalculatedProperties(rawResults[i].Data);
                }
                list[list2[i]] = rawResults[i];
            }
            bool flag2 = false;

            lock (this.dictionaryLock)
            {
                for (int j = 0; j < proxies.Count; j++)
                {
                    Result <TEntry> value;
                    if (proxies[j] != null && this.dictionary.TryGetValue(proxies[j], out value))
                    {
                        list[list2[j]] = value;
                        flag2          = true;
                    }
                    else
                    {
                        this.AddCacheEntry(proxies[j], list[list2[j]], false, false);
                    }
                }
            }
            if (flag2 && ADRecipientCache <TEntry> .PerfCounters != null)
            {
                ADRecipientCache <TEntry> .PerfCounters.RepeatedQueryForTheSameRecipient.Increment();
            }
            return(list);
        }
コード例 #27
0
        private EdgeSyncRecord TestSyncHealth(string domainController)
        {
            ITopologyConfigurationSession session = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(domainController, true, ConsistencyMode.PartiallyConsistent, ADSessionSettings.FromRootOrgScopeSet(), 383, "TestSyncHealth", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\transport\\EdgeSync\\TestEdgeSyncBase.cs");
            ADSite localSite             = null;
            EdgeSyncServiceConfig config = null;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                localSite = session.GetLocalSite();
                if (localSite == null)
                {
                    throw new TransientException(Strings.CannotGetLocalSite);
                }
                config = session.Read <EdgeSyncServiceConfig>(localSite.Id.GetChildId("EdgeSyncService"));
            }, 3);
            if (config == null)
            {
                return(EdgeSyncRecord.GetEdgeSyncServiceNotConfiguredForCurrentSiteRecord(this.Service, localSite.Name));
            }
            bool   flag = false;
            string primaryLeaseFilePath;
            string backupLeaseFilePath;

            if (!this.ReadConnectorLeasePath(session, config.Id, out primaryLeaseFilePath, out backupLeaseFilePath, out flag))
            {
                if (!flag)
                {
                    return(EdgeSyncRecord.GetEdgeSyncConnectorNotConfiguredForEntireForestRecord(this.Service));
                }
                return(EdgeSyncRecord.GetEdgeSyncConnectorNotConfiguredForCurrentSiteRecord(this.Service, localSite.Name));
            }
            else
            {
                string     additionalInfo = null;
                LeaseToken lease          = TestEdgeSyncBase.GetLease(primaryLeaseFilePath, backupLeaseFilePath, out additionalInfo);
                if (lease.NotHeld)
                {
                    return(EdgeSyncRecord.GetFailedRecord(this.Service, base.MyInvocation.MyCommand.Name, "There is no lease file detected. It suggests synchronization has not started at all.", lease, null, additionalInfo));
                }
                Cookie cookie = null;
                string text   = null;
                if (!this.TryGetNewestCookieFromAllDomainControllers(out cookie, out text))
                {
                    throw new InvalidOperationException("Failed accessing all DCs: " + text);
                }
                if (cookie == null)
                {
                    return(EdgeSyncRecord.GetFailedRecord(this.Service, base.MyInvocation.MyCommand.Name, "There is no cookie detected. It suggests we haven't had a single successful synchronization.", lease, null, text));
                }
                EnhancedTimeSpan syncInterval = this.GetSyncInterval(config);
                switch (lease.Type)
                {
                case LeaseTokenType.Lock:
                    if (DateTime.UtcNow > lease.AlertTime)
                    {
                        return(EdgeSyncRecord.GetFailedRecord(this.Service, base.MyInvocation.MyCommand.Name, "Synchronization has completely stopped because lock has expired. It suggests the EdgeSync service died in the middle of the synchronization and no other service instance has taken over.", lease, cookie, text, true));
                    }
                    if (DateTime.UtcNow > cookie.LastUpdated + config.OptionDuration + 3L * syncInterval + TimeSpan.FromHours(1.0))
                    {
                        return(EdgeSyncRecord.GetFailedRecord(this.Service, base.MyInvocation.MyCommand.Name, "Cookie has not been updated as expected. It might be caused by failure to synchronize some items which means that the sychronization might still be running but not efficiently. It might also be caused by a long full sync. Check EdgeSync log for further troubleshooting.", lease, cookie, text));
                    }
                    return(EdgeSyncRecord.GetInconclusiveRecord(this.Service, base.MyInvocation.MyCommand.Name, "Synchronization status is inconclusive because EdgeSync is in the middle of synchronizing data. Try running this cmdlet again later.", lease, cookie, text));

                case LeaseTokenType.Option:
                    if (DateTime.UtcNow > lease.AlertTime)
                    {
                        return(EdgeSyncRecord.GetFailedRecord(this.Service, base.MyInvocation.MyCommand.Name, "Synchronization has completely stopped. We have failed to failover to another instance within the same AD site or to another AD site.", lease, cookie, text, true));
                    }
                    if (DateTime.UtcNow > cookie.LastUpdated + config.FailoverDCInterval + TimeSpan.FromMinutes(30.0))
                    {
                        return(EdgeSyncRecord.GetFailedRecord(this.Service, base.MyInvocation.MyCommand.Name, "Cookie has not been updated as expected. It might be caused by failure to synchronize some items which means that the sychronization might still be running but not efficiently. It might also be caused by a long full sync. Check EdgeSync log for further troubleshooting.", lease, cookie, text));
                    }
                    return(EdgeSyncRecord.GetNormalRecord(this.Service, "The synchronization is operating normally.", lease, cookie, text));

                default:
                    throw new ArgumentException("Unknown lease type: " + lease.Type);
                }
            }
        }
コード例 #28
0
        // Token: 0x06001A76 RID: 6774 RVA: 0x0006E40C File Offset: 0x0006C60C
        public virtual Result <TEntry> FindAndCacheRecipient(ADObjectId objectId)
        {
            if (objectId == null)
            {
                throw new ArgumentNullException("objectId");
            }
            if (ADRecipientCache <TEntry> .PerfCounters != null)
            {
                ADRecipientCache <TEntry> .PerfCounters.IndividualAddressLookupsTotal.Increment();

                ADRecipientCache <TEntry> .PerfCounters.RequestsPendingTotal.Increment();

                ADRecipientCache <TEntry> .PerfCounters.AggregateHits_Base.Increment();

                ADRecipientCache <TEntry> .PerfCounters.AggregateMisses.Increment();

                ADRecipientCache <TEntry> .PerfCounters.AggregateLookupsTotal.Increment();

                this.IncrementQueriesPerCacheCounter();
            }
            Stopwatch       stopwatch = Stopwatch.StartNew();
            Result <TEntry> result;

            try
            {
                TEntry entry = default(TEntry);
                ADNotificationAdapter.RunADOperation(delegate()
                {
                    if (typeof(TEntry) == typeof(TransportMiniRecipient))
                    {
                        entry = (this.ADSession.ReadMiniRecipient <TransportMiniRecipient>(objectId, this.properties) as TEntry);
                        return;
                    }
                    if (this.isFullADRecipientObject)
                    {
                        entry = (TEntry)((object)this.ADSession.Read(objectId));
                        return;
                    }
                    entry = (TEntry)((object)this.ADSession.ReadADRawEntry(objectId, this.properties));
                });
                if (entry == null)
                {
                    result = new Result <TEntry>(default(TEntry), ProviderError.NotFound);
                }
                else
                {
                    result = new Result <TEntry>(entry, null);
                }
            }
            catch (DataValidationException ex)
            {
                ComponentTrace <ADRecipientCacheTags> .TraceError <DataValidationException>(0, -1L, "DataValidationException: {0}", ex);

                result = new Result <TEntry>(default(TEntry), ex.Error);
            }
            finally
            {
                stopwatch.Stop();
                if (ADRecipientCache <TEntry> .PerfCounters != null)
                {
                    ADRecipientCache <TEntry> .PerfCounters.AverageLookupQueryLatency.IncrementBy(stopwatch.ElapsedMilliseconds);
                }
                ADRecipientCache <TEntry> .DecrementPendingRequestsCounter();
            }
            if (result.Data != null)
            {
                ProxyAddress primarySmtpAddress = ADRecipientCache <TEntry> .GetPrimarySmtpAddress(result.Data);

                if (primarySmtpAddress != null)
                {
                    this.AddCacheEntry(primarySmtpAddress, result);
                }
            }
            return(result);
        }