ActiveMQ via C# using Apache.NMS Part 1

by jmorris 12. July 2010 18:17

ActiveMQ via C# using Apache.NMS Part 1

Java Message Service (JMS) is the de facto standard for asynchronous messaging between loosely coupled, distributed applications. Per the specification, it provides a common way for Java application to create, send, receive and read messages. This is great for enterprises or organizations whose architecture depends upon a single platform (Java), but the reality is that most organizations have hi-bred architectures consisting of Java and .NET (and others). Oftentimes these systems need to communicate using common messaging schematics: ActiveMQ and Apache.NMS satisfy this integration requirement.

JMS Primer
The JMS specification outlines the requirements for system communication between Java Messaging Middleware and the clients that use them. Products that implement the JMS specification do so by developing a provider that supports the set of JMS interfaces and messaging semantics. Examples of JMS providers include open source offerings such as ActiveMQ, HornetQ and GlassFish and proprietary offerings such as SonicMQ and WebSphere MQ. The specification simply makes it easier for third parties to develop providers.

All messaging in JMS is peer-2-peer; clients are either JMS or non JMS applications that send and receive messages via a provider. JMS applications are pure Java based applications whereas non JMS use JMS styled APIs such as ActiveMQ.NMS which uses OpenWire, a cross language wire protocol that allows native access to the ActiveMQ provider.

JMS messaging schematics are defined into two separate domains: queue based and topic based applications. Queue based or more formally, point-to-point (PTP) clients rely on “senders” sending messages to specific queues and “receivers” registering as listeners to the queue. In scenarios where more a queue has more than one listener, the messages are delivered in a round-robin fashion between each listener; only one copy of the message is delivered. Think of this as something like a phone call between you and another person.

Topic based application follow the publish/subscribe metaphor in which (in most cases) a single publisher client publishes a message to a topic and all subscribers to that topic receive a copy. This type of messaging metaphor is often referred to as broadcast messaging because a single client sends messages to all client subscribers. This is some analogous to a TV station broadcasting a television show to you and any other people who wish to “subscribe” to a specific channel.

JMS API Basics
The JMS Standard defines a series of interfaces that client applications and providers use to send messages and receive messages. From a client perspective, this makes learning the various JMS implementations relatively easy, since once you learn one you can apply what you learned to another implementation relatively easily and NMS is no exception. The core components of JMS are as follows: ConnectionFactory, Connection, Destination, Session, MessageProducer, and MessageConsumer. The following diagram illustrates communication and creational aspects of each object:

NMS supplies similar interfaces to the .NET world which allows for clients to send messages to and from the ActiveMQ JMS via OpenWire. A quick rundown of the NMS interfaces are as follows:

Note that the Apache.NMS namespace contains several more interfaces and classes, but these are the essential interfaces that map to the JMS specification. The following diagram illustrates the signature that each interface provides:

The interfaces above are all part of the Apache.NMS 1.30 API available for download here. In order to use NMS in your .NET code you also need to down load the Apache.NMS.ActiveMQ client as well and to test your code, you will need to download and install the ActiveMQ broker, which is written in Java so it requires the JRE to be installed as well. The following table provides links to each download:

For my examples I will be using the latest release of Apache.NMS and Apache.NMS.ActiveMQ as of this writing time. You should simple pick the latest version that is stable. The same applies for ActiveMQ and the JDK/JRE…note that you only need the Java Runtime Environment (JRE) to host install ActiveMQ. Install the JDK if you want to take advantage of some the tools that it offers for working with JMS providers.

To start ActiveMQ, install the JRE (if you do not already have it installed – most people do already) and unzip the ActiveMQ release into a directory…in directory will do. Open a command prompt and navigate to the folder with the ActiveMQ release and locate the “bin” folder, then type ‘activemq”. You should see something like the following:

Download and install the Apache.NMS and Apache.NMS.ActiveMQ libraries from the links defined in the table above. Unzip them into a directory on your hard drive, so that you can reference them from Visual Studio.

Open Visual Studio 2008/2010 and create a new Windows project of type “Class Library”:

