Exemple #1
0
 // Token: 0x06000298 RID: 664 RVA: 0x0000F900 File Offset: 0x0000DB00
 public ELCHealthMonitor(Guid databaseGuid, string databaseName, ResourceKey[] primaryResourceDependencies)
 {
     this.databaseGuid = databaseGuid;
     this.databaseName = databaseName;
     this.budget       = StandardBudget.AcquireUnthrottledBudget(this.databaseGuid.ToString(), BudgetType.ResourceTracking);
     this.primaryResourceDependencies = primaryResourceDependencies;
     this.sleepWaitHandle             = new EventWaitHandle(false, EventResetMode.ManualReset);
 }
Exemple #2
0
        private bool ExecuteWithinBudget()
        {
            if (this.budget == null)
            {
                PublicFolderSynchronizer.Tracer.TraceDebug((long)this.GetHashCode(), "Acquiring budget");
                this.budget = StandardBudget.Acquire(PublicFolderSynchronizer.BudgetKey);
            }
            else
            {
                PublicFolderSynchronizer.Tracer.TraceDebug((long)this.GetHashCode(), "Resetting budget");
                this.budget.ResetWorkAccomplished();
            }
            TimeSpan timeSpan;

            for (;;)
            {
                PublicFolderSynchronizer.< > c__DisplayClass11 CS$ < > 8__locals1 = new PublicFolderSynchronizer.< > c__DisplayClass11();
                CS$ < > 8__locals1.< > 4__this = this;
                timeSpan = TimeSpan.Zero;
                CS$ < > 8__locals1.moreBatchesToProcess = false;
                bool flag = this.transientExceptionHandler.TryExecute(new TryDelegate(CS$ < > 8__locals1, (UIntPtr)ldftn(< ExecuteWithinBudget > b__10)));
                if (flag)
                {
                    PublicFolderSynchronizer.Tracer.TraceDebug((long)this.GetHashCode(), "Batch executed successfully");
                    if (!CS$ < > 8__locals1.moreBatchesToProcess)
                    {
                        break;
                    }
                }
                else
                {
                    PublicFolderSynchronizer.Tracer.TraceDebug((long)this.GetHashCode(), "Batch failed execution. Calculating Delays.");
                    int num = Math.Min(this.transientExceptionHandler.TransientExceptionCount, PublicFolderSynchronizer.FibonacciSequence.Length) - 1;
                    timeSpan = TimeSpan.FromMinutes((double)PublicFolderSynchronizer.FibonacciSequence[num]);
                }
                TimeSpan resourceMonitorDelay = this.GetResourceMonitorDelay();
                if (resourceMonitorDelay > timeSpan)
                {
                    timeSpan = resourceMonitorDelay;
                }
                if (timeSpan > TimeSpan.Zero)
                {
                    goto Block_5;
                }
            }
            PublicFolderSynchronizer.Tracer.TraceDebug((long)this.GetHashCode(), "No more batches to process, exiting");
            return(true);

Block_5:
            PublicFolderSynchronizerLogger.LogOnServer("Delay=" + timeSpan.TotalMilliseconds, LogEventType.Verbose, new Guid?(this.syncContext.CorrelationId));
            if (this.timer == null)
            {
                this.timer = new Timer(new TimerCallback(this.TimerExecute));
            }
            PublicFolderSynchronizer.Tracer.TraceDebug <TimeSpan>((long)this.GetHashCode(), "Setting timer to wake up in: {0}", timeSpan);
            this.timer.Change(timeSpan, TimeSpan.Zero);
            return(false);
        }
 // Token: 0x060002FA RID: 762 RVA: 0x0000FAA0 File Offset: 0x0000DCA0
 void IAirSyncUser.AcquireBudget()
 {
     if (((IAirSyncUser)this).Budget != null)
     {
         return;
     }
     this.Budget = StandardBudget.Acquire(((IAirSyncUser)this).BudgetKey);
     ((IAirSyncUser)this).SetBudgetDiagnosticValues(true);
     this.context.ProtocolLogger.SetValue(ProtocolLoggerData.Budget, "(A)" + ((IAirSyncUser)this).Budget.ToString());
 }
