// Token: 0x060000BA RID: 186 RVA: 0x0000843C File Offset: 0x0000663C
        private bool CleanUpMangledDevices(List <MobileDevice> mobileDevices, out int noOfDevicesRemoved)
        {
            noOfDevicesRemoved = 0;
            ExDateTime utcNow = ExDateTime.UtcNow;

            for (int i = mobileDevices.Count - 1; i >= 0; i--)
            {
                MobileDevice device = mobileDevices[i];
                if (ADDeviceManager.DnIsMangled(device.Name) || ADDeviceManager.DnIsMangled(device.DeviceId))
                {
                    ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                    {
                        this.session.Delete(device);
                    });
                    if (!adoperationResult.Succeeded)
                    {
                        AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, null, "Exception occurred during AD Operation during . Message:{0}", adoperationResult.Exception.Message);
                    }
                    noOfDevicesRemoved++;
                    mobileDevices.RemoveAt(i);
                }
                TimeSpan t = ExDateTime.UtcNow.Subtract(utcNow);
                if (t >= GlobalSettings.MaxCleanUpExecutionTime)
                {
                    AirSyncDiagnostics.TraceDebug <int, double>(ExTraceGlobals.RequestsTracer, null, "Done Cleaning up stale devices. DevicesCleaned:{0}, ExecutionTime(in ms):{1}", noOfDevicesRemoved, t.TotalMilliseconds);
                    return(false);
                }
            }
            return(true);
        }
        // Token: 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));
            });
        }
        // Token: 0x060000BF RID: 191 RVA: 0x00008A20 File Offset: 0x00006C20
        private bool DnIsMangled(MobileDevice device)
        {
            string escapedName = device.Id.Rdn.EscapedName;
            string value       = ADDeviceManager.EasDeviceCnString(device);

            if (!escapedName.Equals(value, StringComparison.Ordinal))
            {
                string value2 = ADDeviceManager.MowaDeviceCnString(device);
                if (!escapedName.Equals(value2, StringComparison.Ordinal))
                {
                    AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "Found mangled device object DN: {0}", device.Id.DistinguishedName);
                    return(true);
                }
            }
            return(false);
        }
        // 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);
        }