just ram

stuff I should remember

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:

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](http://cid-d7d57b78b0ddedf5.skydrive.live.com/self.aspx/.Public/blog/portable rake/portablerake.zip) (_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

Wiki

Blog posts

Webcasts

Podcasts

Group

Twitters

Resharper format settings

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:

image

Also delete the section:

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.

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

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:

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>

Debug true shows compilation errors when rendering views.

Add routing to httpModules section of web.config:

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 routes) { routes.Add(new Route( “{controller}/{action}/{id}”, new RouteValueDictionary(new {controller = “home”, action = “index”, id = “”}), new MvcRouteHandler())); }

public void RegisterViewEngine(IList 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.

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”>

Sample

Header

** **

Footer

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

Hello spark.

Run the project and you should get:

image

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.

  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 _T_ortoiseSVN –> _P_roperties.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 _N_ew.. 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]

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

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:

Nu.Core ** **

Then add a reference in your project to NHibernate.ByteCode.Castle.dll.

MonoRail custom rescue controller (IRescueController)

The problem

I am calling a web service from a controller and the web service throws a WebException with different exception messages, one when the remote server is unavailable and another when the remote server times out. I’d like to show a rescue view based on the exception type and message not just it’s type.

The standard Monorail Rescue attribute only takes an exception type so there didn’t seem to be an easy way to solve my problem. I could have a generic rescue view which shows an error for all WebExceptions but I’d like to be a bit more specific. I could send all WebExceptions to the same rescue view and then handle the different messages in the view but I didn’t want the logic in my rescue view.

I noticed in the trunk (revision 5407) the Rescue attribute takes a rescue controller which I’d never seen before. I started digging around the web and source and came up with the following solution which works although I not sure its the best solution!

My solution

I changed my base controller to use a rescue controller instead of rescue views:

[Rescue(typeof(RescueController))]
public class ApplicationController : SmartDispatcherController

I then created a RescueController:

[Layout("default")]
public class RescueController : SmartDispatcherController, IRescueController
{
	public void Rescue(Exception exception, IController controller, IControllerContext controllerContext)
	{
		SetRescueView("generalerror");
		if (exception.GetType() == typeof(WebException) && exception.Message == "Unable to connect to the remote server") SetRescueView("webexception_cannot_connect");
		if (exception.GetType() == typeof(WebException) && exception.Message == "The operation has timed out") SetRescueView("webexception_portal_timeout");

	}

	private void SetRescueView(string viewname)
	{
		RenderSharedView(Path.Combine("rescues", viewname));
	}
}

The Rescue method simply checks the exception type and message and if it gets a match it sets the relevant rescue view. Notice I’m using a little helper method to set the rescue view this tells Monorail look in the standard folder Views\rescues for the view otherwise it would be looking for these views in Views\Rescue which could get confusing.

Gotchas!
  • Make sure your custom rescue controller inherits from SmartDispatcherController otherwise your custom controller will not get called. See Castle Project Users list for more detail

  • Add the Layout attribute to the Rescue controller if you want to use your standard layout on the rescue pages.

  • If your using the Windsor container remember to add the Rescue controller to your container otherwise your custom rescue controller will not be found and called. This one had me scratching my head for a while!

  • Make sure your rescue views exist in the Views\rescues folder otherwise you will get the standard ASP.NET error page and it will look like none of this has worked.

  • This works with the trunk (revision 5407) not sure when the IRescueController functionality was added so it may not work with earlier revisions.

A better solution?

I thought a better solution would be to add a sub string message to the Rescue attribute which could be used to match the exception type and message. E.g:

Rescue("web_exception_unable_to_connect", typeof(WebException), "Unable to connect to remote server")
Rescue("web_exception_timeout", typeof(WebException), "The operation has timed out")

I couldn’t see an easy way to extend the standard Monorail rescue functionality so I ended up creating a builder which allowed me to define a map of exceptions to rescue views.

builder.Map<WebException>()
	.WithMessageContaining("Unable to connect to the remote server")
	.OrMessageContaining("The remote server returned an error: (403) Forbidden.")
	.ToRescue("webexception_cannot_connect");

builder.Map<WebException>()
	.WithMessageContaining("The operation has timed out")
	.ToRescue("webexception_portal_timeout");

My final rescue controller simply uses the map to select the correct rescue view, no more if statements needed.

[Layout("default")]
public class RescueController : SmartDispatcherController, IRescueController
{
	private readonly IExceptionToRescueMapper _mapper;

	public RescueController(IExceptionToRescueMapper mapper)
	{
		_mapper = mapper;
	}

	public void Rescue(Exception exception, IController controller, IControllerContext controllerContext)
	{
		SetRescueView(_mapper.GetRescueFor(exception));
	}

	private void SetRescueView(string viewname)
	{
		RenderSharedView(Path.Combine("rescues", viewname));
	}
}

If you know of a better way I’d love to hear it…