Exemple #4
0
        // Token: 0x06000D98 RID: 3480 RVA: 0x0005A4FC File Offset: 0x000586FC
        internal void AcquireBudgetAndStartTiming()
        {
            string callerInfo = "OwaContext.AcquireBudgetAndStartTiming";

            this.budget = StandardBudget.Acquire(this.LogonIdentity.UserSid, BudgetType.Owa, Utilities.CreateScopedADSessionSettings(this.LogonIdentity.DomainName));
            this.budget.CheckOverBudget();
            this.budget.StartConnection(callerInfo);
            this.budget.StartLocal(callerInfo, default(TimeSpan));
            this.httpContext.Response.AppendToLog("&Initial Budget>>");
            this.httpContext.Response.AppendToLog(this.budget.ToString());
        }
 private static void ProcessUsingBudget(SecurityIdentifier logonUserSid, Action anAction, ADSessionSettings adSessionSettings)
 {
     using (IStandardBudget standardBudget = StandardBudget.Acquire(logonUserSid, BudgetType.Owa, adSessionSettings))
     {
         standardBudget.CheckOverBudget();
         string callerInfo = OwaApplication.GetRequestDetailsLogger.Get(ExtensibleLoggerMetadata.EventId);
         standardBudget.StartConnection(callerInfo);
         standardBudget.StartLocal(callerInfo, default(TimeSpan));
         anAction();
     }
 }
        private void AcquireBudgetAndStartTiming()
        {
            ExTraceGlobals.SharingTracer.TraceDebug <SecurityIdentifier>((long)this.GetHashCode(), "Acquiring and check the budget for sid {0}.", this.sid);
            this.budget = StandardBudget.Acquire(this.sid, BudgetType.Anonymous, ADSessionSettings.FromRootOrgScopeSet());
            this.budget.CheckOverBudget();
            ExTraceGlobals.SharingTracer.TraceDebug <SecurityIdentifier>((long)this.GetHashCode(), "Start timing for sid {0}.", this.sid);
            PublishedFolder.SleepIfNecessary();
            string callerInfo = "PublishedFolder.AcquireBudgetAndStartTiming";

            this.budget.StartConnection(callerInfo);
            this.budget.StartLocal(callerInfo, default(TimeSpan));
        }
 public IResourceMonitor Create(Guid teamMailboxMdbGuid)
 {
     if (teamMailboxMdbGuid == Guid.Empty)
     {
         throw new ArgumentNullException("teamMailboxMdbGuid");
     }
     return(new TeamMailboxSyncResourceMonitorFactory.TeamMailboxSyncResourceMonitor(new ResourceKey[]
     {
         ProcessorResourceKey.Local,
         new MdbReplicationResourceHealthMonitorKey(teamMailboxMdbGuid),
         new MdbResourceHealthMonitorKey(teamMailboxMdbGuid)
     }, StandardBudget.Acquire(new UnthrottledBudgetKey("TeamMailboxSync", BudgetType.ResourceTracking))));
 }
Exemple #8
0
        private MicroDelayScope(MailboxReplicationProxyService mrsProxy, params ResourceKey[] resources)
        {
            this.startedCallProcessingAt = ExDateTime.UtcNow;
            this.resources         = resources;
            this.budget            = StandardBudget.AcquireUnthrottledBudget("MrsProxyBudget", BudgetType.ResourceTracking);
            this.workLoadSettings  = (mrsProxy.IsHighPriority ? CommonUtils.WorkloadSettingsHighPriority : CommonUtils.WorkloadSettings);
            this.skipWLMThrottling = (!ResourceHealthMonitorManager.Active || !TestIntegration.Instance.MicroDelayEnabled || mrsProxy.SkipWLMThrottling || mrsProxy.IsInFinalization);
            bool flag = false;

            try
            {
                if (!this.skipWLMThrottling)
                {
                    ResourceLoadDelayInfo.CheckResourceHealth(this.budget, this.workLoadSettings, this.resources);
                }
                this.budget.StartConnection("MailboxReplicationService.MicroDelayScope.MicroDelayScope");
                this.budget.StartLocal("MailboxReplicationService.MicroDelayScope.MicroDelayScope", default(TimeSpan));
                if (!ActivityContext.IsStarted)
                {
                    this.scope        = ActivityContext.Start(null);
                    this.scope.Action = "MailboxReplicationProxyService";
                    if (OperationContext.Current != null)
                    {
                        this.scope.UpdateFromMessage(OperationContext.Current);
                    }
                    this.scope.UserId = mrsProxy.ExchangeGuid.ToString();
                    if (mrsProxy.ClientVersion != null)
                    {
                        this.scope.ClientInfo = mrsProxy.ClientVersion.ComputerName;
                    }
                }
                flag = true;
            }
            finally
            {
                if (!flag)
                {
                    this.SuppressDisposeTracker();
                    if (this.budget != null)
                    {
                        this.budget.Dispose();
                        this.budget = null;
                    }
                    if (this.scope != null)
                    {
                        this.scope.End();
                        this.scope = null;
                    }
                }
            }
        }
        private void ExecuteInternal(BaseQuery query)
        {
            IStandardBudget standardBudget = null;

            if (Interlocked.Exchange(ref this.firstThreadEntryTimeCaptured, 1) == 0)
            {
                base.RequestLogger.Add(RequestStatistics.Create(RequestStatisticsType.LocalFirstThreadExecute, this.localRequestStopwatch.ElapsedMilliseconds));
            }
            if (base.Aborted)
            {
                return;
            }
            RequestStatisticsForMapi requestStatisticsForMapi = RequestStatisticsForMapi.Begin();
            Stopwatch stopwatch = Stopwatch.StartNew();

            try
            {
                if (base.ClientContext.Budget != null)
                {
                    standardBudget = StandardBudget.Acquire(base.ClientContext.Budget.Owner);
                    if (standardBudget != null)
                    {
                        standardBudget.StartLocal("LocalRequest.ExecuteInternal", default(TimeSpan));
                    }
                }
                LocalRequest.RequestRoutingTracer.TraceDebug <object, int>((long)this.GetHashCode(), "{0}: Entered LocalRequest.Execute() using thread {1}", TraceContext.Get(), Environment.CurrentManagedThreadId);
                if (query.SetResultOnFirstCall(this.localQuery.GetData(query)))
                {
                    LocalRequest.RequestRoutingTracer.TraceDebug <object, EmailAddress, int>((long)this.GetHashCode(), "{0}: Request for mailbox {1} complete and result set in time. Thread {2}", TraceContext.Get(), query.Email, Environment.CurrentManagedThreadId);
                }
            }
            finally
            {
                stopwatch.Stop();
                if (standardBudget != null)
                {
                    standardBudget.EndLocal();
                    standardBudget.Dispose();
                }
                base.RequestLogger.Add(RequestStatistics.Create(RequestStatisticsType.LocalElapsedTimeLongPole, stopwatch.ElapsedMilliseconds, query.ExchangePrincipal.MailboxInfo.Location.ServerFqdn));
                base.RequestLogger.Add(requestStatisticsForMapi.End(RequestStatisticsType.Local, query.ExchangePrincipal.MailboxInfo.Location.ServerFqdn));
                if (Interlocked.Decrement(ref this.pendingItems) == 0)
                {
                    this.ComputeStatistics();
                    this.DisposeIfInternalContext();
                    base.Complete();
                }
                LocalRequest.RequestRoutingTracer.TraceDebug <object, int>((long)this.GetHashCode(), "{0}: Exited LocalRequest.Execute() using thread {1}", TraceContext.Get(), Environment.CurrentManagedThreadId);
            }
        }