And once the project is created, using the “Add Reference” dialog, browse to the directory where you unzipped the Apache.NMS files defined above and a reference to the Apache.NMS.dll. Do the same for the Apache.NMS.ActiveMQ download. Note that each download contains builds for several different .NET versions; I chose the “net-3.5” version of each dll since I am using VS 2008 and targeting the 3.5 version of .NET.

For my examples you will also need to install the latest and greatest version NUnit from After you have installed NUnit, add a reference to the nunit.framework.dll. Note that any unit testing framework should work.

Add three classes to the project:

  1. A test harness class (ApacheNMSActiveMQTests.cs)
  2. A publisher class (TopicPublisher.cs) 
  3. A subscriber class (TopicSubscriber.cs).

Your solution explorer should look something like the following:

The test harness will be used to demonstrate the use of the two other classes. The TopicPublisher class represents a container for a message producer and the TopicSubcriber represents a container for a message consumer.

The Publisher
The publisher, TopicPublisher is a simple container/wrapper class that allows a client to easily send messages to a topic. Remember from my previous discussion about topics that topics allow for broadcast messaging scenarios: a single publisher sends a message to one or more subscribers and that all subscribers will receive a copy of the message.

Message producers typically have a lifetime equal to the amount of time it takes to send a message, however for performance reasons you can extend the life out to the length of the application’s lifetime.

The Subscriber
Like the TopicPublisher above, the TopicSubscriber class is container/wrapper class that allows clients to “listen in” or “subscribe” to a topic.

The TopicSubscriber class is typically has a lifetime that is the equal to the lifetime of the application. The reason is pretty obvious: a publisher always knows when it will publish, but a subscriber never knows when the publisher will send the message. What the subscriber does is create a permanent “listener” to the topic, when a publisher sends a message to the topic, the subscriber will receive and process the message.

Usage Example
The following unit test shows the classes above used in conjunction with the Apache.NMS and Apache.NMS.ActiveMQ API’s to send and receive messages to ActiveMQ which is Java based, from the .NET world!

Here is quick rundown of the ApachNMSActiveMQTests class:

  1. Declare variables for the required NMS objects and the TopicSubscriber
  2. Declare variables for  the broker URI, the topic to subscribe/publish to, and the client and consumer ids
  3. Create a ConnectionFactory object, create and start a Connection, and then create a Session to work with.
  4. Create and start the TopicSubscriber which will be a listener/subscriber to the “TestTopic” topic. Also, to receive messages you must register an event handler or lambda expression with the MessageReceivedDelegate delegate. In this example I in-lined a lambda expression for simplicity.
  5. On the test the method, create a temporary publisher and send a message to the topic.
  6. Tear down and dispose of the subscriber and Session.
  7. Tear down and dispose of the Connection.

After you run the unit test you should see something like the following message:

Note that ActiveMQ must be up and running for the example to work.


kick it on

Tags: , , , ,

Apache.NMS | JMS

Comments (16) -

Bob Tierney
Bob Tierney United States
7/15/2010 9:03:26 AM #

This example works fine and I'm having success sending a text message from C# to ActiveMQ. In turn I'm receiving the message on a Java client. Great! Now I want to send an object and ultimately an array of objects. For now I have a simple "stock" object (name, symbol, high, low, volume).
Stock stock = new Stock();
stock.Name = "International Business Machines";
stock.Symbol = "IBM";
stock.high = 167.55m;
stock.low = 144.55m;
stock.volume = 12345;
IObjectMessage omsg = prod.CreateObjectMessage(stock);
prod.Send(omsg, MsgDeliveryMode.NonPersistent, MsgPriority.High, TimeSpan.MinValue);

The message is sent and I do recieve it on the java client, however the body is null. I am wondering if you or anyone have any suggestions.

Regards ...

jmorris United States
7/15/2010 1:13:47 PM #

@Bob - object serialization between java and C# is kind of tough. I know using xml serialization will work, because you are sending a blob of xml as a string across the wire and it's easy for the serialization process on either side to map the elements to properties on the C# and setters on the Java side. Well, in truth C# is using setters and getters to, but that is beside the point.

Try using xml serialization on both sides and make sure that the objects you are working on are symmetric equivalents. I'll see if I can come up with an example to illustrate.


Bob Tierney
Bob Tierney United States
7/20/2010 7:58:26 AM #

