private void RefreshMoveRequest(Guid mailboxGuid, Guid mdbGuid, int requestFlags, MoveRequestNotification op)
        {
            this.ForwardKnownExceptions(delegate
            {
                Guid empty = Guid.Empty;
                switch (op)
                {
                case MoveRequestNotification.Created:
                    MRSService.ProcessMoveRequestCreatedNotification(mailboxGuid, mdbGuid);
                    MRSService.Tickle(mailboxGuid, mdbGuid, op);
                    return;

                case MoveRequestNotification.Updated:
                    MRSService.Tickle(mailboxGuid, mdbGuid, op);
                    return;

                case MoveRequestNotification.Canceled:
                    MRSService.Tickle(mailboxGuid, mdbGuid, op);
                    return;

                case MoveRequestNotification.SuspendResume:
                    MRSService.Tickle(mailboxGuid, mdbGuid, op);
                    return;

                default:
                    return;
                }
            }, null);
        }
        private static void JobStateChangedHandler(object sender, JobEventArgs args)
        {
            BaseJob baseJob = args.Job as BaseJob;

            if (baseJob != null)
            {
                Guid objectGuid = baseJob.RequestJobStoringMDB.ObjectGuid;
                switch (args.State)
                {
                case JobState.Failed:
                case JobState.Finished:
                    baseJob.Disconnect();
                    baseJob.JobCompletedCallback();
                    lock (MailboxSyncerJobs.syncRoot)
                    {
                        MailboxSyncerJobs.activeJobs.Remove(baseJob.GetRequestKeyGuid());
                        ((IDisposable)baseJob).Dispose();
                        if (MailboxSyncerJobs.activeJobs.Count == 0)
                        {
                            MailboxSyncerJobs.activeJobsIsEmpty.Set();
                        }
                    }
                    MRSService.Tickle(baseJob.RequestJobGuid, baseJob.RequestJobStoringMDB.ObjectGuid, MoveRequestNotification.Canceled);
                    break;

                case JobState.Waiting:
                    break;

                default:
                    return;
                }
            }
        }
 // Token: 0x06000007 RID: 7 RVA: 0x00002684 File Offset: 0x00000884
 private void AbortStartup(Exception ex)
 {
     MRSService.LogEvent(MRSEventLogConstants.Tuple_ServiceFailedToStart, new object[]
     {
         (ex != null) ? CommonUtils.FullExceptionMessage(ex, true) : string.Empty
     });
     base.GracefullyAbortStartup();
 }
 private void SyncNow(List <SyncNowNotification> notifications)
 {
     this.ForwardKnownExceptions(delegate
     {
         foreach (SyncNowNotification notification in notifications)
         {
             MRSService.SyncNow(notification);
         }
     }, null);
 }
 public static void CleanADOrphanAndInconsistency()
 {
     PartitionId[] allAccountPartitionIds = ADAccountPartitionLocator.GetAllAccountPartitionIds();
     for (int i = 0; i < allAccountPartitionIds.Length; i++)
     {
         PartitionId partitionId = allAccountPartitionIds[i];
         CommonUtils.CheckForServiceStopping();
         ADSessionSettings adsessionSettings = ADSessionSettings.FromAllTenantsPartitionId(partitionId);
         adsessionSettings.IncludeSoftDeletedObjects = true;
         adsessionSettings.IncludeInactiveMailbox    = true;
         IRecipientSession     recipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, false, ConsistencyMode.PartiallyConsistent, null, adsessionSettings, 45, "CleanADOrphanAndInconsistency", "f:\\15.00.1497\\sources\\dev\\mrs\\src\\Service\\ADInconsistencyCheck.cs");
         IConfigurationSession configSession    = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(null, false, ConsistencyMode.PartiallyConsistent, null, adsessionSettings, 52, "CleanADOrphanAndInconsistency", "f:\\15.00.1497\\sources\\dev\\mrs\\src\\Service\\ADInconsistencyCheck.cs");
         using (List <Guid> .Enumerator enumerator = MapiUtils.GetDatabasesOnThisServer().GetEnumerator())
         {
             while (enumerator.MoveNext())
             {
                 Guid dbGuid = enumerator.Current;
                 CommonUtils.CheckForServiceStopping();
                 DatabaseInformation databaseInformation = MapiUtils.FindServerForMdb(dbGuid, null, null, FindServerFlags.AllowMissing);
                 if (databaseInformation.IsMissing)
                 {
                     MrsTracer.Service.Debug("CleanADOrphanAndInconsistency Database {0} in Forest {1} is missing, skip it", new object[]
                     {
                         dbGuid,
                         databaseInformation.ForestFqdn
                     });
                 }
                 else
                 {
                     CommonUtils.CatchKnownExceptions(delegate
                     {
                         ADInconsistencyCheck.CleanADOrphanAndInconsistencyForRequests(recipientSession, configSession, dbGuid);
                     }, delegate(Exception f)
                     {
                         MrsTracer.Service.Error("CleanADOrphanAndInconsistency() failed for DB {0}. Error: {1}", new object[]
                         {
                             dbGuid,
                             CommonUtils.FullExceptionMessage(f, true)
                         });
                         MRSService.LogEvent(MRSEventLogConstants.Tuple_ScanADInconsistencyRequestFailEvent, new object[]
                         {
                             dbGuid,
                             string.Empty,
                             string.Empty,
                             CommonUtils.FullExceptionMessage(f, true)
                         });
                     });
                 }
             }
         }
     }
 }
