I want to take message from one queue and send it to database. I want to do it only if it's in specific format.
If i use Receive
method directly and some exception occurs while accessing Body
of the Message, I lose the message since Receive
method of the MessageQueue
removes the message from the queue.
To avoid loss of message, now i first Peek
the message, and if its well formatted, I use Receive
method to remove it from the queue to send it to database.
Code I have written is like this:
Message msg = _queue.Peek(new TimeSpan(0, 0, LoggingService.Configuration.ReceiveTimeout));
// LogMessage is my own class which is adding some more stuff to original message from MessageQueue
LogMessage message = null;
if (msg != null)
{
if (!(msg.Formatter is BinaryMessageFormatter))
msg.Formatter = new BinaryMessageFormatter();
message = LogMessage.GetLogMessageFromFormattedString((string) msg.Body);
// Use Receive method to remove the message from queue. This line will we executed only if the above line does not
// throw any exception i.e. if msg.Body does not have any problem
Message wellFormattedMsg =
_queue.ReceiveById(msg.Id);
SendMessageToDatabase(message);
}
Is this logic right to first using Peek and then Receive? Or is there any other better way f achieving the same thing? Please note that I dont want to get all messages at a time. MessageQueue is non transactional.