private void WaitAndProcessProbeResponses(MapiFolder folder, string fromAddress, Dictionary <string, string> subjectTargets, ExDateTime probeSentTime)
        {
            List <byte[]> list  = new List <byte[]>();
            List <string> list2 = new List <string>();

            for (int i = 0; i < base.Task.ExecutionTimeout; i++)
            {
                foreach (KeyValuePair <string, string> keyValuePair in subjectTargets)
                {
                    if (!string.IsNullOrEmpty(keyValuePair.Value))
                    {
                        using (MapiMessage deliveryReceipt = TestMailFlowHelper.GetDeliveryReceipt(folder, keyValuePair.Key, false))
                        {
                            if (deliveryReceipt != null)
                            {
                                PropValue prop  = deliveryReceipt.GetProp(PropTag.MessageDeliveryTime);
                                PropValue prop2 = deliveryReceipt.GetProp(PropTag.EntryId);
                                PropValue prop3 = deliveryReceipt.GetProp(PropTag.Subject);
                                if (!prop.IsError() && prop.Value != null && prop3.Value != null)
                                {
                                    string text = prop3.Value.ToString();
                                    if (text.StartsWith("RSP: CrossPremiseMailFlowMonitoring-", StringComparison.OrdinalIgnoreCase))
                                    {
                                        EnhancedTimeSpan latency = ((ExDateTime)prop.GetDateTime() > probeSentTime) ? ((ExDateTime)prop.GetDateTime() - probeSentTime) : EnhancedTimeSpan.Zero;
                                        base.OutputResult(Strings.TestMailflowSucceeded(fromAddress, keyValuePair.Value), latency, base.IsRemoteTest);
                                    }
                                    else if (text.StartsWith("Undeliverable: CrossPremiseMailFlowMonitoring-", StringComparison.OrdinalIgnoreCase))
                                    {
                                        EnhancedTimeSpan latency2 = EnhancedTimeSpan.FromSeconds(0.0);
                                        string           info     = (string)deliveryReceipt.GetProp(PropTag.Body).Value;
                                        base.OutputResult(Strings.CrossPremiseProbeNdred(fromAddress, keyValuePair.Value, info), latency2, base.IsRemoteTest);
                                    }
                                    list2.Add(keyValuePair.Key);
                                    list.Add(prop2.GetBytes());
                                }
                            }
                        }
                    }
                }
                foreach (string key in list2)
                {
                    subjectTargets.Remove(key);
                }
                list2.Clear();
                if (subjectTargets.Count == 0)
                {
                    break;
                }
                Thread.Sleep(1000);
            }
            foreach (KeyValuePair <string, string> keyValuePair2 in subjectTargets)
            {
                if (!string.IsNullOrEmpty(keyValuePair2.Value))
                {
                    EnhancedTimeSpan latency3 = EnhancedTimeSpan.FromSeconds(0.0);
                    base.OutputResult(Strings.MapiTransactionResultFailure, latency3, base.IsRemoteTest);
                }
            }
            folder.DeleteMessages(DeleteMessagesFlags.ForceHardDelete, list.ToArray());
        }
 internal override void InternalProcessRecord()
 {
     base.InternalProcessRecord();
     if (!this.sourceServerHasMdb)
     {
         base.AddSuccessMonitoringEvent(1000, Strings.TestMailflowSucceededNoDatabaseOnSourceServer(base.SourceMailboxServer.Name));
         base.Task.WriteWarning(Strings.TestMailflowServerWithoutMdbs(base.SourceMailboxServer.Name));
         return;
     }
     if (!this.targetServerHasMdb)
     {
         base.AddSuccessMonitoringEvent(1000, Strings.TestMailflowSucceededNoDatabaseOnTargetServer(base.Task.TargetMailboxServer.ToString()));
         base.Task.WriteWarning(Strings.TestMailflowServerWithoutMdbs(base.Task.TargetMailboxServer.ToString()));
         return;
     }
     using (MapiStore mapiStore = MapiStore.OpenMailbox(base.SourceMailboxServer.Fqdn, base.SourceSystemMailbox.LegacyExchangeDN, base.SourceSystemMailbox.ExchangeGuid, base.SourceSystemMailbox.Database.ObjectGuid, base.SourceSystemMailbox.Name, null, null, ConnectFlag.UseAdminPrivilege | ConnectFlag.UseSeparateConnection, OpenStoreFlag.UseAdminPrivilege | OpenStoreFlag.TakeOwnership | OpenStoreFlag.MailboxGuid, CultureInfo.InvariantCulture, null, "Client=Management;Action=LegacyTestMailFlow", null))
     {
         using (MapiFolder outboxFolder = mapiStore.GetOutboxFolder())
         {
             using (MapiFolder inboxFolder = mapiStore.GetInboxFolder())
             {
                 LegacyTestMailFlowHelper.CleanUpInbox(inboxFolder);
                 string subject = string.Format("Test-Mailflow {0} {1}", Guid.NewGuid(), "66c7004a-6860-44b2-983a-327aa3c9cfec");
                 TestMailFlowHelper.CreateAndSubmitMessage(outboxFolder, base.SourceSystemMailbox.Name, this.targetMailboxAddress, subject, true);
                 this.WaitAndProcessDeliveryReceipt(inboxFolder, subject, this.friendlySourceAddress, this.friendlyTargetAddress, this.GetPerfInstanceName());
             }
         }
     }
 }
        internal override void InternalProcessRecord()
        {
            base.InternalProcessRecord();
            if (base.Task.MonitoringContext && !this.IsFirstActiveMdbLocallyMounted())
            {
                base.AddInformationMonitoringEvent(2004, Strings.CrossPremiseServerNotSelected(base.SourceMailboxServer.Name));
                return;
            }
            List <SmtpAddress> siteEgressTargets = this.GetSiteEgressTargets();

            if (siteEgressTargets.Count <SmtpAddress>() == 0)
            {
                base.AddWarningMonitoringEvent(2003, Strings.CrossPremiseNoEgressTargets(base.SourceMailboxServer.Name));
                base.Task.WriteWarning(Strings.CrossPremiseNoEgressTargets(base.SourceMailboxServer.Name));
                return;
            }
            ADSystemMailbox adsystemMailbox = this.localSystemMailbox as ADSystemMailbox;

            using (MapiStore mapiStore = MapiStore.OpenMailbox(base.SourceMailboxServer.Fqdn, this.localSystemMailbox.LegacyExchangeDN, adsystemMailbox.ExchangeGuid, adsystemMailbox.Database.ObjectGuid, this.localSystemMailbox.Name, null, null, ConnectFlag.UseAdminPrivilege | ConnectFlag.UseSeparateConnection, OpenStoreFlag.UseAdminPrivilege | OpenStoreFlag.TakeOwnership | OpenStoreFlag.MailboxGuid, CultureInfo.InvariantCulture, null, "Client=Management;Action=CrossPremiseTestMailFlow", null))
            {
                using (MapiFolder rootFolder = mapiStore.GetRootFolder())
                {
                    using (MapiFolder inboxFolder = mapiStore.GetInboxFolder())
                    {
                        using (MapiFolder mapiFolder = rootFolder.CreateFolder("Cross Premise", "The folder for cross premise mailflow monitoring.", true))
                        {
                            if (base.Task.MonitoringContext)
                            {
                                this.MatchCrossPremiseMessages(inboxFolder, mapiFolder, this.localSystemMailbox.WindowsEmailAddress, siteEgressTargets);
                                using (List <SmtpAddress> .Enumerator enumerator = siteEgressTargets.GetEnumerator())
                                {
                                    while (enumerator.MoveNext())
                                    {
                                        SmtpAddress smtpAddress = enumerator.Current;
                                        string      subject     = string.Format("{0}{{{1}}}", "CrossPremiseMailFlowMonitoring-", Guid.NewGuid());
                                        TestMailFlowHelper.CreateAndSubmitMessage(mapiFolder, this.localSystemMailbox.Name, smtpAddress.ToString(), subject, false);
                                    }
                                    goto IL_238;
                                }
                            }
                            Dictionary <string, string> dictionary = new Dictionary <string, string>();
                            ExDateTime utcNow = ExDateTime.UtcNow;
                            foreach (SmtpAddress smtpAddress2 in siteEgressTargets)
                            {
                                string text = string.Format("{0}{{{1}}}", "CrossPremiseMailFlowMonitoring-", Guid.NewGuid());
                                TestMailFlowHelper.CreateAndSubmitMessage(mapiFolder, this.localSystemMailbox.Name, smtpAddress2.ToString(), text, true);
                                dictionary[text] = smtpAddress2.ToString();
                            }
                            this.WaitAndProcessProbeResponses(inboxFolder, this.localSystemMailbox.Name, dictionary, utcNow);
                            IL_238 :;
                        }
                    }
                }
            }
        }
        private static void CleanUpInbox(MapiFolder folder)
        {
            DateTime  t = DateTime.UtcNow.AddMinutes(-20.0);
            MapiTable contentsTable;
            MapiTable mapiTable = contentsTable = folder.GetContentsTable();

            try
            {
                mapiTable.SetColumns(new PropTag[]
                {
                    PropTag.EntryId,
                    PropTag.MessageDeliveryTime,
                    PropTag.NormalizedSubject,
                    PropTag.OriginalSubject
                });
                Restriction restriction = Restriction.Or(new Restriction[]
                {
                    Restriction.Content(PropTag.NormalizedSubject, "66c7004a-6860-44b2-983a-327aa3c9cfec", ContentFlags.SubString | ContentFlags.IgnoreCase),
                    Restriction.Content(PropTag.OriginalSubject, "66c7004a-6860-44b2-983a-327aa3c9cfec", ContentFlags.SubString | ContentFlags.IgnoreCase)
                });
                mapiTable.Restrict(restriction);
                mapiTable.SortTable(new SortOrder(PropTag.MessageDeliveryTime, SortFlags.Ascend), SortTableFlags.None);
                PropValue[][] array = mapiTable.QueryRows(100, QueryRowsFlags.None);
                List <byte[]> list  = new List <byte[]>(100);
                for (int i = 0; i <= array.GetUpperBound(0); i++)
                {
                    if (TestMailFlowHelper.IsValidPropData(array, i, 2))
                    {
                        if (array[i][1].GetDateTime() > t)
                        {
                            break;
                        }
                        list.Add(array[i][0].GetBytes());
                    }
                }
                if (list.Count > 0)
                {
                    folder.DeleteMessages(DeleteMessagesFlags.ForceHardDelete, list.ToArray());
                }
            }
            finally
            {
                if (contentsTable != null)
                {
                    ((IDisposable)contentsTable).Dispose();
                }
            }
        }
        private MapiMessage WaitForDeliveryReceipt(MapiFolder folder, string subject, int errorLatency, int timeoutSeconds, string sourceAddress, string targetAddress)
        {
            bool        flag        = false;
            MapiMessage mapiMessage = null;

            for (int i = 0; i < timeoutSeconds; i++)
            {
                mapiMessage = TestMailFlowHelper.GetDeliveryReceipt(folder, subject, true);
                if (mapiMessage != null)
                {
                    break;
                }
                Thread.Sleep(1000);
                if (!flag && i >= errorLatency)
                {
                    flag = true;
                    base.AddErrorMonitoringEvent(1002, Strings.TestMailflowError(sourceAddress, targetAddress, errorLatency));
                }
            }
            return(mapiMessage);
        }
 private void MatchCrossPremiseMessages(MapiFolder responseFolder, MapiFolder probeFolder, SmtpAddress source, List <SmtpAddress> targets)
 {
     using (MapiTable contentsTable = responseFolder.GetContentsTable())
     {
         using (MapiTable contentsTable2 = probeFolder.GetContentsTable())
         {
             contentsTable.SetColumns(new PropTag[]
             {
                 PropTag.EntryId,
                 PropTag.Subject,
                 PropTag.ClientSubmitTime
             });
             contentsTable2.SetColumns(new PropTag[]
             {
                 PropTag.EntryId,
                 PropTag.Subject,
                 PropTag.ClientSubmitTime
             });
             PropValue[][] array  = contentsTable.QueryRows(1000, QueryRowsFlags.None);
             PropValue[][] array2 = contentsTable2.QueryRows(1000, QueryRowsFlags.None);
             List <byte[]> list   = new List <byte[]>();
             List <byte[]> list2  = new List <byte[]>();
             Dictionary <SmtpAddress, CrossPremiseTestMailFlowHelper.HealthData> dictionary = new Dictionary <SmtpAddress, CrossPremiseTestMailFlowHelper.HealthData>(targets.Count);
             for (int i = 0; i <= array2.GetUpperBound(0); i++)
             {
                 if (TestMailFlowHelper.IsValidPropData(array2, i, 3))
                 {
                     string text = (string)array2[i][1].Value;
                     if (text.StartsWith("CrossPremiseMailFlowMonitoring-", StringComparison.OrdinalIgnoreCase))
                     {
                         byte[] bytes = array2[i][0].GetBytes();
                         using (MapiMessage mapiMessage = (MapiMessage)probeFolder.OpenEntry(bytes))
                         {
                             SmtpAddress key = SmtpAddress.Parse((string)mapiMessage.GetProp(PropTag.ReceivedByEmailAddress).Value);
                             if (!dictionary.ContainsKey(key))
                             {
                                 dictionary.Add(key, new CrossPremiseTestMailFlowHelper.HealthData(EnhancedTimeSpan.Zero, EnhancedTimeSpan.Zero, 0, 0, 0, 0));
                             }
                             ExDateTime exDateTime = (ExDateTime)array2[i][2].GetDateTime();
                             if (exDateTime.Add(base.Task.CrossPremisesExpirationTimeout) < ExDateTime.UtcNow)
                             {
                                 dictionary[key].ExpiredNumber++;
                                 list.Add(bytes);
                             }
                             else
                             {
                                 for (int j = 0; j <= array.GetUpperBound(0); j++)
                                 {
                                     if (TestMailFlowHelper.IsValidPropData(array, j, 3))
                                     {
                                         string text2 = (string)array[j][1].Value;
                                         if (text2.EndsWith(text, StringComparison.OrdinalIgnoreCase))
                                         {
                                             byte[] bytes2 = array[j][0].GetBytes();
                                             if (((ExDateTime)array[j][2].GetDateTime()).Add(base.Task.CrossPremisesExpirationTimeout) < ExDateTime.UtcNow)
                                             {
                                                 list2.Add(bytes2);
                                             }
                                             else
                                             {
                                                 using (MapiMessage mapiMessage2 = (MapiMessage)responseFolder.OpenEntry(bytes2))
                                                 {
                                                     EnhancedTimeSpan t;
                                                     EnhancedTimeSpan t2;
                                                     if (this.ProcessCrossPremiseMessagePair(mapiMessage, mapiMessage2, source.ToString(), key.ToString(), out t, out t2))
                                                     {
                                                         dictionary[key].ProbeLatency    += t;
                                                         dictionary[key].ResponseLatency += t2;
                                                         dictionary[key].SuccessNumber++;
                                                     }
                                                     else
                                                     {
                                                         dictionary[key].FailedNumber++;
                                                     }
                                                 }
                                                 list2.Add(bytes2);
                                                 list.Add(bytes);
                                             }
                                         }
                                     }
                                 }
                                 if (!list.Contains(bytes) && exDateTime.AddMinutes(10.0) < ExDateTime.UtcNow)
                                 {
                                     dictionary[key].PendingNumber++;
                                 }
                             }
                         }
                     }
                 }
             }
             this.SaveHealthData(source, dictionary);
             if (list2.Count > 0)
             {
                 responseFolder.DeleteMessages(DeleteMessagesFlags.ForceHardDelete, list2.ToArray());
             }
             if (list.Count > 0)
             {
                 probeFolder.DeleteMessages(DeleteMessagesFlags.ForceHardDelete, list.ToArray());
             }
         }
     }
 }