public void TestReceiveBrowseReceive()
{
using (IConnection connection = CreateConnection())
{
using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
{
IDestination destination = session.GetQueue("TestReceiveBrowseReceive");
IMessageProducer producer = session.CreateProducer(destination);
IMessageConsumer consumer = session.CreateConsumer(destination);
connection.Start();
IMessage[] outbound = new IMessage[]{session.CreateTextMessage("First Message"),
session.CreateTextMessage("Second Message"),
session.CreateTextMessage("Third Message")};
// lets consume any outstanding messages from previous test runs
while (consumer.Receive(TimeSpan.FromMilliseconds(1000)) != null)
{
}
producer.Send(outbound[0]);
producer.Send(outbound[1]);
producer.Send(outbound[2]);
IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000));
// Get the first.
Assert.AreEqual(((ITextMessage)outbound[0]).Text, ((ITextMessage)msg).Text);
consumer.Close();
IQueueBrowser browser = session.CreateBrowser((IQueue)destination);
IEnumerator enumeration = browser.GetEnumerator();
// browse the second
Assert.IsTrue(enumeration.MoveNext(), "should have received the second message");
Assert.AreEqual(((ITextMessage)outbound[1]).Text, ((ITextMessage)enumeration.Current).Text);
// browse the third.
Assert.IsTrue(enumeration.MoveNext(), "Should have received the third message");
Assert.AreEqual(((ITextMessage)outbound[2]).Text, ((ITextMessage)enumeration.Current).Text);
// There should be no more.
bool tooMany = false;
while (enumeration.MoveNext())
{
Debug.WriteLine("Got extra message: " + ((ITextMessage)enumeration.Current).Text);
tooMany = true;
}
Assert.IsFalse(tooMany);
//Reset should take us back to the start.
enumeration.Reset();
// browse the second
Assert.IsTrue(enumeration.MoveNext(), "should have received the second message");
Assert.AreEqual(((ITextMessage)outbound[1]).Text, ((ITextMessage)enumeration.Current).Text);
// browse the third.
Assert.IsTrue(enumeration.MoveNext(), "Should have received the third message");
Assert.AreEqual(((ITextMessage)outbound[2]).Text, ((ITextMessage)enumeration.Current).Text);
// There should be no more.
tooMany = false;
while (enumeration.MoveNext())
{
Debug.WriteLine("Got extra message: " + ((ITextMessage)enumeration.Current).Text);
tooMany = true;
}
Assert.IsFalse(tooMany);
browser.Close();
// Re-open the consumer.
consumer = session.CreateConsumer(destination);
// Receive the second.
Assert.AreEqual(((ITextMessage)outbound[1]).Text, ((ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000))).Text);
// Receive the third.
Assert.AreEqual(((ITextMessage)outbound[2]).Text, ((ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000))).Text);
consumer.Close();
}
}
}