Earlier we’ve gone through on how one can modify the NServiceBus FullDuplex sample so that the NServiceBus debug-messages aren’t shown on the console. The change we did allowed us to change the whole log4net configuration. But, if we only care about hiding the debug-messages, there’s an easier way.

NServiceBus.Host.exe has a support for different profiles.  Profiles are meant to easy the path from moving your application from the development into the production. The profiles allow you to change some aspects of your application (like logging) without making any code or configuration changes. NServiceBus comes with three different profiles and you can build your own. The built-in profiles are:

  • Lite
  • Integration
  • Production

You can find more information about the built-in profiles through the NServiceBus documentation.

If you’re using the generic host (NServiceBus.Host.exe) and you want to remove the NServiceBus debug messages from your console, you can easily do that with the help of the built-in profiles. If you start your host with an Integration-profile, the debug-messages will not print on the console.

To start the host with a specified profile, add the profile’s class name as an argument to the host. In our case we want to start the host with an integration-profile and here’s how we do that:

NServiceBus.Host.exe NServiceBus.Integration

And as you can see, the debug messages are gone.



In some cases you may want to tighten up your NServiceBus security by encrypting some parts of your message. This may be required if your client application sends some sensitive data to the server. By following this tutorial you learn how to use the built-in encryption features of the NServiceBus.

We’re not going to build everything from the scratch. Instead, we’re using our previous ASP.NET MVC application as the starting point.

1. Modifying the message

We start by modifying our HelloWorldMessage. Until this point, the message hasn’t contained any data so let’s change this now. NServiceBus contains a class called “WireEncryptedString” which we can use when transporting sensitive string-based data from our client to server. Using the class is as easy as using a regular string. Modify our message class by adding a new member to it:

   1: public class HelloWorldMessage : IMessage
   2: {
   3:     public WireEncryptedString SecretMessage;
   4: }


That’s all we have to change in our message so it’s time to modify our client.

2. Modifying the client

