johnllao

October 15, 2010

Simple NServiceBus Sample

Filed under: Uncategorized — johnllao @ 12:57 pm

I have been exploring Service Bus in the past few days as I am very well impressed how reliable messaging is being handled. the first challenge that I encounter is being able to create a simple application that demontrate how it works.

I have seen the NServiceBus and MassTransit examples from their respective sites however I find the sample pretty difficult to digest. So after few hours of exploring I came up wih a simple example to make things work.

In this post I will show how a simple Publish and Subscribe messages work with NServiceBus. I have created a simple WPF window application that hosts the NServiceBus service in itself.

First let us start with the configuration.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
  </configSections>

  <!-- in order to configure remote endpoints use the format:
       "queue@machine" 
  -->

  <MsmqTransportConfig
    InputQueue="IonInputQueue"
    ErrorQueue="IonErrorQueue"
    NumberOfWorkerThreads="5"
    MaxRetries="5"
  />

  <UnicastBusConfig>
    <MessageEndpointMappings>
      <add Messages="IonMessages" Endpoint="IonInputQueue" />
    </MessageEndpointMappings>
  </UnicastBusConfig>

</configuration>

The MsmqTransportConfig tells the name of the queue (e.g. MSMQ) that NServiceBus will use to publish and subscribe.

The UnicastBusConfig tells about the message endpoints you will be used to send messages. So what does that mean? It simple tells what type of Messages you want to send. Messages in NServiceBus are simply classes you create. The Messages attribute in the config tells the Assembly where you can find the Messages class.

So how do we create a Message, in NServiceBus you simply create a class that implements the IMessage interface. Here are the examples.

using NServiceBus;
using System;

namespace Ion.Messages
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class RequestMessage : IMessage
    {
        public Guid MessageId;
        public string Name;
    }
}

using NServiceBus;
using System;

namespace Ion.Messages
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class ResponseMessage : IMessage
    {
        public Guid MessageId;
        public Guid RequestMessageId;
        public string Status;
    }
}

Now we have the messages classes, next I will show you how to Publish and Subscribe to these messages. but before we go into that, we need to make the NServiceBus running, meaning listening and executing the messages that arrives in our queue. Here is the code that do that.

using Ion.Messages;
using NServiceBus;
using NServiceBus.Config;
using System;
using System.Windows;

namespace Ion.Windows.UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static IBus Bus;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Bus = Configure.With().DefaultBuilder().BinarySerializer()
                .MsmqTransport().IsTransactional(true).PurgeOnStartup(false)
                //.MsmqSubscriptionStorage()
                .UnicastBus().ImpersonateSender(false).LoadMessageHandlers()
                .CreateBus()
                .Start();
        }
    }
}

The following code shows how to publish / subscribe to a message.

using Ion.Messages;
using NServiceBus;
using System;
using System.Windows;

namespace Ion.Windows.UI
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.Bus != null)
            {
                App.Bus.Subscribe<ResponseMessage>(MessageResponseHandler);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        private bool MessageResponseHandler(ResponseMessage m)
        {
            MessageBox.Show(m.Status + " - " + m.MessageId.ToString() + " - " + m.RequestMessageId);
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Send(object sender, RoutedEventArgs e)
        {
            if (App.Bus != null)
            {
                App.Bus.SendLocal<RequestMessage>(m =>
                {
                    m.MessageId = Guid.NewGuid();
                    m.Name = "John";
                });
            }
        }
    }
}

using Ion.Messages;
using NServiceBus;
using System;

namespace Ion.Windows.UI.MessageHandlers
{
    /// <summary>
    /// 
    /// </summary>
    public class RequestMessageHandler : IMessageHandler<RequestMessage>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        public void Handle(RequestMessage message)
        {
            if (App.Bus != null)
            {
                App.Bus.Reply<ResponseMessage>(m =>
                {
                    m.MessageId = Guid.NewGuid();
                    m.RequestMessageId = message.MessageId;
                    m.Status = "Completed";
                });
            }
        }
    }
}

You may notice that we created a class that implements the IMessageHandler, this class automatically handles the messages and implements action into it.

That’s it!

Advertisements

1 Comment »

  1. Hi Johnllao,

    I tested with your code above, but there isn’t any message box to show up on the Status, MessageId or RequestMessageId. Could you help?

    I can be reached via tanthiamhuat@yahoo.com

    thanks.

    Sincerely,
    Thiam Huat

    Comment by tanthiamhuat — September 3, 2011 @ 3:00 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: