Search code examples
c#.netsql-servermsmq

How to update message before it's delivered


I am queuing a bunch of messages, and the queue eventually delivers the messages as records into a sql server database. I need to update the message to display the datetime at which the message is going to be delivered. As I am thinking about this, my request does not sound logical; however, is there a way or is there an event to which I can subscribe to get the datetime right before the message is delivered?

var msgQ = new MessageQueue(_myque);
msgTx.Begin();
msgQ.Send(message, msgTx);
msgTx.Commit();

Please note that I am unable to make any changes to the database, and would need to solve this through .NET code. 


Solution

  • This following sample will push a message onto a message queue, and then receive it after a small delay:

    First, a message to send:

    public class Order
    {
        public int orderId;
        public DateTime orderDate;
        public DateTime receivedDate;
    };
    

    Send the a new Order, wait a little, and then receive it from the queue:

    // a private queue - set to applicable queue path.
    var myQueue = new MessageQueue(".\\private$\\myQueue");
    
    myQueue.Send(new Order { orderId = 1, orderDate = DateTime.Now});
    
    // a 10 second delay to demonstrate an infrastructure 
    // delay between the send and receive   
    Thread.Sleep(new TimeSpan(0, 0, 10));
    
    var message = myQueue.Receive();
    
    var receivedOrder = (Order)message.Body;
    receivedOrder.receivedDate = DateTime.Now;  
    
    Console.WriteLine(string.Format("Order {0} sent at {1}, received at {2}", receivedOrder.orderId, receivedOrder.orderDate, receivedOrder.receivedDate));