@Jeff - thanks for your response. Unfortunately my reason for looking at ActiveMQ was to avoid XML. The data set I was hoping to send is quite large (several thousand rows). It's going to be broadcast every 500ms or so. I don't think adding XML marshalling to both sides will scale for my needs.

I appreciate your suggestion nevertheless .... it may be my only choice since I refuse to spend the time building a JNI layer. I'm pretty sure that I'm either too lazy or not that bright for that effort. Possibly both Wink


kapil India
7/23/2010 1:04:04 AM #


I am able to publish the messages from my dot net application on the server using BROKER.But the application on another not able receiving it..but when i try to subsribe the same i am geeting..can anybody help..??

jmorris United States
8/27/2010 9:30:19 AM #

I would need more details to help you...

An Phu
An Phu United States
3/12/2011 4:46:27 AM #

The best post so far I seen on NMS.

There is a minor problem with the TopicSubscriber.  There is no MessageReceivedDelegate.  But no fret, copying that delegate declaration from Re.mark's post solves the problem. ;)

public delegate void MessageReceivedDelegate(string message);

jeff United States
3/12/2011 2:39:32 PM #

Thanks for the compliment Smile

Yeah, I never updated the screenshots, but the final product contains the delegate declaration and a lot of refactoring...

Note there are a few other small "issues" with code. For example there are is no finalizer on the subscriber, so  if the GC collects an instance and Dispose() is never called, you will find yourself with "orphaned" sockets.

Ilya Israel
6/22/2011 7:05:33 AM #

Thanks for your post, it was really helpful for me.
I'm a bit confused with your use of "using" keyword in the usage example  part, I think TopicPublisher class have to implement System.IDisposable interface to be in inside using clauses. You did implemented Dispose() method, so I just changed the code to :

public class Publisher:IDisposable {

jmorris United States
6/23/2011 9:17:10 PM #

@Ilya - yeah, accidentally omitted the IDisposable in the screen shots. For the record, I am using public class Publisher:IDisposable { ..}

Thanks, for reading Smile

Gyan India
8/11/2011 10:49:48 PM #

Hi @ jeff, i need to send the Xml file from my application to ActiveMQ queue.Please help me and how can i achieve this.


sukh United States
11/25/2011 1:16:36 PM #

Hi, I have referenced Apache.NMS.dll and Apache.NMS.ActiveMQ.dll. Issue I am facing is, not able to see the ActiveMQQueue class to initilize the queue.

for example IQueue q= new ActiveMqQueue(destination)

I can't see the ActiveMQQueue class populated in code.

Please advice, if I am missing something.


Harshita India
11/28/2011 9:19:04 PM #

Is there some way to send Java object as a message from C# to ActiveMq?
Actually the scenario is like this:
1) Message will be produced from C# and message will be in the form java object
2) Message will be consumed by Java code.....

suk United States
12/1/2011 7:23:50 AM #

You can utilize IObjectMessage interface and create the object of class and send it to queue.

such as Name name= new name();
IObjectMessage msg= Class.CreateObject(name);

suk United States
12/1/2011 7:19:10 AM #

I am trying to connect to activeMQ using c# windows application, I am getting the below error.

The referenced assembly "Apache.NMS.ActiveMQ" could not be resolved because it has a dependency on "System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.

Can't I connect to activeMQ using window application(c#). I have tried the same for Web app, its works fine but not on windows app.

Any suggestions.


suk United States
1/26/2012 6:51:19 AM #

Hi Guys,

when writing message to ActiveMQ, why its been serialized. Why can't I put a simple message as read.

Example: {abc123}

When I see message on Queue it as format as <XML><String>{abc123}</String> instead of simple text.

What I am missing, Please comment.

following is code for it

    _session = _connection.CreateSession();
                                   destination = _session.GetDestination("QueueName");
                                 consumer = _session.CreateConsumer(destination);
                                producer = _session.CreateProducer(destination);
original_Swift_Message = DataGridView_MT.SelectedRows[i].Cells["ColName"].Value.ToString();
                            producer.send(original_Swift_Message );


suk United States
1/26/2012 7:25:38 AM #

Thanks much, I got solution. I need to convert message into ItextMessage instance and then send it to queue.

Pingbacks and trackbacks (2)+

Jeff Morris

Tag cloud

Month List

Page List