protected virtual void UpdateRecipientSyncStateValueInAD(RecipientSyncOperation operation)
        {
            if (this.updateConnection == null)
            {
                ADObjectId        rootId            = null;
                ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    PooledLdapConnection readConnection = this.ConfigSession.GetReadConnection(this.sourceConnection.Fqdn, ref rootId);
                    this.updateConnection = new Connection(readConnection, EdgeSyncSvc.EdgeSync.AppConfig);
                }, 3);
                if (!adoperationResult.Succeeded)
                {
                    ExTraceGlobals.TargetConnectionTracer.TraceError <string>((long)this.GetHashCode(), "Failed to get AD connection to update SyncState because of {0}", adoperationResult.Exception.Message);
                    throw new ExDirectoryException("Failed to get AD connection to update SyncState", adoperationResult.Exception);
                }
            }
            byte[]        array   = RecipientSyncState.SerializeRecipientSyncState(operation.RecipientSyncState);
            ModifyRequest request = new ModifyRequest(operation.DistinguishedName, DirectoryAttributeOperation.Replace, "msExchExternalSyncState", new object[]
            {
                array
            });

            this.updateConnection.SendRequest(request);
            ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>((long)this.GetHashCode(), "Successfully updated SyncState in AD for {0}", operation.DistinguishedName);
            base.LogSession.LogEvent(EdgeSyncLoggingLevel.Low, EdgeSyncEvent.TargetConnection, operation.DistinguishedName, "Successfully synced to MSERV and updated SyncState");
        }
        private void PerformLookup(string domainController, List <string> addresses)
        {
            MserveWebService mserveWebService = EdgeSyncMservConnector.CreateDefaultMserveWebService(domainController);

            if (mserveWebService == null)
            {
                throw new InvalidOperationException("Invalid MServ configuration.");
            }
            List <RecipientSyncOperation> list;

            foreach (string text in addresses)
            {
                RecipientSyncOperation recipientSyncOperation = new RecipientSyncOperation();
                if (text.StartsWith("smtp:", StringComparison.OrdinalIgnoreCase))
                {
                    recipientSyncOperation.ReadEntries.Add(text.Substring(5));
                }
                else
                {
                    recipientSyncOperation.ReadEntries.Add(text);
                }
                list = mserveWebService.Synchronize(recipientSyncOperation);
                foreach (RecipientSyncOperation recipientSyncOperation2 in list)
                {
                    base.WriteObject(new MservRecipientRecord(recipientSyncOperation2.ReadEntries[0], recipientSyncOperation2.PartnerId));
                }
            }
            list = mserveWebService.Synchronize();
            foreach (RecipientSyncOperation recipientSyncOperation3 in list)
            {
                base.WriteObject(new MservRecipientRecord(recipientSyncOperation3.ReadEntries[0], recipientSyncOperation3.PartnerId));
            }
        }
        private static bool RemoveMserveEntryWithExactValue(string address, int value)
        {
            RecipientSyncOperation recipientSyncOperation = new RecipientSyncOperation();

            recipientSyncOperation.RemovedEntries.Add(address);
            recipientSyncOperation.PartnerId = value;
            MServDirectorySession.SyncToMserv(address, recipientSyncOperation);
            return(recipientSyncOperation.Synchronized);
        }
        internal static bool AddMserveEntry(string address, int value)
        {
            RecipientSyncOperation recipientSyncOperation = new RecipientSyncOperation();

            recipientSyncOperation.AddedEntries.Add(address);
            recipientSyncOperation.PartnerId = value;
            MServDirectorySession.SyncToMserv(address, recipientSyncOperation);
            return(recipientSyncOperation.Synchronized);
        }
        public void UpdateRecipientSyncStateValue(RecipientSyncOperation operation)
        {
            Dictionary <string, HashSet <string> > dictionary = new Dictionary <string, HashSet <string> >(MserveTargetConnection.ReplicationAddressAttributes.Length, StringComparer.OrdinalIgnoreCase);

            foreach (string text in MserveTargetConnection.ReplicationAddressAttributes)
            {
                string recipientSyncStateAttribute = MserveTargetConnection.GetRecipientSyncStateAttribute(operation.RecipientSyncState, text);
                dictionary[text] = RecipientSyncState.AddressHashSetFromConcatStringValue(recipientSyncStateAttribute);
            }
            foreach (OperationType key in operation.PendingSyncStateCommitEntries.Keys)
            {
                foreach (string text2 in operation.PendingSyncStateCommitEntries[key])
                {
                    string key2 = null;
                    if (!operation.AddressTypeTable.TryGetValue(text2, out key2))
                    {
                        throw new InvalidOperationException(text2 + " is not in AddressTypeTable");
                    }
                    switch (key)
                    {
                    case OperationType.Add:
                        if (!dictionary[key2].Contains(text2))
                        {
                            dictionary[key2].Add(text2);
                        }
                        break;

                    case OperationType.Delete:
                        if (dictionary[key2].Contains(text2))
                        {
                            dictionary[key2].Remove(text2);
                        }
                        break;
                    }
                }
            }
            foreach (string text3 in MserveTargetConnection.ReplicationAddressAttributes)
            {
                MserveTargetConnection.SetRecipientSyncStateAttribute(operation.RecipientSyncState, text3, RecipientSyncState.AddressHashSetToConcatStringValue(dictionary[text3]));
            }
        }
        private static void OnAddressChange(DirectoryAttribute attribute, RecipientSyncOperation operation)
        {
            HashSet <string> hashSet = RecipientSyncState.AddressHashSetFromConcatStringValue(MserveTargetConnection.GetRecipientSyncStateAttribute(operation.RecipientSyncState, attribute.Name));

            foreach (object obj in attribute)
            {
                string text = (string)obj;
                string text2;
                if (text.StartsWith("smtp:", StringComparison.OrdinalIgnoreCase))
                {
                    text2 = text.Substring(5);
                }
                else if (text.StartsWith("meum:", StringComparison.OrdinalIgnoreCase))
                {
                    text2 = text.Substring(5);
                }
                else
                {
                    text2 = text;
                }
                if (!hashSet.Contains(text2))
                {
                    operation.AddedEntries.Add(text2);
                    operation.AddressTypeTable[text2] = attribute.Name;
                    ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>(0L, "Add {0} to AddedEntries", text2);
                }
                else
                {
                    hashSet.Remove(text2);
                }
            }
            foreach (string text3 in hashSet)
            {
                operation.RemovedEntries.Add(text3);
                operation.AddressTypeTable[text3] = attribute.Name;
                ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>(0L, "Add {0} to RemovedEntries", text3);
            }
        }
        private bool ResolveDuplicateAddedEntries()
        {
            if (this.operationsWithDuplicatedAddEntries.Count == 0)
            {
                return(true);
            }
            int num = 0;

            foreach (RecipientSyncOperation recipientSyncOperation in this.operationsWithDuplicatedAddEntries)
            {
                num += recipientSyncOperation.DuplicatedAddEntries.Count;
            }
            base.LogSession.LogEvent(EdgeSyncLoggingLevel.Medium, EdgeSyncEvent.TargetConnection, null, "ResolveDuplicateAddedEntries: Count=" + this.operationsWithDuplicatedAddEntries.Count);
            bool result;

            try
            {
                this.mserveService.Reset();
                this.mserveService.TrackDuplicatedAddEntries = false;
                List <RecipientSyncOperation> list  = new List <RecipientSyncOperation>();
                List <RecipientSyncOperation> list2 = null;
                foreach (RecipientSyncOperation recipientSyncOperation2 in this.operationsWithDuplicatedAddEntries)
                {
                    foreach (string item in recipientSyncOperation2.DuplicatedAddEntries)
                    {
                        list.Add(new RecipientSyncOperation
                        {
                            ReadEntries =
                            {
                                item
                            }
                        });
                    }
                }
                base.LogSession.LogEvent(EdgeSyncLoggingLevel.Medium, EdgeSyncEvent.TargetConnection, null, "ResolveDuplicateAddedEntries: Read duplicated entry's partnerId from MSERV");
                if (!this.SyncBatchOperations(list, out list2))
                {
                    result = false;
                }
                else
                {
                    List <RecipientSyncOperation> list3 = new List <RecipientSyncOperation>();
                    List <RecipientSyncOperation> list4 = null;
                    foreach (RecipientSyncOperation recipientSyncOperation3 in list2)
                    {
                        if (recipientSyncOperation3.PartnerId < this.podSiteStartRange || recipientSyncOperation3.PartnerId > this.podSiteEndRange)
                        {
                            RecipientSyncOperation recipientSyncOperation4 = new RecipientSyncOperation();
                            recipientSyncOperation4.PartnerId = recipientSyncOperation3.PartnerId;
                            recipientSyncOperation4.RemovedEntries.AddRange(recipientSyncOperation3.ReadEntries);
                            list3.Add(recipientSyncOperation4);
                        }
                        else
                        {
                            base.LogSession.LogEvent(EdgeSyncLoggingLevel.Medium, EdgeSyncEvent.TargetConnection, null, string.Concat(new object[]
                            {
                                "Warning: ",
                                recipientSyncOperation3.ReadEntries[0],
                                " has existing Exchange partnerID ",
                                recipientSyncOperation3.PartnerId,
                                ". Skip fixing its partnerId as changing partnerID of Exchange forest is not supported."
                            }));
                        }
                    }
                    base.LogSession.LogEvent(EdgeSyncLoggingLevel.Medium, EdgeSyncEvent.TargetConnection, null, "ResolveDuplicateAddedEntries: Delete duplicated entry's partnerId from MSERV");
                    if (!this.SyncBatchOperations(list3, out list4))
                    {
                        result = false;
                    }
                    else
                    {
                        List <RecipientSyncOperation> list5 = null;
                        foreach (RecipientSyncOperation recipientSyncOperation5 in this.operationsWithDuplicatedAddEntries)
                        {
                            recipientSyncOperation5.AddedEntries.Clear();
                            recipientSyncOperation5.RemovedEntries.Clear();
                            recipientSyncOperation5.ReadEntries.Clear();
                            recipientSyncOperation5.AddedEntries.AddRange(recipientSyncOperation5.DuplicatedAddEntries);
                            recipientSyncOperation5.DuplicatedAddEntries.Clear();
                        }
                        base.LogSession.LogEvent(EdgeSyncLoggingLevel.Medium, EdgeSyncEvent.TargetConnection, null, "ResolveDuplicateAddedEntries: Add duplicated entry back to MSERV with Exchange partnerId");
                        if (this.operationsWithDuplicatedAddEntries.Count > this.duplicatedAddEntriesCacheSize)
                        {
                            base.LogSession.LogEvent(EdgeSyncLoggingLevel.Medium, EdgeSyncEvent.TargetConnection, null, "Failed: DuplicatedAddEntriesCacheSize limit reached");
                            this.SyncBatchOperations(this.operationsWithDuplicatedAddEntries, out list5);
                            result = false;
                        }
                        else
                        {
                            result = this.SyncBatchOperations(this.operationsWithDuplicatedAddEntries, out list5);
                        }
                    }
                }
            }
            finally
            {
                this.mserveService.TrackDuplicatedAddEntries = true;
            }
            return(result);
        }
        protected List <RecipientSyncOperation> GetRecipientSyncOperation(ExSearchResultEntry entry)
        {
            List <RecipientSyncOperation> list = new List <RecipientSyncOperation>();

            ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>(0L, "Try to GetRecipientSyncOperation for {0}", entry.DistinguishedName);
            RecipientSyncState recipientSyncState = null;

            if (entry.Attributes.ContainsKey("msExchExternalSyncState"))
            {
                byte[] bytes = Encoding.ASCII.GetBytes((string)entry.Attributes["msExchExternalSyncState"][0]);
                recipientSyncState = RecipientSyncState.DeserializeRecipientSyncState(bytes);
                ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>(0L, "{0} has existing syncState", entry.DistinguishedName);
            }
            if (recipientSyncState == null)
            {
                if (entry.IsDeleted)
                {
                    ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>(0L, "{0} is deleted entry without syncState. Ignore the entry", entry.DistinguishedName);
                    return(list);
                }
                ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>(0L, "{0} is a normal entry without syncState. Creating one", entry.DistinguishedName);
                recipientSyncState = new RecipientSyncState();
            }
            if (!entry.IsDeleted)
            {
                int partnerId = MserveSynchronizationProvider.PartnerId;
                if (partnerId == -1)
                {
                    ExTraceGlobals.TargetConnectionTracer.TraceError <string>(0L, "Failed the sync because we could not get the partner Id for {0}", entry.DistinguishedName);
                    throw new ExDirectoryException(new ArgumentException("Failed the sync because we could not get the partner Id for " + entry.DistinguishedName));
                }
                int num = (recipientSyncState.PartnerId != 0) ? recipientSyncState.PartnerId : partnerId;
                recipientSyncState.PartnerId = partnerId;
                if (num != partnerId)
                {
                    ExTraceGlobals.TargetConnectionTracer.TraceDebug <string, int, int>(0L, "{0}'s partnerId changed from {1} to {2}", entry.DistinguishedName, num, partnerId);
                    base.LogSession.LogEvent(EdgeSyncLoggingLevel.Low, EdgeSyncEvent.TargetConnection, entry.DistinguishedName, "Warning: Changing partner ID from " + num.ToString() + " to " + partnerId.ToString());
                }
                else
                {
                    RecipientSyncOperation recipientSyncOperation = new RecipientSyncOperation(entry.DistinguishedName, partnerId, recipientSyncState, false);
                    ExTraceGlobals.TargetConnectionTracer.TraceDebug <int>(0L, "Create new operation with partner Id {0}", partnerId);
                    foreach (string key in MserveTargetConnection.ReplicationAddressAttributes)
                    {
                        if (entry.Attributes.ContainsKey(key))
                        {
                            MserveTargetConnection.OnAddressChange(entry.Attributes[key], recipientSyncOperation);
                        }
                    }
                    if (recipientSyncOperation.RemovedEntries.Count != 0 || recipientSyncOperation.AddedEntries.Count != 0)
                    {
                        list.Add(recipientSyncOperation);
                    }
                }
            }
            else
            {
                int partnerId2 = recipientSyncState.PartnerId;
                if (partnerId2 != 0)
                {
                    RecipientSyncOperation recipientSyncOperation2 = new RecipientSyncOperation(entry.DistinguishedName, partnerId2, null, true);
                    ExTraceGlobals.TargetConnectionTracer.TraceDebug <int>(0L, "Create remove operation with partner Id {0}", partnerId2);
                    foreach (string text in MserveTargetConnection.ReplicationAddressAttributes)
                    {
                        string recipientSyncStateAttribute = MserveTargetConnection.GetRecipientSyncStateAttribute(recipientSyncState, text);
                        if (recipientSyncStateAttribute != null)
                        {
                            List <string> list2 = RecipientSyncState.AddressToList(recipientSyncStateAttribute);
                            if (this.CanRemove(entry.DistinguishedName, text, list2))
                            {
                                foreach (string text2 in list2)
                                {
                                    recipientSyncOperation2.RemovedEntries.Add(text2);
                                    ExTraceGlobals.TargetConnectionTracer.TraceDebug <string>(0L, "Add {0} to RemovedEntries", text2);
                                }
                            }
                        }
                    }
                    if (recipientSyncOperation2.RemovedEntries.Count != 0)
                    {
                        list.Add(recipientSyncOperation2);
                    }
                }
                else
                {
                    ExTraceGlobals.TargetConnectionTracer.TraceDebug(0L, "No partner Id present on syncState. Skip the recipient");
                }
            }
            return(list);
        }
        private static List <RecipientSyncOperation> SyncToMserv(string address, RecipientSyncOperation operation)
        {
            int    num       = 0;
            int    partnerId = operation.PartnerId;
            string text      = (operation.AddedEntries.Count > 0) ? "Add" : ((operation.RemovedEntries.Count > 0) ? "Remove" : "Read");

            ExTraceGlobals.FaultInjectionTracer.TraceTest(4156960061U);
            ExTraceGlobals.FaultInjectionTracer.TraceTest(2546347325U);
            List <RecipientSyncOperation> result;

            for (;;)
            {
                bool      flag      = false;
                int       tickCount = Environment.TickCount;
                Exception ex        = null;
                List <RecipientSyncOperation> list = null;
                MserveWebService mserveWebService  = null;
                try
                {
                    mserveWebService = EdgeSyncMservConnector.CreateDefaultMserveWebService(null);
                    mserveWebService.TrackDuplicatedAddEntries = true;
                    flag = true;
                    ExTraceGlobals.MServTracer.TraceDebug <string, string, int>(0L, "Executing {0} for {1} with PartnerId = {2}", text, address, operation.PartnerId);
                    mserveWebService.Synchronize(operation);
                    list   = mserveWebService.Synchronize();
                    result = list;
                }
                catch (InvalidMserveRequestException ex2)
                {
                    ex = ex2;
                    throw new MServTransientException(DirectoryStrings.TransientMservError(ex2.Message));
                }
                catch (MserveException ex3)
                {
                    ex = (ex3.InnerException ?? ex3);
                    if (!MserveWebService.IsTransientException(ex3) && (ex3.InnerException == null || (!(ex3.InnerException is WebException) && !(ex3.InnerException is IOException) && !(ex3.InnerException is HttpWebRequestException) && !(ex3.InnerException is DownloadTimeoutException))))
                    {
                        throw new MServPermanentException(DirectoryStrings.PermanentMservError(ex.Message));
                    }
                    num++;
                    ExTraceGlobals.MServTracer.TraceWarning(0L, "Attempt {0}: got transient exception {1} for {2} ({3})", new object[]
                    {
                        num,
                        ex3.InnerException,
                        flag ? text : "MServeWebService creation",
                        address
                    });
                    if (num < MServDirectorySession.retriesAllowed)
                    {
                        continue;
                    }
                    throw new MServTransientException(DirectoryStrings.TransientMservError(ex.Message));
                }
                finally
                {
                    if (list != null && list.Count > 0 && text == "Read")
                    {
                        partnerId = list[0].PartnerId;
                    }
                    string failure = string.Empty;
                    int    num2    = Environment.TickCount - tickCount;
                    if (ex != null)
                    {
                        failure = ((ex.InnerException == null) ? ex.Message : ex.InnerException.ToString());
                    }
                    string diagnosticHeader = string.Empty;
                    string ipAddress        = string.Empty;
                    string transactionId    = string.Empty;
                    if (mserveWebService != null)
                    {
                        diagnosticHeader = (mserveWebService.LastResponseDiagnosticInfo ?? string.Empty);
                        ipAddress        = (mserveWebService.LastIpUsed ?? string.Empty);
                        transactionId    = (mserveWebService.LastResponseTransactionId ?? string.Empty);
                    }
                    MservProtocolLog.BeginAppend(text, (ex == null) ? "Success" : "Failure", (long)num2, failure, address, partnerId.ToString(), ipAddress, diagnosticHeader, transactionId);
                }
                break;
            }
            return(result);
        }