public int ProceedToNextIteration(int defaultDelay)
        {
            AuditLogSearchHealth auditLogSearchHealth = AuditLogSearchHealthHandler.GetInstance().AuditLogSearchHealth;
            bool flag = !this.RetryTenants.IsEmpty && this.RetryIteration < AuditLogSearchRetryPolicy.retryLimit;
            int  num;

            if (flag)
            {
                num = Math.Min(AuditLogSearchRetryPolicy.retryDelays[this.RetryIteration], defaultDelay);
                this.retryIteration = this.RetryIteration + 1;
                auditLogSearchHealth.ClearRetry();
                using (IEnumerator <ADUser> enumerator = this.RetryTenants.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        ADUser tenant = enumerator.Current;
                        auditLogSearchHealth.AddRetryTenant(tenant);
                    }
                    goto IL_90;
                }
            }
            num = defaultDelay;
            this.Reset();
            IL_90:
            Random random = new Random();
            int num2 = (int)TimeSpan.FromMinutes(2.0).TotalMilliseconds;

            num += random.Next(-num2, num2);
            auditLogSearchHealth.RetryIteration = this.RetryIteration;
            auditLogSearchHealth.NextSearchTime = new DateTime?(DateTime.UtcNow + TimeSpan.FromMilliseconds((double)num));
            return(num);
        }
        // Token: 0x06000067 RID: 103 RVA: 0x000030DC File Offset: 0x000012DC
        public override void Work()
        {
            AuditLogSearchHealthHandler instance             = AuditLogSearchHealthHandler.GetInstance();
            AuditLogSearchHealth        auditLogSearchHealth = instance.AuditLogSearchHealth;

            WaitHandle[] waitHandles = new WaitHandle[]
            {
                base.StopEvent,
                instance.RunSearchNowEvent
            };
            AuditLogSearchContext.EventLogger.LogEvent(MSExchangeAuditLogSearchEventLogConstants.Tuple_AuditLogSearchServiceletStarted, string.Empty, new object[]
            {
                this.pid
            });
            ExTraceGlobals.ServiceletTracer.TraceInformation(42415, (long)this.GetHashCode(), "AuditLogSearch servicelet starting");
            this.PublishNotification("AsyncSearchServiceletStarting", this.pid.ToString(), ResultSeverityLevel.Informational);
            AuditLogSearchServicelet.hbTimer.Elapsed += this.Callback;
            AuditLogSearchServicelet.hbTimer.Enabled  = true;
            for (;;)
            {
                int defaultDelay = this.ReadPollInterval();
                try
                {
                    GrayException.MapAndReportGrayExceptions(delegate()
                    {
                        this.WorkInternal();
                    });
                }
                catch (GrayException ex)
                {
                    ExTraceGlobals.ServiceletTracer.TraceError(21863L, ex.ToString());
                    AuditLogSearchContext.EventLogger.LogEvent(MSExchangeAuditLogSearchEventLogConstants.Tuple_ServiceletException, string.Empty, new object[]
                    {
                        ex.ToString()
                    });
                    this.PublishNotification("AuditLogSearchCompletedWithErrors", ex.ToString(), ResultSeverityLevel.Error);
                    auditLogSearchHealth.AddException(ex);
                }
                int  millisecondsTimeout = this.retryPolicy.ProceedToNextIteration(defaultDelay);
                int  num  = WaitHandle.WaitAny(waitHandles, millisecondsTimeout, false);
                bool flag = num == 0;
                if (flag)
                {
                    break;
                }
                bool flag2 = num == 1;
                if (flag2)
                {
                    this.retryPolicy.Reset();
                }
            }
            AuditLogSearchServicelet.hbTimer.Enabled = false;
            AuditLogSearchContext.EventLogger.LogEvent(MSExchangeAuditLogSearchEventLogConstants.Tuple_AuditLogSearchServiceletEnded, string.Empty, new object[]
            {
                this.pid
            });
            ExTraceGlobals.ServiceletTracer.TraceInformation(28310, (long)this.GetHashCode(), "AuditLogSearch servicelet stopped");
            AuditLogSearchServicelet.hbTimer.Enabled = false;
        }
        public void Reset()
        {
            this.retryIteration = 0;
            this.RetryTenants   = new ConcurrentQueue <ADUser>();
            AuditLogSearchHealth auditLogSearchHealth = AuditLogSearchHealthHandler.GetInstance().AuditLogSearchHealth;

            auditLogSearchHealth.RetryIteration = this.RetryIteration;
            auditLogSearchHealth.NextSearchTime = new DateTime?(DateTime.UtcNow);
        }
 // Token: 0x06000011 RID: 17 RVA: 0x000024D8 File Offset: 0x000006D8
 private static MailboxConnectivity CheckMailboxConnectivity(MailboxConnectivity mailboxConnectivity)
 {
     try
     {
         mailboxConnectivity.Message = "Getting ADSessionSettings";
         ADSessionSettings adsessionSettings = ADSessionSettings.RootOrgOrSingleTenantFromAcceptedDomainAutoDetect(mailboxConnectivity.TenantAcceptedDomain);
         if (adsessionSettings == null)
         {
             mailboxConnectivity.Message = "ADSessionSettings were not found.";
             return(mailboxConnectivity);
         }
         mailboxConnectivity.Message = "Creating IRecipientSession";
         IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.IgnoreInvalid, null, adsessionSettings, 223, "CheckMailboxConnectivity", "f:\\15.00.1497\\sources\\dev\\Management\\src\\ServiceHost\\Servicelets\\AuditLogSearch\\Program\\AuditLogSearchHealthHandler.cs");
         if (tenantOrRootOrgRecipientSession == null)
         {
             mailboxConnectivity.Message = "IRecipientSession was not found.";
             return(mailboxConnectivity);
         }
         bool   flag = mailboxConnectivity.ExchangeUserId.CompareTo(Guid.Empty) == 0;
         ADUser aduser;
         if (flag)
         {
             mailboxConnectivity.Message = "Getting OrganizationId";
             OrganizationId organizationId = OrganizationId.FromAcceptedDomain(mailboxConnectivity.TenantAcceptedDomain);
             mailboxConnectivity.Message = "Finding arbitration mailbox";
             aduser = AdminAuditLogHelper.GetTenantArbitrationMailbox(organizationId);
             mailboxConnectivity.ExchangeUserId = aduser.ExchangeGuid;
         }
         else
         {
             mailboxConnectivity.Message = "Finding ADRecipient";
             ADRecipient adrecipient = tenantOrRootOrgRecipientSession.FindByExchangeGuidIncludingAlternate(mailboxConnectivity.ExchangeUserId);
             aduser = (adrecipient as ADUser);
         }
         if (aduser == null)
         {
             mailboxConnectivity.Message = "ADUser was not found.";
             return(mailboxConnectivity);
         }
         mailboxConnectivity.Message = "Getting ExchangePrincipal";
         ExchangePrincipal principal = ExchangePrincipal.FromADUser(aduser, null);
         mailboxConnectivity.Message = "Creating EwsAuditClient";
         EwsAuditClient client = new EwsAuditClient(new EwsConnectionManager(principal, OpenAsAdminOrSystemServiceBudgetTypeType.Default, ExTraceGlobals.ServiceletTracer), TimeSpan.FromSeconds(5.0), ExTraceGlobals.ServiceletTracer);
         mailboxConnectivity.Message = "Checking connectivity";
         AuditLogSearchHealthHandler.CheckMailboxConnectivity(client, false);
         mailboxConnectivity.Message = "Checking connectivity (archive)";
         AuditLogSearchHealthHandler.CheckMailboxConnectivity(client, true);
         mailboxConnectivity.Message = "Ok";
         mailboxConnectivity.Success = true;
     }
     catch (Exception ex)
     {
         mailboxConnectivity.Message  += " FAILED.";
         mailboxConnectivity.Exception = ex.ToString();
     }
     return(mailboxConnectivity);
 }
 // Token: 0x0600006C RID: 108 RVA: 0x000037A8 File Offset: 0x000019A8
 private void ThreadStart(object queue)
 {
     try
     {
         GrayException.MapAndReportGrayExceptions(delegate()
         {
             ConcurrentQueue <ADUser> tenants = (ConcurrentQueue <ADUser>)queue;
             this.ProcessTenants(tenants);
         });
     }
     catch (GrayException ex)
     {
         ExTraceGlobals.WorkerTracer.TraceError(11881L, ex.ToString());
         AuditLogSearchContext.EventLogger.LogEvent(MSExchangeAuditLogSearchEventLogConstants.Tuple_WorkerException, string.Empty, new object[]
         {
             ex.ToString()
         });
         AuditLogSearchHealthHandler.GetInstance().AuditLogSearchHealth.AddException(ex);
     }
 }
        // Token: 0x0600000E RID: 14 RVA: 0x000022E8 File Offset: 0x000004E8
        internal override HealthHandlerResult GetExchangeDiagnosticsInfoData(DiagnosableParameters parameters)
        {
            string argument = parameters.Argument;

            if (string.IsNullOrWhiteSpace(argument))
            {
                return(this.AuditLogSearchHealth);
            }
            if (argument.Equals("/run", StringComparison.InvariantCultureIgnoreCase))
            {
                this.RunSearchNowEvent.Set();
                return(new HealthHandlerResult("Ok"));
            }
            if (argument.Equals("/check", StringComparison.InvariantCultureIgnoreCase))
            {
                Search search = (from s in this.AuditLogSearchHealth.Searches
                                 where s.ExceptionDetails != null
                                 select s).FirstOrDefault <Search>() ?? this.AuditLogSearchHealth.Searches.FirstOrDefault <Search>();
                if (search == null)
                {
                    return(new HealthHandlerResult("There are no faulted or any searches."));
                }
                MailboxConnectivity mailboxConnectivity = new MailboxConnectivity
                {
                    Message = string.Empty,
                    TenantAcceptedDomain = search.UserPrincipalName.Split(new char[]
                    {
                        '@'
                    }).LastOrDefault <string>(),
                    ExchangeUserId = (string.IsNullOrWhiteSpace(search.LastProcessedMailbox) ? Guid.Empty : Guid.Parse(search.LastProcessedMailbox))
                };
                return(AuditLogSearchHealthHandler.CheckMailboxConnectivity(mailboxConnectivity));
            }
            else
            {
                Match match = Regex.Match(argument, "^\\s* [/-]?check \\s* (?<org>\\S+) (\\s* [/\\s] \\s* (?<mailbox>\\S+))? \\s*$", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.CultureInvariant);
                if (match.Success)
                {
                    MailboxConnectivity mailboxConnectivity2 = new MailboxConnectivity
                    {
                        Exception = string.Empty,
                        Message   = string.Empty
                    };
                    string value  = match.Groups["org"].Value;
                    string value2 = match.Groups["mailbox"].Value;
                    Guid   empty  = Guid.Empty;
                    if (!string.IsNullOrEmpty(value) && (string.IsNullOrWhiteSpace(value2) || Guid.TryParse(value2, out empty)))
                    {
                        mailboxConnectivity2.TenantAcceptedDomain = value;
                        mailboxConnectivity2.ExchangeUserId       = empty;
                        mailboxConnectivity2 = AuditLogSearchHealthHandler.CheckMailboxConnectivity(mailboxConnectivity2);
                    }
                    else
                    {
                        mailboxConnectivity2.Message = "A domain name and a mailbox GUID are expected.";
                    }
                    return(mailboxConnectivity2);
                }
                return(new HealthHandlerResult("Invalid argument."));
            }
        }
        // Token: 0x0600006A RID: 106 RVA: 0x000033F8 File Offset: 0x000015F8
        private void WorkInternal()
        {
            AuditLogSearchHealth auditLogSearchHealth = AuditLogSearchHealthHandler.GetInstance().AuditLogSearchHealth;

            auditLogSearchHealth.ProcessStartTime = DateTime.UtcNow;
            auditLogSearchHealth.ProcessEndTime   = null;
            int num = this.random.Next(100000, 999999);

            AuditLogSearchContext.EventLogger.LogEvent(MSExchangeAuditLogSearchEventLogConstants.Tuple_AuditLogSearchStarted, string.Empty, new object[]
            {
                this.pid,
                num
            });
            Exception ex = null;

            try
            {
                ConcurrentQueue <ADUser> concurrentQueue;
                if (this.retryPolicy.IsRetrying)
                {
                    concurrentQueue = this.retryPolicy.RetryTenants;
                    ExTraceGlobals.ServiceletTracer.TraceInformation <int>(25566, (long)this.GetHashCode(), "Retrying search for {0} tenant arbitration mailbox(es)", concurrentQueue.Count);
                }
                else
                {
                    auditLogSearchHealth.Clear();
                    ADUser[] array = AuditLogSearchServicelet.GlobalFindAllArbitrationMailboxes();
                    if (array == null || array.Length == 0)
                    {
                        ExTraceGlobals.ServiceletTracer.TraceInformation(36433, (long)this.GetHashCode(), "No tenant arbitration mailboxes found in this server");
                        return;
                    }
                    concurrentQueue = new ConcurrentQueue <ADUser>(array);
                    ExTraceGlobals.ServiceletTracer.TraceInformation <int>(25566, (long)this.GetHashCode(), "Found {0} tenant arbitration mailbox(es)", concurrentQueue.Count);
                    foreach (ADUser tenant in concurrentQueue)
                    {
                        auditLogSearchHealth.AddTenant(tenant);
                    }
                }
                this.retryPolicy.ClearRetryTenants();
                int num2 = Math.Min(concurrentQueue.Count, Environment.ProcessorCount);
                ExTraceGlobals.ServiceletTracer.TraceInformation <int>(19568, (long)this.GetHashCode(), "Starting {0} worker threads", num2);
                Thread[] array2 = new Thread[num2];
                for (int i = 0; i < num2; i++)
                {
                    Thread thread = array2[i] = new Thread(new ParameterizedThreadStart(this.ThreadStart));
                    thread.Start(concurrentQueue);
                }
                ExTraceGlobals.ServiceletTracer.TraceInformation(28049, (long)this.GetHashCode(), "Waiting for the threads to join");
                foreach (Thread thread2 in array2)
                {
                    thread2.Join();
                }
                AuditLogSearchContext.EventLogger.LogEvent(MSExchangeAuditLogSearchEventLogConstants.Tuple_AuditLogSearchEnded, string.Empty, new object[]
                {
                    this.pid,
                    num
                });
            }
            catch (ADTransientException ex2)
            {
                ex = ex2;
            }
            catch (LocalServerNotFoundException ex3)
            {
                ex = ex3;
            }
            finally
            {
                auditLogSearchHealth.ProcessEndTime = new DateTime?(DateTime.UtcNow);
            }
            if (ex != null)
            {
                string text = ex.ToString();
                ExTraceGlobals.ServiceletTracer.TraceInformation <string>(11881, (long)this.GetHashCode(), "Error: {0}", text);
                this.PublishNotification("AuditLogSearchCompletedWithErrors", text, ResultSeverityLevel.Error);
                AuditLogSearchContext.EventLogger.LogEvent(MSExchangeAuditLogSearchEventLogConstants.Tuple_TransientException, string.Empty, new object[]
                {
                    this.pid,
                    num,
                    text
                });
                auditLogSearchHealth.AddException(ex);
            }
        }