Example #6
0
 private static void PerformLightJobAction(MapiStore systemMailbox, RequestStatisticsBase requestJobStats)
 {
     CommonUtils.CatchKnownExceptions(delegate
     {
         bool flag = false;
         LightJobBase lightJobBase;
         if (QuarantinedJobs.Contains(requestJobStats.IdentifyingGuid))
         {
             lightJobBase = new QuarantineJob(requestJobStats.IdentifyingGuid, requestJobStats.WorkItemQueueMdb.ObjectGuid, systemMailbox, requestJobStats.MessageId);
         }
         else if (requestJobStats.ShouldRehomeRequest)
         {
             lightJobBase = new RehomeJob(requestJobStats.IdentifyingGuid, requestJobStats.RequestQueue, requestJobStats.OptimalRequestQueue, systemMailbox, requestJobStats.MessageId);
         }
         else if (requestJobStats.ShouldClearRehomeRequest)
         {
             lightJobBase = new ClearRehomeJob(requestJobStats.IdentifyingGuid, requestJobStats.WorkItemQueueMdb.ObjectGuid, systemMailbox, requestJobStats.MessageId);
         }
         else if (requestJobStats.ShouldSuspendRequest)
         {
             lightJobBase = new SuspendJob(requestJobStats.IdentifyingGuid, requestJobStats.WorkItemQueueMdb.ObjectGuid, systemMailbox, requestJobStats.MessageId);
         }
         else
         {
             lightJobBase = new ResumeJob(requestJobStats.IdentifyingGuid, requestJobStats.WorkItemQueueMdb.ObjectGuid, systemMailbox, requestJobStats.MessageId);
             flag         = true;
         }
         using (lightJobBase)
         {
             lightJobBase.Run();
             if (flag)
             {
                 MRSService.Tickle(requestJobStats.IdentifyingGuid, requestJobStats.WorkItemQueueMdb.ObjectGuid, MoveRequestNotification.Created);
             }
         }
     }, delegate(Exception failure)
     {
         LocalizedString localizedString = CommonUtils.FullExceptionMessage(failure);
         MrsTracer.Service.Debug("Unexpected failure occurred trying to perform a light pipe action on MoveJob '{0}' from queue '{1}', skipping it. {2}", new object[]
         {
             requestJobStats.RequestGuid,
             requestJobStats.RequestQueue,
             localizedString
         });
         MailboxReplicationService.LogEvent(MRSEventLogConstants.Tuple_UnableToProcessRequest, new object[]
         {
             requestJobStats.RequestGuid.ToString(),
             requestJobStats.WorkItemQueueMdb.ObjectGuid.ToString(),
             localizedString
         });
     });
 }
