How the new Host feature works in nServiceBus
The latest Alpha version of nServiceBus uses the TopShelf project as part of its new hosting feature. This new Host feature makes it super easy to setup a console/windows service for your clients/servers. So here’s how *I think* it works and what you can do with it…
Get nServiceBus
First you’ll need to get the latest build which includes the new Host feature either:
- Check out the source and build it yourself from the subversion repository:
https://nservicebus.svn.sourceforge.net/svnroot/nservicebus/trunk/
OR - Download a demo solution I hacked out of the nServiceBus samples (FullDuplex/RequestResponse): nServiceBus Host Demo
Either way take a look at the FullDuplex/RequestResponse sample project which consists of a Client, Server and Messages project:
Run the sample
Note: To get the Server to run successfully in my demo solution I had to change the app.config slightly by replacing the UnicastBusConfig setting with:
<UnicastBusConfig DistributorControlAddress="" DistributorDataAddress="">
<MessageEndpointMappings>
</MessageEndpointMappings>
</UnicastBusConfig>
Ok simply hit F5 to run the sample and two console windows should appear one for the Client and one for the Server:
So everything is running ok our Client can send messages to the Server and receive a response. But what’s just happened?
Multiple startup projects
First the solution is set to start both the Client and the Server projects. This is set in the solution property pages you can view this setting by right clicking on the solution and selecting Set StartUp Projects…
As you can see the solution is set to start multiple projects namely the Client and the Server.
Now the Server and Client projects are both Class Library’s so how come they are running as console apps when we F5 (debug) the solution?
Debug settings
If we take a look at the Debug settings for the Client (Right click the Client project and select Properties, then Debug from the tab):
Notice the Start Action is set to Start external program NServiceBus.Host.exe from the Client projects debug\bin directory. When we hit F5 to debug the application visual studio runs this exe and that’s how we get the console windows.
Reference NServiceBus.Host.exe
NServiceBus.Host.exe ends up in the debug\bin because its referenced by the project for example in the Client:
But how does it know where to get its configuration?
Configuration
NServiceBus.Host.exe scans its current directory for any dlls. For each dll it finds it searches for a class which implements the interface IConfigureThisEndpoint. If the search is successful the Host knows to use the app.config for this dll so in the case of the Client – Client.dll.config is used to configure nServiceBus.
Client
If we take a look at the Client project we’ll find the class EndpointConfig which implements the IConfigureThisEndpoint. This is simply a marker interface which has no actual implementation. Notice there are other interfaces used to configure the client which do require implementations:
public class EndpointConfig:IConfigureThisEndpoint,
As.aClient,
ISpecify.ToUseXmlSerialization,
ISpecify.XmlSerializationNamespace,
IWantCustomInitialization,
ISpecify.ToRun<ClientEndpoint>
{
public string Namespace
{
get { return "http://www.UdiDahan.com"; }
}
public void Init(Configure configure)
{
configure.RijndaelEncryptionService();
}
}
Of particular interest, the interface used to configure the dll as a client (As.aClient) and another to specify which code to actually run (ISpecify.ToRun<ClientEndpoint>). The ClientEndPoint class contains the code which is runs when the Host starts and stops.
Note there are lots more interfaces which can be used to specify configuration options:
Server
The Server project works in pretty much the same way as the Client it has an EndpointConfig class:
public class EndpointConfig:IConfigureThisEndpoint,
As.aServer,
ISpecify.ToUseXmlSerialization,
ISpecify.XmlSerializationNamespace,
IWantCustomInitialization
{
public string Namespace
{
get { return "http://www.UdiDahan.com"; }
}
public void Init(Configure configure)
{
configure.RijndaelEncryptionService();
}
}
Here the interfaces are used to configure the dll as a server (As.aServer) and IWantCustomInitialization which allows you to specify additional configuration via the Init method. The Server project also contains the RequestDataMessageHandler class which the bus knows to use when a RequestDataMessage arrives.
All this makes it very easy to create Client and Server applications for nServiceBus which are a doddle to debug in visual studio.
But wait there’s more…
Run from console
You can run the Client or Server from outside Visual Studio from the command line. Open a command prompt, cd to the relevant bin folder and type:
NServiceBus.Host.exe
Install as a Windows Service
We can install the Server as a Windows Service no extra code or configuration required! Open a command prompt, cd to the relevant bin folder and type:
NServiceBus.Host.exe /install
You’ll then be prompted to supply some authentication details for the service:
Enter some relevant user details and hit ok and your service will be installed and ready to start:
Uninstall service
Finally you can also uninstall the service:
NServiceBus.Host.exe /uninstall
Note: The service will not disappear from this Services management console until you reboot your machine, this is standard for a windows service.
That’s as much as I have puzzled out for now, if I’ve made and glaring errors please let me know.
jQuery Validation Plugin – Dynamically change validator message
UPDATE: Please read Guu’s comment below for a far better solution to this problem!
I’ve been using the jQuery Validation Plugin and needed to change a validation message dynamically based on the user input. I had a quick search but couldn’t find an easy solution. Unfortunately the messages are not changeable after the initial construction of the validator object. I managed to get around the problem by removing the validator an then re-adding with a new message:
Create validator
$("#Enquiry").validate({
rules: {
EnquiryText: { required: true }
},
messages: {
EnquiryText: "Enquiry must contain an entry."
}
});
Dynamically change message
function setEnquiryValidationTo(message) {
$("#EnquiryText").rules("remove");
$("#EnquiryText").rules("add", {
required: true,
messages: {
required: message
}
});
}
There may be a better/easier way to do this but I couldn’t find one via Google.
Building FubuMVC with a portable version of rake
To build FubuMVC you need to install ruby, rake etc. Unfortunately for me the firewall at work will not allow me to get the rake gem (I’ve downloaded gems before using the HTTP_PROXY setting before but no luck this time). Any hoose I remember reading Stephen Balkum post on packaging up Rake as an executable. I followed Stephens guide and created a portable rake package which got around my firewall problem but FubuMVC required another gem rubyzip to allow a build.
Adding another gem
Luckily using Stephen’s guide its really easy to add extra gems, you just need to have them installed before you build your exe. So we follow the first part of the process outlined in Stephen’s guide then do the following:
NOTE: In this case we need rubyzip but it could be any old gem.
- Download rubyzip and extract to contents to c:\rubywork\zip
- To install rubyzip, at a command prompt in c:\rubywork\zip, run ..\ruby\bin\ruby install.rb
- Download zlib and extract the zlib1.dll to C:\rubywork\ruby\lib\ruby\1.8\i386-mswin32
- Rename zlib1.dll to zlib.dll (rubyzip required this extra dll other gems may not)
Now continue part two of the process from Stephen’s guide to compile your very own allinoneruby.exe which includes, rake and rubyzip.
You should now have allinoneruby.exe and rake.rb file.
Building FubuMVC
We can now drop these files into to the FubuMVC project under the build support folder:
We need a helper batch file in the root folder of FubuMVC called rake.bat which contains:
@.\build_support\allinoneruby.exe .\build_support\rake.rb %*
This will be called when we run the build.
Run the build already
Drop to the command prompt and cd into the FubuMVC project root and simply type build. You should get something like:
Download
Don’t want to go through all that? You can download my version of portable rake here (I don’t think I’m breaking any licensing agreements here, this is all open source software. If I am let me know and I’ll remove the link)
DISCLAIMER: I offer no guarantees I can only confirm this works on my machine!
One final note
I’ve used this method to build some of the other open source projects out there which use rake (all the cool kids seem to be using rake) and so far I’ve not had any problems. This could be pretty frictionless way to introduce rake to a team of .net developers who don’t want the overhead of installing ruby on their machines. Just add it to a tools folder check it in to source control they’ll never know!
FubuMVC – Resources
UPDATE: Lots of changes are a foot with FubuMVC so a few new blog posts appearing, I’ll update this post as I find them.
I’m looking at FubuMVC for a side project, I thought it would be useful to collect a list of resources.
Source
- FubuMVC Subversion Git – Framework source code
- FubuMVC Contrib – Sample projects and add on’s to the main framework
Wiki
Blog posts
- Setting up a FubuMVC Project from Scratch – Four part series by Ryan Kelley (Part 2, Part 3, Part 4) the source code for this series is part of the FubuMVC Contrib project although I would recommend you follow along with the series and type the code as you go
- Simple application using FubuMVC – Introduction by Shashank
- FubuMVC AltOxite Works! – Guide to getting AltOxite to work (AltOxite source code is part of the FubuMVC Contrib project)
- FubuMVC – Front Controller style framework - Overview of the framework by Mark Nijhof. Note Mark’s blog was written in FubuMVC and the source is part of the FubuMVC Contrib project
- Mark Nijhof – writes up the main points from his European Virtual Alt.Net presentation
- FubuMVC.Validation – Convention based validation – Mark Nijhof describes his validation add on for FubuMVC. His validation add on is part of the FubuMVC Contrib project
- Switch between View Result and Json Result without sweat in FubuMVC
- Our “Opinions” on the ASP.NET MVC (Introducing the Thunderdome Principle) – FubuMVC evolved from a set of opinions over Asp.Net MVC. Jeremy details the “Thunderdome” principal – “All Controller methods take in one ViewModel object and return one ViewModel object”. I guess the Thunderdome name comes from the similarity to the rules of Thunderdome – “Two men enter, one man leaves.”
- Going Controller-less in MVC: The Way Fowler Meant It To Be – Chad Myers describes where FubuMVC is going
- What’s happening with FubuMVC and Where’s Ryan been? Ryan Kelley talks about recent changes to FubuMVC
Webcasts
- FubuMVC Video from Houston ALT.NET
- Mark Nijhof presents FubuMVC at the European Virtual Alt.Net
- Two part video (Part 1, Part 2) of Jeremy Miller and Chad Myers give their opinions on Asp.Net MVC at the KaizenConf (FubuMVC evolved from theses opinions)
Podcasts
Group
Twitters
Resharper format settings
I can never remember these so thought it best to write them down. Start with the settings from:
Plus a few extras…
Go to menu Resharper –> Options –> Languages –> C# –> Formatting Style
- Braces Layout –> All set to (BSD style)
- Braces Layout –> Empty braces formatting = Together on the same line
- Blank lines – I don’t like a lot of blank lines so I set mostly to 1/0
-
Other –> Align Multiline Constructs – Call arguments = Off
-
Other –> Other – Indent array, object and collection initializer block = Off

