If any one line of code makes up the heart of this application, this is it.
mq.Formatter = new XmlMessageFormatter(
typeof( System.String ) ,
typeof( System.Data.DataSet )
} ) ;
We use the XmlMessageFormatter object, and as part of it's parameters, we assign an array of Types. It is very important to note that you need to fully qualify the types because they cannot access the imports/using statements in your file. Create one for each object or data type that you expect to use in receiving from a queue. You can use your own types, which is very handy for storing and retrieving your own custom objects.
Next is the act of determining the type of the object that has been received, so you can properly cast the object.
if ( message.Body.GetType().ToString() == "System.Data.DataSet" )
dataSet = (DataSet)message.Body ;
Success = true ;
if ( message.Body.GetType().ToString() == "System.String" )
rString = (string)message.Body ;
Success = true ;
In section 1) you see that we test to determine if the type is a DataSet, and if so, we cast the message body into a DataSet object and we are done. Pass it on to its destination and continue processing. In section 2), the same is true for the string type. This can be used with custom objects and other tests can be done as well.
Finally, notice the TimeSpan component in the following code, also found in the MessagePeek method.
message = mq.PeekById( msgid , new TimeSpan( 0, 0, 1 ) ) ;
I will not go deep into the details, but if your object does not exist, you can have your caller wait a specified amount of time before it returns an error. Combine this with asynchronous calls, and you can now wait for an object to become available and process it.
I hope you have found this example application useful. The push today is to move away from batch processing, but this is not always practical, nor is always the best option.