Monday, December 20, 2004

Microsoft Message Queue Trigger with VB.NET

Last week, including the weekend and today, I’ve been working with (or as I prefer, TRYING to work with) Message Queues and .NET.
The scenario is this. I have different web applications and needed a way for them to communicate with each other “backstage”, so I thought about Microsoft Message Queues.
I didn’t want to write a service to monitor the queue, because that’s something that’s provided by the MSMQ service itself so it makes no sense to replicate such functionality. After much trial and error and hitting the computer desk, and complaining about the lack of information about this on the Internet, I finally made my triggers work. Here is a small tutorial for anyone that wants to do this (and also for when I forget how the heck I did it).

Create the .NET Assembly
Create a COM Class
Sign the assembly with a strong key
Register the assembly in the Global Assembly Cache (GAC)
Register the trigger rule
Register the Trigger
Test the thing!!!!

The first step was to create a .NET assembly. This assembly needs three special things.
It needs to have a COM CLASS
It needs to have ‘Register for COM Interop” checked in the Configuration Build dialog.
It needs to have a strong name (signed with a key)

So, create a new Class Library project, add a COM Class and code your class.
Create a key with the sn.exe utility (from the Visual Studio Command Prompt) with the –k option to generate a new key and specify the key name. After doing this, place the .snk file in the project folder, and add the following to the AssemblyInfo.vb in your Class Library.

<Assembly: AssemblyDelaySign(False)>
<Assembly: AssemblyKeyName("")>
<Assembly: AssemblyKeyFile("..\..\\yourkeyfilename.snk")>

Compile your class, and use the following to register in the Global Assembly Cache:
regasm dllname.dll
gacutil /if dllname.dll


To unregister this class from the GAC (If you need to), use the following syntax::
regasm -u dllname.dll
gacutil -uf dllname


After doing this, your class library is visible to COM clients (you can test this by calling your component from traditional ASP or VB 6).

When you create the MSMQ Trigger, keep in mind that in Windows 2000 the only action for a message is Peeking, so you’ll have to delete the message from the queue manually in your code. In Windows 2003 and XP you can specify a “Retrieval’ action, so the trigger automatically deletes the message.

Register the class and method name in the trigger definition dialog and test!!

No comments: