News Stay informed about the latest enterprise technology news and product updates.

An asynchronous message queuing example with .NET

Wondering how Visual Basic .NET handles sending and receiving messages compared to VB6? Roy Hoobler says although the .NET classes are in a new "messaging" assembly that is easy to navigate and understand, the classes themselves are not much different than their older COM component counterparts. This article shows how to create a queue, send a test message, and automatically receive messages.

Roy Hoobler has been involved with Internet programming from 1995 and developing Web businesses and "niche" market sites since 1996. In 1997, he completed his MCSD certification and worked for a large consulting firm primarily focusing on Intranet and Extranet applications for fortune 1000 companies. In early 1998, seeing the potential of how business would be conducted on the Internet, Roy joined [email protected] Inc. ( where he designs (and still codes) business and cutting-edge e-commerce applications using a wide range of technologies, including XML.

Roy is the moderator of our Enterprise Developer Forum. So be sure to .xJN4aAKSfbb^[email protected]!viewtype=&skip=&expand=>post a question for Roy or read Roy's other articles on SearchWebServices.

.NET Info Center
Click Here
To get the latest Visual Studio .NET information directly from Microsoft.

* .NET Tips

* .NET Advice

* .NET News

* .NET Resources

.NET Development
An asynchronous message queuing example with .NET

Working on a couple of applications using Visual Basic 6.0 and message queuing made me curious to see how Visual Basic .NET would handle sending and receiving messages. I was also hoping that using .NET programming would be more straightforward and easier to implement than VB6. Although the .NET classes are in a new "messaging" assembly that is easy to navigate and understand, the classes themselves are not much different than their older COM component counterparts. This article shows how to create a queue, send a test message, and automatically receive messages.

The System.Messaging and System.Threading assemblies need to be referenced in the Visual Studio .NET project. The main difference between VB 6.0 and Visual Basic .NET is the use of a "handler" and a "callback" method for doing asynchronous receiving. The class and module files need to import System.Messaging. Some functionality is handled in the background and you may think the receiveCallBack module doesn't reference Messaging when in fact, it does (the XmlMessageFormatter object is a Messaging component). Microsoft Message Queuing also needs to be installed on the developer's machine for the program to execute. To install, go to control panel, click add/remove software and then select Window's Components.

The code to check and create a message queue on the local machine in Visual Basic .NET is almost the same as VB 6.0. To send a test message, I created a form with one button and two text boxes. The first text box is the message text and the second is the name of the queue where message will be sent (my queue is ".PRIVATE$ROY"). The "StartReceive" call in the form1_load routine starts the application listening for messages immediately. The code for the form is in Listing 1.

[Listing 1]

Public Class Form1
  Inherits System.Windows.Forms.Form
  Private oMC As New MessageClass.MessageClass()

  Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
    oMC.sendTestMessage(me.txtQueName.text, me.txtMessage.text)
  End Sub

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

  End Sub
End Class

Next, I created a VB Class called MessageClass. This class has two methods, one to send a test message and another to receive messages from the queue. The method sendTestMessage, first checks to see if the queue exists. If it doesn't, a queue is created and the message is sent to the queue (Listing 2). Notice the use of "Try" and "Catch" which are also new to Visual Studio .NET.

[Listing 2]

Imports System.Messaging
Imports System.Threading
Public Class MessageClass

  Function sendTestMessage(sQue as String, sMessage as String) As Messaging.Message
    Dim oQue As New Messaging.MessageQueue()
    Dim oMessage As New Messaging.Message()
    oQue.MachineName = "ibm-laptop"
    If Not oQue.Exists(sQue) Then
        oQue = oQue.Create(sQue)
      Catch e1 As Messaging.MessageQueueException
      End Try
      oQue.QueueName = sQue.replace(".","")
    End If
      oMessage.Body = sMessage
    Catch e As Messaging.MessageQueueException
    End Try
  End Function

... Continued in Listing 4

After sending the message, you can check the queue to see if the message has been received by opening Computer Manager and selecting Message Queue. If it was not properly sent, the message might be in the "outgoing" queue on the sending machine. If it was sent successfully, the message will be in the queue with the given name on the local machine. In this example, viewing the "outgoing" queue is difficult because we are sending to the local machine. However, by commenting out the startReceive() call in the Form Load routine, you can easily see the received message waiting in the queue (Figure 1). Messages can also be purged from the queue using the Computer Manager application.

A little trickier to implement is asynchronous receiving. To start programming this functionality, a Call Back function is needed. I was surprised that using Call Back functions in Visual Studio .NET is very similar to the way Call Backs worked in VB 6.0. However, they were generally not used for Message Queuing with VB 6.0 because you instantiated the queue "with events." The functionality of receiving the message is placed in a Visual Basic code module (Listing 3). For now, the received message is just being written to the console (debug) window. Further processing (storing the message in the database or parsing XML text) takes place in the OnReceiveCompleted subroutine.

[Listing 3]

Imports System.Messaging
Imports System.Threading
Module receiveCallBack
  Public Sub OnReceiveCompleted(ByVal source As Object, ByVal asyncResult As ReceiveCompletedEventArgs)
    Dim mq As MessageQueue = CType(source, MessageQueue)
    Dim m As Message = mq.EndReceive(asyncResult.AsyncResult)
      m.Formatter = New XmlMessageFormatter(New String() {"System.String, mscorlib"})
      Console.WriteLine("Message: {0}", CStr(m.Body))
  End Sub

End Module

After setting up the Call Back function, the "startReceive" method of the MessageClass (listing 4) prepares the application for receiving messages. Near the end of this function, a "handler" is added to the class that intercepts the message queue event. The handler will call the OnReceiveCompleted function (listing 3) to process the event. After processing the message, the mq.BeginReceive() method is invoked again to continue listening.

[Listing 4]

 Public Function StartReceive()
    Dim appName As String = Environment.GetCommandLineArgs()(0)
    Dim mqPath As String '= "." + Environment.GetCommandLineArgs()(1)
    mqPath = ".PRIVATE$roy"
    If (Not MessageQueue.Exists(mqPath)) Then
    Console.WriteLine("The queue '{0}' does not exist!", mqPath)
    Dim mq As MessageQueue = New MessageQueue(mqPath)
    Dim formatter As XmlMessageFormatter = CType(mq.Formatter, XmlMessageFormatter)
    formatter.TargetTypeNames = New String() {"System.String,mscorlib"}
    AddHandler mq.ReceiveCompleted, AddressOf OnReceiveCompleted
  End If
 End Function
End Class

The above examples cover the basics of sending and receiving messages with Visual Basic .NET. Other methods allow a developer to manage queues as well as check (peek) for messages in the queue. I hope the above examples help programmers who need to get a good start sending and receiving messages, as well as give some thought about how to build applications around MS Message Queue.

For More Information:

  • Visit the SearchVB .NET Info Center for the latest .NET tips, expert advice, news and resources.
  • Looking for free research? Browse our comprehensive White Papers section by topic, author or keyword.
  • Are you tired of technospeak? The Web Services Advisor column uses plain talk and avoids the hype.
  • For insightful opinion and commentary from today's industry leaders, read our Guest Commentary columns.
  • Hey Codeheads! Start benefiting from these time-saving XML Developer Tips and .NET Developer Tips.

  • Visit our huge Best Web Links for Web Services collection for the freshest editor-selected resources.
  • Visit Ask the Experts for answers to your Web services, SOAP, WSDL, XML, .NET, Java and EAI questions.
  • Discuss this article, voice your opinion or talk with your peers in the SearchWebServices Discussion Forums.

Dig Deeper on Topics Archive