Regions
Stop Resharper adding regions to interface implementations and nested classes:
Go to menu: Resharper –> Options –> Languages –> C# –> Type Members Layout
Un-tick Use Default Patterns and you get a text area full of xml. Scroll to the bottom and delete the section:
<Group>
<ImplementsInterface Immediate="true" Region="${ImplementsInterface} Members"/>
</Group>
Also delete the section:
<Group>
<Name Region="Nested type: ${Name}"/>
</Group>
Finally click Ok.
Code Cleanup
Go to menu Resharper –> Options –> Tools –> Code Cleanup
Add a new profile with the following settings:
I didn’t realise I had fiddled with the default settings so much no wonder I can never remember them.
Setup ASP.NET MVC with Spark View Engine in 5 minutes or less
Setup folder structure:
Download and put the asp.net mvc dll’s in mvc folder and spark dll’s in spark folder.
Create a new asp.net application not a mvc application just a standard asp.net application. This means you will not get the mvc helpers for creating controllers and views but that’s not a massive loss and has the advantage that you don’t need the asp.net mvc installed if you open the solution on another machine.
Change content of Default.aspx to: <!– Placeholder do not delete! –>
The default.aspx placeholder is required to allow the asp.net routing to work.
Delete the code behind files for Default.aspx (Default.aspx.cs, Default.aspx.designer.cs) they are not needed.
Add references to the Spark.dll and Spark.Web.Mvc.dll located in the libs folder.
Add references to asp.net mvc System.Web.Routing.dll, System.Web.Abstractions.dll, System.Web.Mvc.dll
Add spark to the web.config:
</sectionGroup>
<section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
</configSections>
<spark>
<compilation debug="true" />
</spark>
Debug true shows compilation errors when rendering views.
Add routing to httpModules section of web.config:
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Add a application.cs which creates the routes and registers the spark view engine:
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using Spark.Web.Mvc;
namespace Web
{
public class Application
{
public void RegisterRoutes(IList<RouteBase> routes)
{
routes.Add(new Route(
"{controller}/{action}/{id}",
new RouteValueDictionary(new {controller = "home", action = "index", id = ""}),
new MvcRouteHandler()));
}
public void RegisterViewEngine(IList<IViewEngine> engines)
{
SparkEngineStarter.RegisterViewEngine(engines);
}
}
}
Add a global.asax with the following code behind.
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Web
{
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
var app = new Application();
app.RegisterRoutes(RouteTable.Routes);
app.RegisterViewEngine(ViewEngines.Engines);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
string path = Request.AppRelativeCurrentExecutionFilePath;
if (string.Equals(path, "~/default.aspx", StringComparison.InvariantCultureIgnoreCase) ||
string.Equals(path, "~/"))
{
Context.RewritePath("~/Home");
}
}
}
}
Create content, controllers and view folders in the root of the asp.net project:
Create a shared folder in the views folder with a _global.spark file this will be used to share come code with all views.
<use namespace="System.Collections.Generic"/>
<use namespace="System.Web.Mvc.Html"/>
Create a layouts folder in the views folder with a file called application.spark which will be used for the layout of the application very much like a master page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Header</h1>
<use content="view"/>
<h1>Footer</h1>
</body>
</html>
The use content view tag highlighted above is replaced by the current view returned by asp.net mvc.
Add a HomeController.cs under the controllers folder with the following content:
using System.Web.Mvc;
namespace Web.controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
Under the views folder create a home\index.spark with the following content:
<p>Hello spark.</p>
Run the project and you should get:
You can download this sample solution here.
HOWTO: Add svn:externals in windows using tortoisesvn
I have a few projects in subversion using the same set of third party tools nant, bdd, mbunit etc. I’ve read its a good idea to put the tools into their own repository and include them in the other projects using an svn:external. The advantage this gives you is any changes you make to the external repository can be updated easily across all projects. Any hoose this is who to do it.
- Go to the root of the folder you want to add the externals too.
- Right click on the root folder of the project you want to add the external repository to and select TortoiseSVN –> Properties.
Note: This folder has to be a checked out subversion repository or you’ll not get the context menu! - You will now see the subversion properties dialog.
- Click the New.. button. You will now see the Add properties dialog.
- Select svn:externals from the property name drop down list.
- Enter the name you want to give to the external folder followed by the path to your tools repository in property value text area.
In the example above: tools svn://server/tools/trunk
Note: You can add more external repositories by simply adding more lines to the property value text area. - Click Ok to add the property will now be listed in the properties dialog.
- Right click on the root folder and select SVN Update from the menu. Subversion will now pull down the files from the external repository and your done.
Once you check this change in other people checking out from the repository will automatically get the externals folder. Also any changes to the external repository will be updated in this repository on any update. So in this case if I add a new tool or update one of the tools all repositories using this external repository will get the changes on their next update.
Gotchas
- Don’t forget to give the folder name before the repository address and not just the repository address or you will get an error along the lines of: Error parsing svn:externals property on …
HOWTO: Download and run Microsoft Report Builder 1.0
Assuming you have an SQL Server 2005 running reporting services you can run Report builder as a ClickOnce app using the following url:
http://<servername>/reportserver/reportbuilder/reportbuilder.application
developwithpassion.bdd – notes
A few notes I’ve compiled while starting to play with JP Boodhoo’s BDD framework (http://github.com/developwithpassion). At first sight the syntax looks quite alien but try it for a while you eyes soon adjust.
JP blog posts
- How I’m Currently Writing My BDD Style Tests – Part 1
- How I’m Currently Writing My BDD Style Tests – Part 2
- Test examples with MBUnit and jpboodhoo.bdd
- Slight addition to jpboodhoo.bdd
- Using jpboodhoo.bdd with TestDriven.Net
- More new conventions for how I organize my tests!!
Base classes
- observations_for_a_static_sut – For testing a static class or a quick inline test
- observations_for_a_sut_with_a_contract – For testing against the interface of a class
- sut is automatically created
- No more broken test when you add a new dependency to a class! YAY
- Automatic creation of sut can be over ridden
- observations_for_a_sut_without_a_contract – For testing against a concrete class
Delegate call order
- context
- Can define a context block in the concerns base class which will be run before a context block in the inheriting class
- Can call method provide_a_basic_sut_constructor_argument
- after_sut_has_been_initialized
- because
- it
- after_each_observation
Exceptions
When you want to test spec? for an exception use the doing method:
because b = () =>
doing(() => sut.MethodWhichThrows());it should_throw_exception = () =>
exception_thrown_by_the_sut.Message.should_contain("MY EXCEPTION");
Castle ActiveRecord – Exception : The ProxyFactoryFactory was not configured
I’ve just updated to the latest version of the Castle stack and got hit with this exception:
The ProxyFactoryFactory was not configured. Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers. Example: NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu Example: NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle
Turns out the NHibernate config has changed and as the exception says you must now specify a factory class.
To fix the exception add a new line to your active record facility config:
<facility id="activerecord.facility" isweb="true" type="Castle.Facilities.ActiveRecordIntegration.ActiveRecordFacility, Castle.Facilities.ActiveRecordIntegration">
<assemblies>
<item>Nu.Core</item>
</assemblies>
<config>
<add value="false" key="cache.use_query_cache" />
<add value="ReadCommitted" key="connection.isolation" />
<add value="false" key="show_sql" />
<add value="NHibernate.Dialect.SQLiteDialect" key="dialect" />
<add value="NHibernate.Driver.SQLite20Driver" key="connection.driver_class" />
<add value="true=1;false=0" key="query.substitutions" />
<add value="#{ConnectionString}" key="connection.connection_string" />
<add value="NHibernate.Connection.DriverConnectionProvider" key="connection.provider" />
<add value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" key="proxyfactory.factory_class" />
</config>
</facility>
Then add a reference in your project to NHibernate.ByteCode.Castle.dll.