Example #7
0
 public void StopService()
 {
     MrsTracer.Service.Debug("Stopping service...", new object[0]);
     CommonUtils.ServiceIsStopping = true;
     MRSService.lightJobPoller.WaitForJobToBeDone();
     MRSService.jobPoller.WaitForJobToBeDone();
     MailboxSyncerJobs.WaitForAllJobsToComplete();
     ProcessAccessManager.UnregisterComponent(ConfigBase <MRSConfigSchema> .Provider);
     ProcessAccessManager.UnregisterComponent(MRSService.issueCache);
     ProcessAccessManager.UnregisterComponent(this);
     MailboxSyncerJobs.StopScheduling();
     MRSService.LogEvent(MRSEventLogConstants.Tuple_ServiceStopped, new object[0]);
     MrsTracer.Service.Debug("Service stopped.", new object[0]);
 }
 private static void CleanADOrphanAndInconsistencyForRequests(IRecipientSession recipientSession, IConfigurationSession configSession, Guid dbGuid)
 {
     MrsTracer.Service.Debug("Try to CleanADOrphanAndInconsistencyForRequests for Database {0} name is {1}", new object[]
     {
         dbGuid,
         dbGuid
     });
     using (RequestJobProvider rjProvider = new RequestJobProvider(dbGuid))
     {
         rjProvider.LoadReport   = false;
         rjProvider.AllowInvalid = true;
         foreach (object obj in Enum.GetValues(typeof(MRSRequestType)))
         {
             MRSRequestType requestType = (MRSRequestType)obj;
             MrsTracer.Service.Debug("Try to CleanADOrphanAndInconsistencyForRequests for request type {0}", new object[]
             {
                 requestType
             });
             CommonUtils.CatchKnownExceptions(delegate
             {
                 if (requestType == MRSRequestType.Move)
                 {
                     ADInconsistencyCheck.CleanADOrphanAndInconsistencyForMoves(recipientSession, rjProvider, dbGuid);
                     return;
                 }
                 ADInconsistencyCheck.CleanADOrphanAndInconsistencyForNonMoves(configSession, requestType, rjProvider, dbGuid);
             }, delegate(Exception f)
             {
                 MrsTracer.Service.Error("CleanADOrphanAndInconsistencyForRequests() failed for DB {0}. Request type {1} Error: {2}", new object[]
                 {
                     dbGuid,
                     requestType.ToString(),
                     CommonUtils.FullExceptionMessage(f, true)
                 });
                 MRSService.LogEvent(MRSEventLogConstants.Tuple_ScanADInconsistencyRequestFailEvent, new object[]
                 {
                     dbGuid,
                     requestType.ToString(),
                     string.Empty,
                     CommonUtils.FullExceptionMessage(f, true)
                 });
             });
         }
     }
 }