As you remember, we create our message in the HomeController. Open it up and modify the SendHello-method so that our new SecretMessage-field is filled with information:

   1: public ActionResult SendHello()
   2: {
   3:     var message = new HelloWorldMessage() { SecretMessage = "Encrypt this" };
   5:     MvcApplication.Bus.Send(message);
   7:     return View("Index");

Now open up the client’s web.config and add a new configSection:

<section name="RijndaelEncryptionServiceConfig" type="NServiceBus.Config.RijndaelEncryptionServiceConfig, NServiceBus.Core"/>

And then add the actual configuration just before the </configuration> tag:

<RijndaelEncryptionServiceConfig Key="gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e7"/>
Only one thing left in our client. You must change the NServiceBus initialization so that the RijndaelEncryptionService is used.  After the change, the full configuration in Global.asax.cs looks like this:
   1: Bus = Configure.WithWeb()
   2:     .Log4Net()
   3:     .DefaultBuilder()
   4:     .XmlSerializer()
   5:     .RijndaelEncryptionService()
   6:     .MsmqTransport()
   7:         .IsTransactional(false)
   8:         .PurgeOnStartup(false)
   9:     .UnicastBus()
  10:         //.ImpersonateSender(false)
  11:     .CreateBus()
  12:     .Start();

Before we modify our server, start up the client and hit the “Send hello” few times. Now, fire up the MSMQ monitoring tool of which we learned last time and browse to the Message Queuing – Private Queues – inputqueue – Queue messages. Here you can see listed all the messages in our queue. Double click on one of them and a window with information about your message opens. Select the Body-tab and see what your HelloWorldMessage looks like:


As you can see, our SecretMessage has been encrypted. For comparison, here’s a screenshot of the SecretMessage if we were using a regular string:


The last thing to do is to modify our server so that it can read our encrypted message. Let’s do that next.

4. Modifying the server

Our server’s message handler, initialization and configuration must be changed so that it can process the secret message. In message handler, start by modifying our current implementation so that it prints out the secret message to the console:

   1: public void Handle(HelloWorldMessage message)
   2: {
   4:     Console.WriteLine("Hello world from the client!");
   6:     var principal = System.Threading.Thread.CurrentPrincipal;
   8:     var userName = principal.Identity.Name;
   9:     Console.WriteLine("User: {0}", userName);
  10:     Console.WriteLine("Secret message: {0}", message.SecretMessage.Value);
  11: }
Notice the Value-property of the SecretMessage-field.

Now start your server and see how it processes the messages:


As you can see, the encrypted message isn’t yet readable. Open up the Class1, which contains our server initialization. We need to tell our server to use the encryptions by calling the Configure.Instance.RijndaelEncryptionService-method. But, because of some unknown reason, if we just add that one line into our Init-method, the server will crash in startup because of an “Object reference not set”. So instead, modify the Class1-class to look like this snippet:

   1: public class EndpointConfig : IConfigureThisEndpoint, AsA_Server { }
   2: public class ServerInit : IWantCustomInitialization, IWantCustomLogging
   3: {
   4:     public void Init()
   5:     {
   6:         Configure.Instance.RijndaelEncryptionService();
   7:         NServiceBus.SetLoggingLibrary.Log4Net(log4net.Config.XmlConfigurator.Configure);
   8:     }
   9: }

Now we have taken care of our server’s initialization so there’s only one last step left: modifying the server configuration. We need to add the exact same configurations as we did when modifying the web.config. Go ahead and copy-paste the RijndaelEncryptionServiceConfig-configurations from the client and you’re all set.  It’s time to start your application and see the difference.




When sending sensitive information between your client and server, it may be best to encrypt some parts of the message. NServiceBus contains a built-in “WireEncryptedString”- and “RijndaelEncryptionService”-classes which make the process very simple.


Yesterday we learned how to create a small ASP.NET MVC 2 application which uses the NServiceBus as its server. Also we learned how to extract the user name of the message’s sender in a message handler. Today we’re going to try out what happens to the client if the server is down.

Take the application we built yesterday and start the client. Make sure that the server isn’t running. Click on the “Send hello” few times and notice that the software seems to be working normally. This is because the call from our HomeControl to the NServiceBus is asynchronous. The web client doesn’t have wait for the server to answer. Now imagine that we’re using a real web application and user fills some information and sends the message to the bus. What the user doesn’t know is that the server has just crashed so there’s now one handling the calls from the queue. Was the user’s work lost? You can start your server to find out.


As you can see, the answer is no. NServiceBus uses the Store & Forward Messaging model where the client just passes the message to the messaging system and then the client is free to continue its own work. It’s up to the messaging system to deliver the message to the right destination. You can find more information about this model from the links provided in the end of this post.

Close the server again and click the “Send hello” few more times. Let’s use Windows’ own tools to visualize what is happening. Remember how we configured our client to use the InputQueue as our HelloWorldMessage’s endpoint? Good, because it’s that queue which is holding our messages until we start our server again.

Internally, NServiceBus uses MSMQ-queues when working with the messages. The operating system includes a software which can be used to monitor the MSMQ-queues. If you’re using Windows 7 or Windows Vista (sorry, I don’t have instructions for you Win XP users), you can start up your Computer Management –application. From there, browse to “Services and Applications” - “Message Queuing” - “Private Queues”. Your view should look similar to the following screenshot:


There’s our messages! If you now start your server, you should see how the messages are processed. If you switch back to the Computer Management and hit F5, your inputqueue is again empty.


Designing you application around a messaging system like NServiceBus allows the client application to work even if your server goes down for a moment. Also, if your messages seem to be disappearing before they reach the server, you can use Windows’ own tools  to browse through your message queues.



In this post we’re going to create a small Hello World application using the ASP.NET MVC 2 and NServiceBus. We’re going to use the forms authentication to pass the user credentials from the web client to the NServiceBus-based server. You can download the source code from the link in this post’s conclusion.

We’re going to use Visual Studio 2010 and .NET Framework 4.0 to create the sample.

1. Creating the solution

Let’s start by creating the solution. Start up your Visual Studio 2010 and create a new ASP.NET MVC 2 Web Application. By using the default template and not the empty web application template, we can use the built in AccountController for our client’s authentication. This class already implements the forms authentication for us. Please note though that using the default AccountController isnot advisable if you want to build an easily testable application.

You can hit F5 to make sure that your application is working at this point. We’re going to implement the connection from the client to the NServiceBus little later. Before that, we’re going to build our server.

2. The server

Now that we have our solution and ASP.NET MVC client set up, we’re going to implement the NServiceBus server. We’re not going to build that one from the scratch either. Instead we’re going to use the server which we built when we’re trying to get NServiceBus to play nicely with .NET Framework 4.0. Add that server project to your solution and make sure that everything compiles. At this point your solution should look like this:


You can right click on your ClassLibrary1 and select Debug – Start new instance to start your server. If you do that now, you can see that everything is logged to the console windows and it’s quite hard to figure out what’s going on. That’s why we’re going customize our logging. Remember, we’re going to build a full-blown Hello World application so it’s important we see our hellos on the screen.

Customizing the logging is easy.Open up your Class1.cs and make it implement the IWantCustomLogging-interface. Then, add the required Init-method and from there, make a call to SetLoggingLibrary’s Log4Net-method. The final product looks like this:

   1: public class Class1 : IConfigureThisEndpoint, AsA_Server, IWantCustomLogging
   2: {
   3:     public void Init()
   4:     {
   5:         SetLoggingLibrary.Log4Net(log4net.Config.XmlConfigurator.Configure);
   6:     }
   7: }
Then open up the App.config and use it to configure the Log4net. First, add a new log4net-configsection. Then, add the log4net-configuration. Your complete configuration should look like the following snippet:
<?xml version="1.0" encoding="utf-8" ?>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  <log4net debug="false">
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n"/>
      <level value="INFO"/>
      <appender-ref ref="console"/>
Now, start the server from the context menu and instead of every debug message you should only see one information:

2010-08-09 18:12:34,780 [Worker.5] INFO  NServiceBus.Unicast.UnicastBus [(null)]
<(null)> - InputQueue initialized.

The next thing we need to do is to create the hello world message and the handler for it.

3. The message and its handler

Start creating the message by adding a new class library project to the solution. In our tutorial we’re going to name it “Message”. Add a reference to NServiceBus.dll and rename the Class1 to HelloWorldMessage. Then all what is left is to decorate the class with IMessage-interface. The code looks like this:

   1: namespace Message
   2: {
   3:     public class HelloWorldMessage : IMessage
   4:     {
   5:     }
   6: }

The message is ready so we’re going to build our message handler next. First, add a reference from your server-project to the Message-project. Then, add a class to the server-project and call it HelloWorldMessageHandler. Your new handler must implement the IHandleMessages<HelloWorldMessage> –interface.

Remember that we’re using the forms authentication in our client and this means that you can reach the authentication credentials of the message sender from the System.Threading.Thread.CurrentPrincipal. With this information, fill in the implementation for our handler:

   1: public class HelloWorldMessageHandler : IHandleMessages<HelloWorldMessage>
   2: {
   3:     public void Handle(HelloWorldMessage message)
   4:     {
   5:         Console.WriteLine("Hello world from the client!");
   7:         var principal = System.Threading.Thread.CurrentPrincipal;
   9:         var userName = principal.Identity.Name;
  10:         Console.WriteLine("User: {0}", userName);
  11:     }
  12: }
As you can see, the handler will print out the “Hello world” message and then the user’s name who sent the message to our bus.

Our server is now ready so you can start it from the context menu and let it run on the background (select Debug – Start new instance and then Debug – Detach all). Now all that is left is to connect our ASP.NET MVC 2 client to our server.

4. Connecting the client with out server

Because we’re using the ASP.NET MVC 2 template, we have most of the required functions already implemented. We’re going to modify the default web application by adding a new ActionLink to the Home-view. When a user clicks the link, a HelloWorld-message is sent to the server. Start by adding a reference to the following projects and dlls:

  • Message-project which we created in our previous step
  • NServiceBus.dll
  • NServiceBus.Core.dll
  • log4net.dll

Then open the Index-view (Views / Home) and remove everything from the MainContent-section and add the new actionlink:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <%: Html.ActionLink("Send hello", "SendHello", "Home")%>
Now, open the HomeController and add a new SendHello-method which returns an ActionResult. Before we can actually implement this method we have to acquire an instance to the NServiceBus. To do this, we’re going to edit the Application_Start-method in Global.asax.cs. Please note that our way isn’t the best way of doing this. In a real application you should use a IoC-container to inject the IBus to your controller-class.

Open the Global.asax.cs and add a static IBus member called Bus:

public static IBus Bus { get; private set; }
Then initialize the Bus-member in the Application_Start-method. The complete method should look like the following:
   1: protected void Application_Start()
   2: {
   3:     AreaRegistration.RegisterAllAreas();
   5:     RegisterRoutes(RouteTable.Routes);
   7:     Bus = Configure.WithWeb()
   8:         .Log4Net()
   9:         .DefaultBuilder()
  10:         .XmlSerializer()
  11:         .MsmqTransport()
  12:             .IsTransactional(false)
  13:             .PurgeOnStartup(false)
  14:         .UnicastBus()
  15:             .ImpersonateSender(false)
  16:         .CreateBus()
  17:         .Start();
  18: }

Because the Bus-member is public and static, we can now use it from our HomeController. Open up the HomeController again and finish the implementation of our SendHello-method. In the method, first create an instance of the HelloWorldMessage, then send it through the Bus and finally, return us back to the Home-view:

   1: public ActionResult SendHello()
   2: {
   3:     var message = new HelloWorldMessage();
   5:     MvcApplication.Bus.Send(message);
   7:     return View("Index");
   8: }
Only thing left is to update our client’s configuration with the knowledge of our NServiceBus server.

5. Modifying the web.config

Open the Web.config from your client-project and just after the <configuration> tag add the following four lines:

    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core"/>
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
At that point you may see an error stating that the assembly NServiceBus.Core could not be resolved. You can fix this by building the project. Locate the </configuration> tag from your web.config and before that, add the NServiceBus configuration:
<MsmqTransportConfig InputQueue="MyWebClient" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5"/>
    <add Messages="Message" Endpoint="InputQueue"/>

Everything is now set up! Start up your web client (and make sure your server is still running) and you should see our modified home-page:


Click the Send hello –button few times and this is what you should see in your server’s console window:


The point of this tutorial was to pass the forms authentication information from your client to the server so let’s try that next. In your web site, click the Log on –link, then Register and fill in the details of your user. After registering, you’re already logged in and you should see our home-page. Click the Send hello and see how our server behaves.


Nice! If you take a step back and look at our NServiceBus-initialization in the Global.asx.cs, you can see that we set the ImpersonateSender to false. I’m not sure if this is by design or is it a bug, but we can remove the line, leave it to false or set it to true and in every case, the server can see the credentials of the user. This post from Udi Dahan seems to imply that is by design.


Now that we can see the user credentials on our NServiceBus message handler, we can implement a simple security system to our server. If you know that some messages can only be send by an authenticated user, you can throw away the messages which are missing the principal-information. You can do this in every message handler, manually. Or alternatively, you can create an AuthenticationMessageHandler which executes before your normal message handlers and throws away the messages from unauthorized sources (by calling the Bus.DoNotContinueDispatchingCurrentMessageToHandlers()-method). I’m hoping to post about this solution on a later date.


Getting the forms authentication information on a NServiceBus message handler is

as simple as reading the principal-information from the current thread. You can use that information when implementing a security system to your NServiceBus server.

Download the source code.