Question

I'm investigating using MSMQ for my team's new project but I need to know if I can send MSMQ messages and execute SQL commands within a System.Transactions.TransactionScope and have them commit or rollback together. I can't find a reliable source online that says "yes" with code examples.

I need to send some messages to a single queue and insert some records in a single database, but I need to to succeed or fail together.

EDIT: I was not able to actually verify whether this works or not in my testing (I was pulled off this task quickly) but all the documentation states that TransactionScope does capture MSMQ messages and SQL commands in the same instance.

Was it helpful?

Solution

From personal experience I know the TransactionScope works great with SQL. I'm not too familiar with MSMQ but a quick Google search shows some examples (normally forum discussions) where it looks like it's working successfully. The System.Messaging.MessageQueue object also has a .Transactional property and the .Send() method has a MessageQueueTransaction parameter so I'd say it should all work together.

Here's the code example from one of the forums in the search (not my code):

using (TransactionScope scope = new TransactionScope())  
{  
    using (MessageQueue myQueue = new MessageQueue(QUEUE_NAME))  
    {  
    if (myQueue.Transactional)  
        {  
        myQueue.Send(TicketTextBox.Text, "Message", MessageQueueTransactionType.Automatic);  
        }  
    }  
scope.Complete();  
}

Just throw your SQL code inside the using() block for the TransactionScope (before the .Complete()) and you should be good to go?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top