Exemple #10
0
 // Token: 0x06001D58 RID: 7512 RVA: 0x00074F04 File Offset: 0x00073104
 private static void InitializeThrottlingBudget(UserContext userContext, string description, out IStandardBudget budget)
 {
     ValidateArgument.NotNull(userContext, "userContext is null");
     budget = null;
     try
     {
         string callerInfo = string.IsNullOrEmpty(description) ? "SpeechRecognitionProcessor.InitializeThrottlingBudget" : description;
         budget = StandardBudget.Acquire(userContext.ExchangePrincipal.Sid, BudgetType.OwaVoice, userContext.ExchangePrincipal.MailboxInfo.OrganizationId.ToADSessionSettings());
         budget.CheckOverBudget();
         budget.StartConnection(callerInfo);
         budget.StartLocal(callerInfo, default(TimeSpan));
     }
     catch (Exception ex)
     {
         if (budget != null)
         {
             budget.Dispose();
             budget = null;
         }
         throw ex;
     }
 }
Exemple #11
0
        internal bool TryAcquireBudget()
        {
            if (this.budget != null)
            {
                throw new InvalidOperationException("Budget already acquired");
            }
            Exception ex2;

            try
            {
                ADSessionSettings settings;
                if (!string.IsNullOrEmpty(this.userDomain))
                {
                    settings = ADSessionSettings.RootOrgOrSingleTenantFromAcceptedDomainAutoDetect(this.userDomain);
                }
                else
                {
                    settings = ADSessionSettings.FromRootOrgScopeSet();
                }
                this.budget = StandardBudget.Acquire(this.clientSecurityContext.UserSid, BudgetType.Rca, settings);
                return(true);
            }
            catch (DataValidationException ex)
            {
                ex2 = ex;
            }
            catch (ADTransientException ex3)
            {
                ex2 = ex3;
            }
            catch (ADOperationException ex4)
            {
                ex2 = ex4;
            }
            RfriContext.ReferralTracer.TraceError <string>((long)this.ContextHandle, "TryAcquireBudget exception: {0}", ex2.Message);
            return(false);
        }
        public void ProcessQueuedEvents(IAsyncCommand callingCommand)
        {
            NotificationManager.AsyncEvent asyncEvent = null;
            if (this.currentlyExecuting)
            {
                AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "ProcessQueuedEvents.UniqueId:{0}.  Already processing event.  Exiting.", this.uniqueId);
                return;
            }
            lock (this.eventQueue)
            {
                if (this.currentlyExecuting)
                {
                    AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, this, "ProcessQueuedEvents.UniqueId:{0}.  Already processing event.  Exiting.", this.uniqueId);
                    return;
                }
                this.currentlyExecuting = true;
            }
            IBudget budget = null;

            try
            {
                this.EnqueueDiagOperation(NotificationManager.DiagnosticEvent.RunStart);
                budget = StandardBudget.Acquire(this.budgetKey);
                lock (this.eventQueue)
                {
                    if (callingCommand != null)
                    {
                        callingCommand.ProcessingEventsEnabled = true;
                    }
                    AirSyncDiagnostics.TraceDebug <string, string, int>(ExTraceGlobals.RequestsTracer, this, "ProcessQueuedEvents.UniqueId:{0}, ProcessingEnabled: {1}, eventQueue count:{2}.", this.uniqueId, (callingCommand == null) ? "<null command>" : "true", this.eventQueue.Count);
                    asyncEvent = this.GetNextEvent();
                }
                IAsyncCommand cmd   = null;
                bool          flag3 = asyncEvent != null;
                while (flag3)
                {
                    try
                    {
                        cmd = this.StartCommandContext();
                        AirSyncDiagnostics.TraceDebug <NotificationManager.AsyncEventType, string, bool>(ExTraceGlobals.ThreadingTracer, this, "Processing event {0} for {1}. Command is null? {2}", asyncEvent.Type, this.uniqueId, this.command == null);
                        switch (asyncEvent.Type)
                        {
                        case NotificationManager.AsyncEventType.XsoEventAvailable:
                            this.ProcessXsoEventAvailable(asyncEvent, budget);
                            break;

                        case NotificationManager.AsyncEventType.XsoException:
                            this.ProcessXsoException(asyncEvent);
                            break;

                        case NotificationManager.AsyncEventType.Timeout:
                            this.ProcessTimeout(budget);
                            break;

                        case NotificationManager.AsyncEventType.Acquire:
                            this.ProcessAcquire(asyncEvent);
                            break;

                        case NotificationManager.AsyncEventType.Release:
                            this.ProcessRelease(asyncEvent);
                            break;

                        case NotificationManager.AsyncEventType.Kill:
                            this.Kill();
                            break;

                        case NotificationManager.AsyncEventType.AccountTerminated:
                            this.ProcessAccountTerminated(asyncEvent);
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        AirSyncDiagnostics.TraceDebug <string, string>(ExTraceGlobals.ThreadingTracer, this, "Exception in processQueuedEvents for {0}. Exception:{1}", this.uniqueId, ex.ToString());
                        if (!this.InternalHandleException(ex))
                        {
                            throw;
                        }
                    }
                    finally
                    {
                        this.EndCommandContext(cmd);
                        asyncEvent = this.GetNextEvent();
                        flag3      = (asyncEvent != null);
                    }
                }
            }
            finally
            {
                this.currentlyExecuting = false;
                this.EnqueueDiagOperation(NotificationManager.DiagnosticEvent.RunEnd);
                if (budget != null)
                {
                    try
                    {
                        budget.Dispose();
                    }
                    catch (FailFastException arg)
                    {
                        AirSyncDiagnostics.TraceError <FailFastException>(ExTraceGlobals.RequestsTracer, this, "Budget.Dispose failed with exception: {0}", arg);
                    }
                }
            }
        }