Example #9
0
 public MoveJob(PropValue[] properties, Guid requestQueueGuid)
 {
     this.JobType = MapiUtils.GetValue <MRSJobType>(properties[9], MRSJobType.Unknown);
     if (!RequestJobXML.IsKnownJobType(this.JobType))
     {
         MrsTracer.Service.Debug("Skipping unknown jobType {0}", new object[]
         {
             (int)this.JobType
         });
         return;
     }
     this.RequestGuid         = MapiUtils.GetValue <Guid>(properties[26], Guid.Empty);
     this.ExchangeGuid        = MapiUtils.GetValue <Guid>(properties[5], Guid.Empty);
     this.ArchiveGuid         = MapiUtils.GetValue <Guid>(properties[6], Guid.Empty);
     this.CancelRequest       = MapiUtils.GetValue <bool>(properties[4], false);
     this.MrsServerName       = MapiUtils.GetValue <string>(properties[2], null);
     this.Status              = MapiUtils.GetValue <RequestStatus>(properties[0], RequestStatus.None);
     this.JobState            = MapiUtils.GetValue <JobProcessingState>(properties[1], JobProcessingState.NotReady);
     this.LastUpdateTimeStamp = MapiUtils.GetValue <DateTime>(properties[7], DateTime.MinValue);
     this.Flags = MapiUtils.GetValue <RequestFlags>(properties[10], RequestFlags.None);
     this.SourceDatabaseGuid        = MapiUtils.GetValue <Guid>(properties[11], Guid.Empty);
     this.TargetDatabaseGuid        = MapiUtils.GetValue <Guid>(properties[12], Guid.Empty);
     this.SourceArchiveDatabaseGuid = MapiUtils.GetValue <Guid>(properties[15], Guid.Empty);
     this.TargetArchiveDatabaseGuid = MapiUtils.GetValue <Guid>(properties[16], Guid.Empty);
     this.Priority = MapiUtils.GetValue <int>(properties[17], -1);
     this.DoNotPickUntilTimestamp = MapiUtils.GetValue <DateTime>(properties[13], DateTime.MinValue);
     this.RequestType             = MapiUtils.GetValue <MRSRequestType>(properties[14], MRSRequestType.Move);
     this.MessageID          = MapiUtils.GetValue <byte[]>(properties[27], null);
     this.SourceExchangeGuid = MapiUtils.GetValue <Guid>(properties[18], Guid.Empty);
     this.TargetExchangeGuid = MapiUtils.GetValue <Guid>(properties[19], Guid.Empty);
     this.RehomeRequest      = MapiUtils.GetValue <bool>(properties[20], false);
     this.InternalFlags      = MapiUtils.GetValue <RequestJobInternalFlags>(properties[21], RequestJobInternalFlags.None);
     this.PoisonCount        = MapiUtils.GetValue <int>(properties[23], 0);
     this.FailureType        = MapiUtils.GetValue <string>(properties[24], null);
     this.WorkloadType       = MapiUtils.GetValue <RequestWorkloadType>(properties[25], RequestWorkloadType.None);
     byte[] value = MapiUtils.GetValue <byte[]>(properties[22], null);
     this.PartitionHint             = ((value != null && value.Length > 0) ? TenantPartitionHint.FromPersistablePartitionHint(value) : null);
     this.RequestQueueGuid          = requestQueueGuid;
     this.IsActiveOnThisMRSInstance = MRSService.JobIsActive(this.RequestGuid);
     this.isInteractive             = MoveJob.IsInteractive(this.RequestType, this.WorkloadType);
 }
 private bool HandleFailure(Exception failure)
 {
     if (failure == null)
     {
         return(true);
     }
     if (failure is ServiceIsStoppingPermanentException)
     {
         return(false);
     }
     if (CommonUtils.ClassifyException(failure).Length > 0)
     {
         return(true);
     }
     MRSService.LogEvent(MRSEventLogConstants.Tuple_PeriodicTaskStoppingExecution, new object[]
     {
         this.jobName,
         CommonUtils.FullExceptionMessage(failure)
     });
     return(false);
 }
        public void PickupJobs(out string failure)
        {
            string dbName      = null;
            string scanFailure = null;

            failure = null;
            using (new DatabaseSettingsContext(this.MdbGuid, null).Activate())
            {
                CommonUtils.CatchKnownExceptions(delegate
                {
                    DatabaseInformation databaseInformation = MapiUtils.FindServerForMdb(this.MdbGuid, null, null, FindServerFlags.None);
                    dbName = databaseInformation.DatabaseName;
                    if (!databaseInformation.IsOnThisServer)
                    {
                        scanFailure = string.Format("MDB is mounted on remote server {0}", databaseInformation.ServerFqdn);
                        MRSQueue.RemoveQueue(this.MdbGuid);
                        return;
                    }
                    MrsTracer.Service.Debug("Picking up jobs from '{0}' ({1})", new object[]
                    {
                        dbName,
                        this.MdbGuid
                    });
                    using (MapiStore systemMailbox = MapiUtils.GetSystemMailbox(this.MdbGuid, false))
                    {
                        using (MapiFolder requestJobsFolder = RequestJobXML.GetRequestJobsFolder(systemMailbox))
                        {
                            using (MapiTable contentsTable = requestJobsFolder.GetContentsTable(ContentsTableFlags.DeferredErrors))
                            {
                                if (contentsTable.GetRowCount() > 0)
                                {
                                    RequestJobNamedPropertySet requestJobNamedPropertySet = RequestJobNamedPropertySet.Get(systemMailbox);
                                    contentsTable.SetColumns(requestJobNamedPropertySet.PropTags);
                                    this.ProcessJobs(systemMailbox, contentsTable, requestJobNamedPropertySet);
                                }
                            }
                        }
                    }
                    MrsTracer.Service.Debug("Pick up jobs from Mdb: '{0}' - complete.", new object[]
                    {
                        dbName
                    });
                }, delegate(Exception f)
                {
                    if (dbName == null)
                    {
                        dbName = MrsStrings.MissingDatabaseName(this.MdbGuid).ToString();
                    }
                    MrsTracer.Service.Debug("PickupJobs() failed for mdb '{0}'. Error: {1}", new object[]
                    {
                        dbName,
                        CommonUtils.FullExceptionMessage(f)
                    });
                    scanFailure = CommonUtils.FullExceptionMessage(f, true);
                    MRSService.LogEvent(MRSEventLogConstants.Tuple_UnableToProcessJobsInDatabase, new object[]
                    {
                        dbName,
                        CommonUtils.FullExceptionMessage(f)
                    });
                });
            }
            failure = scanFailure;
        }
 public static void LogEvent(ExEventLog.EventTuple tuple, params object[] args)
 {
     MRSService.LogEvent(tuple, args);
 }
