just in ram

A list of stuff I should remember but never do

How the new Host feature works in nServiceBus

with 5 comments

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:

Either way take a look at the FullDuplex/RequestResponse sample project which consists of a Client, Server and Messages project:

image

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:

image

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…

image

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):

image

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:

image

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:

image

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

image

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

image

You’ll then be prompted to supply some authentication details for the service:

image

Enter some relevant user details and hit ok and your service will be installed and ready to start:

image

Uninstall service

Finally you can also uninstall the service:

NServiceBus.Host.exe /uninstall

image

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.

kick it on DotNetKicks.com

Written by Justin Ramel

August 3rd, 2009 at 5:02 pm

Posted in nServiceBus

Tagged with

jQuery Validation Plugin – Dynamically change validator message

with 4 comments


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.

Written by Justin Ramel

June 25th, 2009 at 9:43 pm

Posted in jQuery

Tagged with

Building FubuMVC with a portable version of rake

with one comment

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:

image

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:

image

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!

Written by Justin Ramel

June 19th, 2009 at 3:55 pm

Posted in FubuMVC, General

Tagged with

FubuMVC – Resources

without comments

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

Wiki

Blog posts

Webcasts

Podcasts

Group

Twitters

Written by Justin Ramel

June 18th, 2009 at 12:11 am

Posted in FubuMVC

Tagged with

Resharper format settings

with one comment

I can never remember these so thought it best to write them down. Start with the settings from:

http://codebetter.com/blogs/aaron.jensen/archive/2008/10/19/getting-resharper-and-vs-to-play-nice-with-mspec.aspx

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 lineimage
  • Blank lines – I don’t like a lot of blank lines so I set mostly to 1/0image
  • Other –> Align Multiline Constructs – Call arguments = Off

  • Other –> Align Multiline Constructs – Expression = Offimage

  • Other –> Other – Indent array, object and collection initializer block = Offimage

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>

image

Also  delete the section:

<Group>
  <Name Region="Nested type: ${Name}"/>
</Group>

image

Finally click Ok.

Code Cleanup

Go to menu Resharper –> Options –> Tools –> Code Cleanup

Add a new profile with the following settings:

image

I didn’t realise I had fiddled with the default settings so much no wonder I can never remember them.

Written by Justin Ramel

June 10th, 2009 at 5:15 pm

Posted in Resharper

Tagged with

Setup ASP.NET MVC with Spark View Engine in 5 minutes or less

with 2 comments

Setup folder structure:

image

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.

add new projectChange 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.

vs_add_ref

Add references to asp.net mvc System.Web.Routing.dll, System.Web.Abstractions.dll, System.Web.Mvc.dll

image

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.

image

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:

image

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:

image

You can download this sample solution here.

Written by Justin Ramel

June 8th, 2009 at 2:33 pm

Posted in Mvc, Spark

Tagged with ,

HOWTO: Add svn:externals in windows using tortoisesvn

with 2 comments

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.

  1. Go to the root of the folder you want to add the externals too.
  2. Right click on the root folder of the project you want to add the external repository to and select TortoiseSVN –> Properties.tortoise_settings[3]   Note: This folder has to be a checked out subversion repository or you’ll not get the context menu! 
  3. You will now see the subversion properties dialog.tortoise_properties[1]
  4. Click the New.. button. You will now see the Add properties dialog.tortoise_add_properties[1]
  5. Select svn:externals from the property name drop down list.
  6. 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.
  7. Click Ok to add the property will now be listed in the properties dialog.tortoise_properties2[1]
  8. 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 …tortoise_error[1]

Written by Justin Ramel

June 4th, 2009 at 12:00 am

Posted in Subversion

Tagged with

HOWTO: Download and run Microsoft Report Builder 1.0

with 2 comments

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

Written by Justin Ramel

May 20th, 2009 at 4:58 pm

Posted in General

Tagged with

developwithpassion.bdd – notes

with one comment

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

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");

Written by Justin Ramel

April 30th, 2009 at 6:29 pm

Posted in BDD

Tagged with

Castle ActiveRecord – Exception : The ProxyFactoryFactory was not configured

with 18 comments

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.

Written by Justin Ramel

January 23rd, 2009 at 4:38 pm

Posted in ActiveRecord, Castle

Tagged with ,