Exemple #13
0
        protected override void InternalValidate()
        {
            MailboxIdParameter mailboxIdParameter = null;

            try
            {
                base.InternalValidate();
            }
            catch (ManagementObjectNotFoundException)
            {
                if (this.Identity == null || !this.TryGetMailboxIdFromIdentity(this.Identity.ToString(), out mailboxIdParameter))
                {
                    throw;
                }
                this.deviceExistsinAD = false;
            }
            if (base.HasErrors)
            {
                return;
            }
            if (MobileDeviceTaskHelper.IsRunningUnderMyOptionsRole(this, base.TenantGlobalCatalogSession, base.SessionSettings))
            {
                ADObjectId adobjectId;
                if (!base.TryGetExecutingUserId(out adobjectId))
                {
                    throw new ExecutingUserPropertyNotFoundException("executingUserid");
                }
                if (!base.DataObject.Id.Parent.Parent.Equals(adobjectId) || (mailboxIdParameter != null && !mailboxIdParameter.Equals(adobjectId)))
                {
                    base.WriteError(new LocalizedException(Strings.ErrorObjectNotFound(this.Identity.ToString())), ErrorCategory.InvalidArgument, null);
                }
            }
            Exception ex = null;

            if (mailboxIdParameter == null)
            {
                mailboxIdParameter = this.Identity.GetMailboxId();
            }
            if (mailboxIdParameter == null && base.DataObject != null)
            {
                this.Identity      = new MobileDeviceIdParameter(base.DataObject);
                mailboxIdParameter = this.Identity.GetMailboxId();
            }
            if (mailboxIdParameter == null)
            {
                base.WriteError(new LocalizedException(Strings.ErrorObjectNotFound(this.Identity.ToString())), ErrorCategory.InvalidArgument, null);
            }
            this.principal = MobileDeviceTaskHelper.GetExchangePrincipal(base.SessionSettings, this.CreateTenantGlobalCatalogSession(base.SessionSettings), mailboxIdParameter, "Remove-MobileDevice", out ex);
            if (ex != null)
            {
                base.WriteError(ex, ErrorCategory.InvalidArgument, null);
            }
            if (DeviceInfo.IsThrottlingLimitsExceeded((IConfigurationSession)base.DataSession, this.principal, out this.activeSyncDevices))
            {
                uint maxDeviceDeleteCount = 0U;
                using (IBudget budget = StandardBudget.Acquire(this.principal.Sid, BudgetType.Eas, this.principal.MailboxInfo.OrganizationId.ToADSessionSettings()))
                {
                    IThrottlingPolicy throttlingPolicy = budget.ThrottlingPolicy;
                    maxDeviceDeleteCount = throttlingPolicy.EasMaxDeviceDeletesPerMonth.Value;
                }
                base.WriteError(new LocalizedException(Strings.MaxDeviceDeletesPerMonthReached(this.activeSyncDevices.ObjectsDeletedThisPeriod, maxDeviceDeleteCount)), ErrorCategory.WriteError, null);
            }
        }
 protected override IStandardBudget AcquireBudget()
 {
     return(StandardBudget.AcquireFallback(this.callerExternalIdentity.EmailAddress.ToString(), BudgetType.Ews));
 }