Example #13
0
 protected override void AfterRelinquishAction()
 {
     MRSService.Tickle(base.RequestGuid, this.RequestQueueGuid, MoveRequestNotification.Created);
 }
        // Token: 0x06000004 RID: 4 RVA: 0x00002248 File Offset: 0x00000448
        protected override void OnStartInternal(string[] args)
        {
            try
            {
                ConfigBase <MRSConfigSchema> .InitializeConfigProvider(new Func <IConfigSchema, IConfigProvider>(ConfigProvider.CreateProvider));

                if (!ConfigBase <MRSConfigSchema> .GetConfig <bool>("IsEnabled"))
                {
                    MRSService.LogEvent(MRSEventLogConstants.Tuple_ServiceIsDisabled, new object[0]);
                    this.AbortStartup(null);
                }
                else
                {
                    MrsTracer.Service.Debug("Starting Mailbox Replication Service", new object[0]);
                    MRSService.Instance = new MRSService();
                    this.host           = new ServiceHost(typeof(MailboxReplicationService), new Uri[0]);
                    this.proxyHost      = new ServiceHost(typeof(MailboxReplicationProxyService), new Uri[0]);
                    if (MailboxReplicationServiceImpl.runningAsService)
                    {
                        base.RequestAdditionalTime((int)(this.host.OpenTimeout + TimeSpan.FromSeconds(10.0)).TotalMilliseconds);
                    }
                    this.host.Open(TimeSpan.FromSeconds(120.0));
                    this.proxyHost.Open(TimeSpan.FromSeconds(120.0));
                    MRSService.Instance.StartService();
                    MrsTracer.Service.Debug("Mailbox Replication Service started successfully", new object[0]);
                    using (Process currentProcess = Process.GetCurrentProcess())
                    {
                        MRSService.LogEvent(MRSEventLogConstants.Tuple_ServiceStarted, new object[]
                        {
                            VersionInformation.MRS.ProductMajor,
                            VersionInformation.MRS.ProductMinor,
                            VersionInformation.MRS.BuildMajor,
                            VersionInformation.MRS.BuildMinor,
                            currentProcess.Id
                        });
                    }
                }
            }
            catch (AddressAlreadyInUseException ex)
            {
                this.AbortStartup(ex);
            }
            catch (ArgumentException ex2)
            {
                this.AbortStartup(ex2);
            }
            catch (ConfigurationErrorsException ex3)
            {
                this.AbortStartup(ex3);
            }
            catch (ConfigurationSettingsException ex4)
            {
                this.AbortStartup(ex4);
            }
            catch (InvalidOperationException ex5)
            {
                this.AbortStartup(ex5);
            }
            catch (System.TimeoutException ex6)
            {
                this.AbortStartup(ex6);
            }
            catch (System.ServiceProcess.TimeoutException ex7)
            {
                this.AbortStartup(ex7);
            }
            catch (CommunicationException ex8)
            {
                this.AbortStartup(ex8);
            }
            catch (RpcException ex9)
            {
                this.AbortStartup(ex9);
            }
        }
        private static void CleanADOrphanAndInconsistencyForMoves(IRecipientSession recipientSession, RequestJobProvider rjProvider, Guid dbGuid)
        {
            ADObjectId  propertyValue = new ADObjectId(dbGuid);
            QueryFilter queryFilter   = new AndFilter(new QueryFilter[]
            {
                new ComparisonFilter(ComparisonOperator.NotEqual, ADUserSchema.MailboxMoveStatus, RequestStatus.None),
                new ExistsFilter(ADUserSchema.MailboxMoveStatus)
            });
            QueryFilter queryFilter2 = QueryFilter.OrTogether(new QueryFilter[]
            {
                QueryFilter.AndTogether(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADUserSchema.MailboxMoveSourceMDB, propertyValue),
                    new BitMaskAndFilter(ADUserSchema.MailboxMoveFlags, 4UL)
                }),
                QueryFilter.AndTogether(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADUserSchema.MailboxMoveTargetMDB, propertyValue),
                    new BitMaskAndFilter(ADUserSchema.MailboxMoveFlags, 8UL)
                })
            });
            QueryFilter filter = new AndFilter(new QueryFilter[]
            {
                queryFilter,
                queryFilter2
            });

            ADRecipient[] array = recipientSession.Find(null, QueryScope.SubTree, filter, null, 1000);
            if (array == null || array.Length == 0)
            {
                MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves(): No move requests found for DB {0}", new object[]
                {
                    dbGuid
                });
                return;
            }
            bool needUpdateAD = false;

            ADRecipient[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                ADRecipient request = array2[i];
                CommonUtils.CatchKnownExceptions(delegate
                {
                    needUpdateAD  = false;
                    ADUser aduser = request as ADUser;
                    MoveRequestStatistics moveRequestStatistics = (MoveRequestStatistics)rjProvider.Read <MoveRequestStatistics>(new RequestJobObjectId(aduser.ExchangeGuid, dbGuid, null));
                    if (moveRequestStatistics == null || (!moveRequestStatistics.IsFake && moveRequestStatistics.Status == RequestStatus.None))
                    {
                        MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():AD orphan {0} found for DB {1}", new object[]
                        {
                            aduser.ExchangeGuid,
                            dbGuid
                        });
                        CommonUtils.CleanupMoveRequestInAD(recipientSession, null, aduser);
                        return;
                    }
                    if (moveRequestStatistics.IsFake)
                    {
                        MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():request {0} is uplevel/Fake, ignore it", new object[]
                        {
                            aduser.ExchangeGuid
                        });
                        return;
                    }
                    if (moveRequestStatistics.User == null)
                    {
                        MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():request {0} has been deleted from AD, ignore it", new object[]
                        {
                            aduser.ExchangeGuid
                        });
                        return;
                    }
                    if (moveRequestStatistics.TimeTracker.GetCurrentDurationChunk() > ADInconsistencyCheck.updateLatencyThreshhold)
                    {
                        RequestStatus versionAppropriateStatus = RequestJobBase.GetVersionAppropriateStatus(moveRequestStatistics.Status, aduser.ExchangeVersion);
                        if (versionAppropriateStatus != moveRequestStatistics.User.MailboxMoveStatus)
                        {
                            MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():AD inconsistency {0} found for DB {1}, AD status is {2} but store status is {3} ({4})", new object[]
                            {
                                aduser.ExchangeGuid,
                                dbGuid,
                                aduser.MailboxMoveStatus,
                                moveRequestStatistics.Status,
                                versionAppropriateStatus
                            });
                            aduser.MailboxMoveStatus = versionAppropriateStatus;
                            needUpdateAD             = true;
                        }
                        RequestFlags versionAppropriateFlags = RequestJobBase.GetVersionAppropriateFlags(moveRequestStatistics.Flags, aduser.ExchangeVersion);
                        if (versionAppropriateFlags != moveRequestStatistics.User.MailboxMoveFlags)
                        {
                            MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():AD inconsistency {0} found for DB {1}, AD flags is {2} but store flags is {3} ({4})", new object[]
                            {
                                aduser.ExchangeGuid,
                                dbGuid,
                                aduser.MailboxMoveFlags,
                                moveRequestStatistics.Flags,
                                versionAppropriateFlags
                            });
                            aduser.MailboxMoveFlags = versionAppropriateFlags;
                            needUpdateAD            = true;
                        }
                        if (needUpdateAD)
                        {
                            recipientSession.Save(request);
                        }
                    }
                }, delegate(Exception f)
                {
                    MrsTracer.Service.Error("CleanADOrphanAndInconsistencyForMoves() failed for DB {0}. move request {1} Error: {2}", new object[]
                    {
                        dbGuid,
                        ((ADUser)request).ExchangeGuid,
                        CommonUtils.FullExceptionMessage(f, true)
                    });
                    MRSService.LogEvent(MRSEventLogConstants.Tuple_ScanADInconsistencyRequestFailEvent, new object[]
                    {
                        dbGuid,
                        MRSRequestType.Move.ToString(),
                        ((ADUser)request).ExchangeGuid,
                        CommonUtils.FullExceptionMessage(f, true)
                    });
                });
            }
        }
        private static void CleanADOrphanAndInconsistencyForNonMoves(IConfigurationSession configSession, MRSRequestType requestType, RequestJobProvider rjProvider, Guid dbGuid)
        {
            ADObjectId requestQueueId = new ADObjectId(dbGuid);
            RequestIndexEntryQueryFilter requestIndexEntryQueryFilter = new RequestIndexEntryQueryFilter();

            requestIndexEntryQueryFilter.IndexId        = new RequestIndexId(RequestIndexLocation.AD);
            requestIndexEntryQueryFilter.RequestType    = requestType;
            requestIndexEntryQueryFilter.RequestQueueId = requestQueueId;
            MRSRequestWrapper[] array = ADHandler.Find(configSession, requestIndexEntryQueryFilter, null, true, null);
            if (array != null && array.Length > 0)
            {
                bool needUpdateAD          = false;
                MRSRequestWrapper[] array2 = array;
                for (int i = 0; i < array2.Length; i++)
                {
                    MRSRequestWrapper request = array2[i];
                    CommonUtils.CatchKnownExceptions(delegate
                    {
                        needUpdateAD = false;
                        if (request.Status != RequestStatus.None)
                        {
                            RequestStatisticsBase requestStatisticsBase = (RequestStatisticsBase)rjProvider.Read <RequestStatisticsBase>(new RequestJobObjectId(request.RequestGuid, dbGuid, null));
                            if (requestStatisticsBase == null || (!requestStatisticsBase.IsFake && requestStatisticsBase.Status == RequestStatus.None))
                            {
                                MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForRequests():AD orphan {0} found for DB {1}", new object[]
                                {
                                    request.RequestGuid,
                                    dbGuid
                                });
                                ADHandler.Delete(configSession, request);
                                return;
                            }
                            if (requestStatisticsBase.IsFake)
                            {
                                MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForRequests():request {0} is uplevel/Fake, ignoring it", new object[]
                                {
                                    request.RequestGuid
                                });
                                return;
                            }
                            if (requestStatisticsBase.IndexEntries == null || requestStatisticsBase.IndexEntries.Count == 0)
                            {
                                MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForRequests():request {0} has been removed from AD, ignoring it", new object[]
                                {
                                    request.RequestGuid
                                });
                                return;
                            }
                            if (requestStatisticsBase.TimeTracker.GetCurrentDurationChunk() > ADInconsistencyCheck.updateLatencyThreshhold)
                            {
                                if (requestStatisticsBase.Status != requestStatisticsBase.IndexEntries[0].Status)
                                {
                                    MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForRequests():AD inconsistency {0} found for DB {1}, AD status is {2} but store status is {3}", new object[]
                                    {
                                        request.RequestGuid,
                                        dbGuid,
                                        request.Status,
                                        requestStatisticsBase.Status
                                    });
                                    request.Status = requestStatisticsBase.Status;
                                    needUpdateAD   = true;
                                }
                                if (requestStatisticsBase.Flags != requestStatisticsBase.IndexEntries[0].Flags)
                                {
                                    MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForRequests():AD inconsistency {0} found for DB {1}, AD flags is {2} but store flags is {3}", new object[]
                                    {
                                        request.RequestGuid,
                                        dbGuid,
                                        request.Flags,
                                        requestStatisticsBase.Flags
                                    });
                                    request.Flags = requestStatisticsBase.Flags;
                                    needUpdateAD  = true;
                                }
                                if (needUpdateAD)
                                {
                                    ADHandler.Save(configSession, request);
                                    return;
                                }
                            }
                        }
                        else
                        {
                            MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForRequests():request {0} for {1} has been removed from AD, store orphan will be handled by MRS pick up job logic", new object[]
                            {
                                request.RequestGuid,
                                dbGuid
                            });
                        }
                    }, delegate(Exception f)
                    {
                        MrsTracer.Service.Error("CleanADOrphanAndInconsistencyForRequests() failed for DB {0}. Request type {1} Request guid {2} Error: {3}", new object[]
                        {
                            dbGuid,
                            requestType.ToString(),
                            request.RequestGuid,
                            CommonUtils.FullExceptionMessage(f, true)
                        });
                        MRSService.LogEvent(MRSEventLogConstants.Tuple_ScanADInconsistencyRequestFailEvent, new object[]
                        {
                            dbGuid,
                            requestType.ToString(),
                            request.RequestGuid,
                            CommonUtils.FullExceptionMessage(f, true)
                        });
                    });
                }
                return;
            }
            MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForRequests(): No {0} requests found for DB {1}", new object[]
            {
                requestType,
                dbGuid
            });
        }