SQL Service Broker Part 2: Working with .NET

In Part 1, we covered the basic mechanics of sending and receiving a message. In Part 2, we will cover writing and consuming messages with the .NET framework. This will build on the message types, contracts, queues, services, and stored procedures that we created in Part 1. If you haven’t read that, I recommend that you do so.

Reading and writing with .NET is a fairly simple task. Let’s take a look at how to do this. First, we will start a background thread to listen for received messages. Second, we will allow a simple text entry for a user to send messages.

There’s a lot more going on in the receiver. Let’s break it down. First, we open up a TransactionScope, SqlConnection, and SqlCommand. These are going to be our primary objects for receiving a message from a queue. Second, we remember that the text variable in our stored procedure is marked at OUT, so we need to designate that as such in our code. Third, close the connection and complete the scope. Finally, display a message box containing the message.

And that’s it! We can now write .NET programs (or any programs that can call stored procedures) to work with our queues.