Exemple #15
0
        // Token: 0x060002D5 RID: 725 RVA: 0x00012C14 File Offset: 0x00010E14
        protected override void OnWriteBodyContents(XmlDictionaryWriter dictionaryXml)
        {
            bool error = true;
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();

            xmlWriterSettings.Indent           = true;
            xmlWriterSettings.IndentChars      = "  ";
            xmlWriterSettings.ConformanceLevel = ConformanceLevel.Document;
            XmlWriter xmlWriter  = XmlWriter.Create(dictionaryXml, new XmlWriterSettings());
            string    callerInfo = "LegacyBodyWriter.OnWriteBodyContents";

            if (!this.parseSuccess)
            {
                ExTraceGlobals.FrameworkTracer.TraceError <string>((long)this.GetHashCode(), "[OnWriteBodyContents()] 'Validation failed. Provider \"{0}\"'", base.GetType().AssemblyQualifiedName);
                Common.GenerateErrorResponse(xmlWriter, "http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006", "600", Strings.InvalidRequest.ToString(), this.debugData, this.requestData, base.GetType().AssemblyQualifiedName);
            }
            else
            {
                IStandardBudget standardBudget = null;
                try
                {
                    FaultInjection.GenerateFault((FaultInjection.LIDs) 2917543229U);
                    standardBudget = StandardBudget.Acquire(this.requestData.User.Identity.GetSecurityIdentifier(), BudgetType.Ews, Common.GetSessionSettingsForCallerScope());
                    HttpContext.Current.Items["StartBudget"] = standardBudget.ToString();
                    standardBudget.CheckOverBudget();
                    standardBudget.StartConnection(callerInfo);
                    standardBudget.StartLocal(callerInfo, default(TimeSpan));
                    string text;
                    error = this.GenerateResponse(xmlWriter, standardBudget, out text);
                    HttpContext.Current.Items["EndBudget"] = standardBudget.ToString();
                    if (!string.IsNullOrEmpty(text))
                    {
                        HttpContext.Current.Response.Redirect(text, false);
                    }
                }
                catch (OverBudgetException)
                {
                    this.TraceExceptionAndGenerateErrorResponse(xmlWriter, Strings.ServerBusy.ToString(), "[OnWriteBodyContents()] 'Account has exceeded budget.");
                }
                catch (NonUniqueRecipientException ex)
                {
                    this.TraceExceptionAndGenerateErrorResponse(xmlWriter, Strings.ADUnavailable.ToString(), "[OnWriteBodyContents()] " + ex.Message);
                }
                catch (ADTransientException ex2)
                {
                    this.TraceExceptionAndGenerateErrorResponse(xmlWriter, Strings.ADUnavailable.ToString(), "[OnWriteBodyContents()] " + ex2.Message);
                }
                finally
                {
                    if (standardBudget != null)
                    {
                        try
                        {
                            FaultInjection.GenerateFault((FaultInjection.LIDs) 4081462589U);
                            standardBudget.Dispose();
                        }
                        catch (ADTransientException arg)
                        {
                            ExTraceGlobals.FrameworkTracer.TraceError <ADTransientException>((long)this.GetHashCode(), "[OnWriteBodyContents()] Got ADTransientException {0} while disposing budget.", arg);
                        }
                        standardBudget = null;
                    }
                }
            }
            PerformanceCounters.UpdateTotalRequests(error);
            RequestDetailsLoggerBase <RequestDetailsLogger> .Current.ActivityScope.Action = "POX";
        }
Exemple #16
0
 protected override IStandardBudget AcquireBudget()
 {
     return(StandardBudget.Acquire(this.callerSid, BudgetType.Ews, Common.GetSessionSettingsForCallerScope()));
 }
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            bool flag = this.principal.RecipientTypeDetails == RecipientTypeDetails.MonitoringMailbox;

            try
            {
                this.mailboxSession = MailboxSession.OpenAsAdmin(this.principal, CultureInfo.InvariantCulture, "Client=Management;Action=Get-MobileDeviceStatistics");
                List <DeviceInfo> list = new List <DeviceInfo>();
                if (base.Fields["ActiveSync"] == null && base.Fields["OWAforDevices"] == null)
                {
                    base.Fields["ActiveSync"]    = new SwitchParameter(true);
                    base.Fields["OWAforDevices"] = new SwitchParameter(true);
                }
                else if (base.Fields["ActiveSync"] == null)
                {
                    if (this.OWAforDevices == false)
                    {
                        base.Fields["ActiveSync"] = new SwitchParameter(true);
                    }
                }
                else if (base.Fields["OWAforDevices"] == null && this.ActiveSync == false)
                {
                    base.Fields["OWAforDevices"] = new SwitchParameter(true);
                }
                if (this.ActiveSync == true)
                {
                    DeviceInfo[] allDeviceInfo = DeviceInfo.GetAllDeviceInfo(this.mailboxSession, MobileClientType.EAS);
                    if (allDeviceInfo != null)
                    {
                        list.AddRange(allDeviceInfo);
                    }
                }
                if (this.OWAforDevices == true)
                {
                    DeviceInfo[] allDeviceInfo2 = DeviceInfo.GetAllDeviceInfo(this.mailboxSession, MobileClientType.MOWA);
                    if (allDeviceInfo2 != null)
                    {
                        list.AddRange(allDeviceInfo2);
                    }
                }
                if (list != null)
                {
                    List <MobileDevice> allMobileDevices = this.GetAllMobileDevices();
                    int num = 0;
                    using (List <DeviceInfo> .Enumerator enumerator = list.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            DeviceInfo deviceInfo = enumerator.Current;
                            if (deviceInfo.DeviceADObjectId != null && ADObjectId.Equals(deviceInfo.UserADObjectId, this.principal.ObjectId))
                            {
                                MobileDevice mobileDevice = allMobileDevices.Find((MobileDevice currentDevice) => currentDevice.DeviceId.Equals(deviceInfo.DeviceIdentity.DeviceId));
                                if (mobileDevice != null)
                                {
                                    num++;
                                    this.deviceConfiguration = this.CreateDeviceConfiguration(deviceInfo);
                                    if (this.Identity != null)
                                    {
                                        TIdentity identity = this.Identity;
                                        if (!identity.InternalADObjectId.Equals(this.deviceConfiguration.Identity))
                                        {
                                            continue;
                                        }
                                    }
                                    if (mobileDevice != null && this.deviceConfiguration.DeviceAccessStateReason < DeviceAccessStateReason.UserAgentsChanges && mobileDevice.ClientType == MobileClientType.EAS)
                                    {
                                        if (!flag)
                                        {
                                            DeviceAccessState       deviceAccessState       = DeviceAccessState.Unknown;
                                            DeviceAccessStateReason deviceAccessStateReason = DeviceAccessStateReason.Unknown;
                                            ADObjectId deviceAccessControlRule = null;
                                            bool       flag2 = false;
                                            if (mobileDevice.OrganizationId != OrganizationId.ForestWideOrgId && (mobileDevice.DeviceAccessStateReason != DeviceAccessStateReason.Individual || mobileDevice.DeviceAccessState != DeviceAccessState.Blocked) && mobileDevice.DeviceAccessStateReason != DeviceAccessStateReason.Policy)
                                            {
                                                Command.DetermineDeviceAccessState(this.LoadAbq(OrganizationId.ForestWideOrgId), mobileDevice.DeviceType, mobileDevice.DeviceModel, mobileDevice.DeviceUserAgent, mobileDevice.DeviceOS, out deviceAccessState, out deviceAccessStateReason, out deviceAccessControlRule);
                                                if (deviceAccessState == DeviceAccessState.Blocked)
                                                {
                                                    mobileDevice.DeviceAccessState       = deviceAccessState;
                                                    mobileDevice.DeviceAccessStateReason = deviceAccessStateReason;
                                                    mobileDevice.DeviceAccessControlRule = deviceAccessControlRule;
                                                    flag2 = true;
                                                }
                                            }
                                            if (!flag2 && mobileDevice.DeviceAccessState != DeviceAccessState.DeviceDiscovery && mobileDevice.DeviceAccessStateReason != DeviceAccessStateReason.Individual && mobileDevice.DeviceAccessStateReason != DeviceAccessStateReason.Upgrade && mobileDevice.DeviceAccessStateReason != DeviceAccessStateReason.Policy)
                                            {
                                                Command.DetermineDeviceAccessState(this.LoadAbq(mobileDevice.OrganizationId), mobileDevice.DeviceType, mobileDevice.DeviceModel, mobileDevice.DeviceUserAgent, mobileDevice.DeviceOS, out deviceAccessState, out deviceAccessStateReason, out deviceAccessControlRule);
                                                mobileDevice.DeviceAccessState       = deviceAccessState;
                                                mobileDevice.DeviceAccessStateReason = deviceAccessStateReason;
                                                mobileDevice.DeviceAccessControlRule = deviceAccessControlRule;
                                            }
                                        }
                                        this.deviceConfiguration.DeviceAccessState       = mobileDevice.DeviceAccessState;
                                        this.deviceConfiguration.DeviceAccessStateReason = mobileDevice.DeviceAccessStateReason;
                                        this.deviceConfiguration.DeviceAccessControlRule = mobileDevice.DeviceAccessControlRule;
                                    }
                                    if (this.ShowRecoveryPassword == false)
                                    {
                                        this.deviceConfiguration.RecoveryPassword = "******";
                                    }
                                    if (this.GetMailboxLog)
                                    {
                                        this.deviceConfiguration.MailboxLogReport = deviceInfo.GetOrCreateMailboxLogReport(this.mailboxSession);
                                    }
                                    base.WriteObject(this.deviceConfiguration);
                                    if (this.Identity != null)
                                    {
                                        this.ProcessMailboxLogger(new DeviceInfo[]
                                        {
                                            deviceInfo
                                        });
                                    }
                                }
                            }
                        }
                    }
                    if (this.Identity == null)
                    {
                        this.ProcessMailboxLogger(list.ToArray());
                    }
                    if (num > 0)
                    {
                        using (IBudget budget = StandardBudget.Acquire(this.mailboxSession.MailboxOwner.Sid, BudgetType.Eas, this.mailboxSession.GetADSessionSettings()))
                        {
                            if (budget != null)
                            {
                                IThrottlingPolicy throttlingPolicy = budget.ThrottlingPolicy;
                                if (throttlingPolicy != null && !throttlingPolicy.EasMaxDevices.IsUnlimited && (long)num >= (long)((ulong)throttlingPolicy.EasMaxDevices.Value))
                                {
                                    this.WriteWarning((num == 1) ? Strings.MaxDevicesReachedSingular(throttlingPolicy.EasMaxDevices.Value) : Strings.MaxDevicesReached(num, throttlingPolicy.EasMaxDevices.Value));
                                }
                            }
                        }
                    }
                }
            }
            catch (StorageTransientException ex)
            {
                TaskLogger.LogError(ex);
                base.WriteError(ex, ErrorCategory.ReadError, this.principal);
            }
            catch (StoragePermanentException ex2)
            {
                TaskLogger.LogError(ex2);
                base.WriteError(ex2, ErrorCategory.InvalidOperation, this.principal);
            }
            finally
            {
                if (this.mailboxSession != null)
                {
                    this.mailboxSession.Dispose();
                }
                TaskLogger.LogExit();
            }
        }
        private IEnumerable <MailTips> GetMailTipsInBatches(MailTipsState mailTipsState)
        {
            Exception ex = null;

            try
            {
                using (IStandardBudget standardBudget = StandardBudget.Acquire(mailTipsState.ClientSecurityContext.UserSid, BudgetType.Owa, ADSessionSettings.FromRootOrgScopeSet()))
                {
                    string callerInfo = "MailTipsNotificationHandler.GetMailTipsInBatches";
                    standardBudget.CheckOverBudget();
                    standardBudget.StartConnection(callerInfo);
                    standardBudget.StartLocal(callerInfo, default(TimeSpan));
                    mailTipsState.Budget = standardBudget;
                    ClientContext clientContext = ClientContext.Create(mailTipsState.ClientSecurityContext, mailTipsState.Budget, mailTipsState.LogonUserTimeZone, mailTipsState.LogonUserCulture);
                    ((InternalClientContext)clientContext).QueryBaseDN = mailTipsState.QueryBaseDn;
                    ExTraceGlobals.CoreCallTracer.TraceDebug <ADObjectId>((long)this.GetHashCode(), "QueryBaseDN set to {0}", mailTipsState.QueryBaseDn);
                    ProxyAddress sendingAsProxyAddress = this.GetSendingAsProxyAddress(mailTipsState);
                    mailTipsState.CachedOrganizationConfiguration = CachedOrganizationConfiguration.GetInstance(mailTipsState.LogonUserOrgId, CachedOrganizationConfiguration.ConfigurationTypes.All);
                    ExTraceGlobals.CoreCallTracer.TraceDebug <OrganizationId>((long)this.GetHashCode(), "Organization ID = {0}", mailTipsState.LogonUserOrgId);
                    try
                    {
                        int num = 0;
                        do
                        {
                            ProxyAddress[] nextBatch = MailTipsNotificationHandler.GetNextBatch(mailTipsState.RecipientsInfo, ref num);
                            mailTipsState.GetMailTipsQuery            = new GetMailTipsQuery(this.GetHashCode(), clientContext, sendingAsProxyAddress, mailTipsState.CachedOrganizationConfiguration, nextBatch, MailTipTypes.OutOfOfficeMessage | MailTipTypes.MailboxFullStatus | MailTipTypes.CustomMailTip | MailTipTypes.ExternalMemberCount | MailTipTypes.TotalMemberCount | MailTipTypes.DeliveryRestriction | MailTipTypes.ModerationStatus, mailTipsState.LogonUserCulture.LCID, mailTipsState.Budget, null);
                            mailTipsState.GetMailTipsQuery.ServerName = mailTipsState.ServerName;
                            mailTipsState.RequestLogger = mailTipsState.GetMailTipsQuery.RequestLogger;
                            IEnumerable <MailTips> collection = mailTipsState.GetMailTipsQuery.Execute();
                            mailTipsState.MailTipsResult.AddRange(collection);
                        }while (num < mailTipsState.RecipientsInfo.Length);
                    }
                    catch (UserWithoutFederatedProxyAddressException ex2)
                    {
                        ex = ex2;
                    }
                    catch (InvalidFederatedOrganizationIdException ex3)
                    {
                        ex = ex3;
                    }
                }
            }
            catch (OverBudgetException ex4)
            {
                ex = ex4;
            }
            catch (ObjectDisposedException ex5)
            {
                ex = ex5;
            }
            catch (OwaInvalidOperationException ex6)
            {
                ex = ex6;
            }
            finally
            {
                if (ex != null)
                {
                    MailTipsNotificationHandler.PopulateException(mailTipsState, ex, this.GetHashCode());
                }
            }
            return(mailTipsState.MailTipsResult);
        }
        private void WriteNotification(bool asyncOperation, double throttleInterval, IPendingRequestNotifier notifier, PendingRequestManager.PendingNotifierState notifierState)
        {
            bool flag = false;

            if (notifier.ShouldThrottle)
            {
                int num = notifierState.IncrementOnDataAvailableThrottleCount();
                if (num > 100)
                {
                    flag = true;
                }
                else if (num == 100 && throttleInterval <= 10.0)
                {
                    ExTraceGlobals.NotificationsCallTracer.TraceDebug <string, int>((long)this.GetHashCode(), "Start throttling mechanism - timer was started and from now on notifier {0} / {1} will be on throttling mode ", notifier.GetType().Name, notifier.GetHashCode());
                    flag = true;
                    if (notifierState.ThrottleTimer == null)
                    {
                        notifierState.ThrottleTimer = new Timer(new TimerCallback(this.ThrottleTimeout), notifier, 20000, -1);
                    }
                    else
                    {
                        notifierState.ThrottleTimer.Change(20000, -1);
                    }
                }
                if (num <= 100 && throttleInterval > 10.0 && num != 1)
                {
                    notifierState.ExchangeOnDataAvailableThrottleCount(1);
                }
            }
            if (flag)
            {
                ExTraceGlobals.NotificationsCallTracer.TraceDebug <string, int>((long)this.GetHashCode(), "PendingRequestManager.WriteNotification throttled notifier: {0} / {1}", notifier.GetType().Name, notifier.GetHashCode());
                return;
            }
            ExTraceGlobals.NotificationsCallTracer.TraceDebug <string, int>((long)this.GetHashCode(), "PendingRequestManager.WriteNotification is reading data from the notifier. Notifier: {0} / {1}", notifier.GetType().Name, notifier.GetHashCode());
            try
            {
                List <NotificationPayloadBase> payloadList = (List <NotificationPayloadBase>)notifier.ReadDataAndResetState();
                if (notifier.SubscriptionId != null)
                {
                    Pusher.Instance.Distribute(payloadList, notifier.ContextKey, notifier.SubscriptionId);
                }
                if (this.pendingRequestChannels != null)
                {
                    lock (this.pendingRequestChannels)
                    {
                        if (this.pendingRequestChannels != null)
                        {
                            if (this.budget == null)
                            {
                                this.budget = StandardBudget.Acquire(this.userContext.ExchangePrincipal.Sid, BudgetType.Owa, this.userContext.ExchangePrincipal.MailboxInfo.OrganizationId.ToADSessionSettings());
                            }
                            this.budget.CheckOverBudget();
                            this.budget.StartLocal("PendingRequestManager.WriteNotification", default(TimeSpan));
                            try
                            {
                                using (Dictionary <string, PendingRequestChannel> .Enumerator enumerator = this.pendingRequestChannels.GetEnumerator())
                                {
                                    while (enumerator.MoveNext())
                                    {
                                        KeyValuePair <string, PendingRequestChannel> channel = enumerator.Current;
                                        try
                                        {
                                            OwaDiagnostics.SendWatsonReportsForGrayExceptions(delegate()
                                            {
                                                KeyValuePair <string, PendingRequestChannel> channel = channel;
                                                channel.Value.WritePayload(asyncOperation, payloadList);
                                                Dictionary <string, long> dictionary = this.channelNotificationMarks;
                                                KeyValuePair <string, PendingRequestChannel> channel2 = channel;
                                                if (dictionary.ContainsKey(channel2.Key))
                                                {
                                                    Dictionary <string, long> dictionary3;
                                                    Dictionary <string, long> dictionary2 = dictionary3 = this.channelNotificationMarks;
                                                    KeyValuePair <string, PendingRequestChannel> channel3 = channel;
                                                    string key;
                                                    dictionary2[key = channel3.Key] = dictionary3[key] + (long)payloadList.Count;
                                                    return;
                                                }
                                                Dictionary <string, long> dictionary4 = this.channelNotificationMarks;
                                                KeyValuePair <string, PendingRequestChannel> channel4 = channel;
                                                dictionary4.Add(channel4.Key, (long)payloadList.Count);
                                            });
                                        }
                                        catch (GrayException ex)
                                        {
                                            Exception ex2 = (ex.InnerException != null) ? ex.InnerException : ex;
                                            ExTraceGlobals.NotificationsCallTracer.TraceError((long)this.GetHashCode(), "Exception when writing the notifications to the client. Notifier {0} / {1}, exception message: {2}, stack: {3};", new object[]
                                            {
                                                notifier.GetType().Name,
                                                notifier.GetHashCode(),
                                                ex2.Message,
                                                ex2.StackTrace
                                            });
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                this.budget.EndLocal();
                            }
                        }
                    }
                }
            }
            catch (Exception ex3)
            {
                ExTraceGlobals.NotificationsCallTracer.TraceError <string, int, string>((long)this.GetHashCode(), "Exception when writing the notifications to the client. Notifier {0} / {1}, exception message: {2};", notifier.GetType().Name, notifier.GetHashCode(), (ex3.InnerException != null) ? ex3.InnerException.Message : ex3.Message);
                throw;
            }
        }