Archive for the 'Castle' Category

10 is live!

After a few evenings hard work, I can now announce that is now live!

Currently there is only one screencast to watch but I’ll be building on this in the coming weeks. If you have any ideas for future episodes or feedback for the site feel free to post them on the forum.

I’ll be adding a submission form soon so you can submit your own screencasts for inclusion in the site. If you want to submit a Castlecast before this is ready, just email me the details at: andy[at]

Now a big thank you to the Castle team, especially Henry Conceição for space on the Castle build server and also for the hosting of the site. You guys rock!

If you’re interested in how the site was built then the source is available on GitHub so feel free to take a look and if you fancy sending me a pull request, I’d be happy to receive them ;o)


Introducing Castlecasts

It’s been a very long time since I lasted blogged but I’ve found some time and would like to take this opportunity to announce Castlecasts.

After doing a lot of learning in Ruby on Rails, one of the best resources that I found was the site. For those who don’t know, it contains over 200 screencasts about various aspects of programming in RoR. So I posted the idea of creating a similar site for the CastleProject which seemed to have some interest.

I found some spare time and have decided to start I’ve been looking for a way to give back to the Castle team for a while as I’ve been using their components for over 2 years. I think this could be an excellent resource for the Castle community, if you have any questions or comments please let me know.

The site isn’t ready yet but I have created the first screencast. It’s hosted on Vimeo (for now) to keep hosting costs down. Once the site is ready I’ll let you know, but in the meantime, here is the first episode:

Getting Started With MonoRail from Andy Pike on Vimeo.

You can get the source code for this episode on github:

I plan on adding a whole bunch more episodes, so if you have a suggestion for something to cover or have a screencast you would like to add, DM me on twitter: @andypike

I’ll be on the look out for some hosting, so if you feel like sponsoring, donation of hosting would be cool ;o) I’m working on the site now, should have something simple up and running soon. Then I’ll start creating more episodes.


Integrating Gravatar with Castle MonoRail

As part of my experimental Castle MonoRail project that I mentioned last time. I now wanted to allow users to include an image (avatar) within their profile. Obviously I could have just allowed them to upload an image, store it and then shown it when required. But I thought I’d integrate with Gravatar instead.

Gravatar is basically a free service where anyone can store an avatar image against an email address. They provide a very simple API for us developer types to integrate with given a user’s email address. So without further ado, here is what I did:

1. I signed up for a Gravatar account and uploaded an image ready for testing.

2. I created a test (TDD style) for a GravatarHelper class that would at first just return the correct image URL for an email address. I took the test data from their documentation so I knew it was correct:

public class When_using_the_gravatar_helper
    public void Should_build_a_basic_image_url()
        var gravatar = new GravatarHelper();
        string url = gravatar.Url(" ");

        Assert.That(url, Is.EqualTo(""));

OK, so pretty straightforward there then. The email address is of mixed case and has spaces around it on purpose as the documentation specifies that emails need to be trimmed and lowercased before hashing.

3. Now I have my failing test, I went right ahead and started implementing it:

public class GravatarHelper : AbstractHelper
    private const string PROTOCOL = "http";
    private const string DOMAIN = "";
    private const string PATH = "avatar";
    private const string EXTENSION = "jpg";

    public string Url(string email)
        email = email.ToLower().Trim();

        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] hash = md5.ComputeHash(Encoding.ASCII.GetBytes(email));

        var hashAsHex = new StringBuilder();
        Array.ForEach(hash, b => hashAsHex.Append(b.ToString("X2")));

        return string.Format("{0}://{1}/{2}/{3}.{4}", PROTOCOL, DOMAIN, PATH, hashAsHex, EXTENSION).ToLower();

Again, no rocket science here. I just lowercase and trim the email address then hash it using the built-in .NET MD5 hash provider. Then I have to convert each byte in the hash into hex and add it to a string. Lastly I return the URL that has been built up from the various parts (and lowercased for good measure).

4. Next, just add the helper to my controller:

[Helper(typeof(GravatarHelper), "gravatar")]
public class AccountController : SmartDispatcherController

5. Then the simple task of using the helper in my view (not my real email):

<img src="$gravatar.url('')" />

And hey presto, my Gravatar of my son appeared on my page, wahoo:


Now that is all very good, but there are some extra parameters that the Gravatar API support. These are size, rating and default (in case the email address isn’t registered with them). I also wanted the helper to generate the image tag for me. So I went about creating a new helper test:

public void Should_build_an_image_url_inside_an_image_tag_with_parameters()
    var gravatar = new GravatarHelper { ServerUtility = new StubServerUtility() };
    IDictionary parameters = new Hashtable
                                     { "size", "48" },
                                     { "default", "" },
                                     { "rating", "g" }
    string tag = gravatar.Image(" ", parameters);
    Assert.That(tag, Is.EqualTo("<img src=\"\" alt=\"Gravatar\" />"));

I’m using an IDictionary here so that I can leverage the support for it in NVelocity. So about these parameters: The size parameter is the size in pixels that you would like the image (1 to 512) which defaults to 80. The default parameter is a URL of an image in case the email address supplied isn’t known by Gravatar. The rating parameter can be g, pg, r or x. Also notice in the test the need to set the ServerUtility property of the helper, I just using the StubServerUtility provided by Castle.

Now for the implementation:

private const string IMAGE_TAG_FORMAT = "<img src=\"{0}\" alt=\"Gravatar\" />";

public string Url(string email, IDictionary parameters)
    string url = Url(email);
    string queryString = CommonUtils.BuildQueryString(ServerUtility, parameters, false);

    return string.Concat(url, "?", queryString);

public string Image(string email, IDictionary parameters)
    return string.Format(IMAGE_TAG_FORMAT, Url(email, parameters));

The eagle-eyed amongst you will notice that I’ve added an overload to the Url method as well that supports parameters (I wrote a test for this first, so don’t panic). So you can now either create a url with parameters or a full image tag. So now in my view I can do this:

$gravatar.image("", "%{size='48', rating='g', default=''}")

That about wraps it up for now. I’ve committed all my code into my Google Code repository, so feel free to have a look:

kick it on


Integrating reCAPTCHA with Castle MonoRail

I’m currently working on a little experimental Castle MonoRail project and wanted to add a CAPTCHA image to a form. Of course I could try to create my own but I don’t like reinventing the wheel so I did a little digging and came across reCAPTCHA. It can be integrated into websites and has a number of tools available to help you do this.

I couldn’t find an example of using it with MonoRail, but did find this example for ASP.NET MVC by Derik Whittaker which pointed me in the right direction. Here’s what I did:

1. Sign up to reCAPTCHA to obtain my private and public keys. I made this a global account so I can test it on my local server rather than only on an assigned domain.

2. Added the keys to my web.config:

    <add key="recaptcha.public" value="***" />
    <add key="recaptcha.private" value="***" />

3. Downloaded the ASP.NET library and added a reference to the recaptcha.dll assembly.

3. Created a new helper for rendering the control in the view:

public class CaptchaHelper : AbstractHelper
    public string Render()
        var captchaControl = new RecaptchaControl {
              ID = "recaptcha",
              Theme = "blackglass",
              PublicKey = ConfigurationManager.AppSettings["recaptcha.public"],
              PrivateKey = ConfigurationManager.AppSettings["recaptcha.private"]
        var htmlWriter = new HtmlTextWriter( new StringWriter() );
        return htmlWriter.InnerWriter.ToString();

4. Added the helper to my controller:

[Helper(typeof(CaptchaHelper), "captcha")]
public class HomeController : SmartDispatcherController

5. Called the helper inside a form in my view:


6. Created a new parameter binder (instead of Derik’s filter) that determines if the user entered the CAPTCHA code correctly:

[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class CaptchaBindAttribute : Attribute, IParameterBinder
    private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
    private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
    public object Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
        var captchaChallengeValue = context.Request[CHALLENGE_FIELD_KEY];
        var captchaResponseValue = context.Request[RESPONSE_FIELD_KEY];
        var captchaValidtor = new Recaptcha.RecaptchaValidator
                                  PrivateKey = ConfigurationManager.AppSettings["recaptcha.private"],
                                  RemoteIP = context.UnderlyingContext.Request.UserHostAddress,
                                  Challenge = captchaChallengeValue,
                                  Response = captchaResponseValue
        var recaptchaResponse = captchaValidtor.Validate();
        return recaptchaResponse.IsValid;
    public int CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
        if (parameterInfo.ParameterType == typeof(bool))
            return 10;
        return 0;

7. Used the new parameter binder on the receiving controller action to determine if the user passed the CAPTCHA test:

public void Register([CaptchaBind]bool captchaValid)

And that’s about it. I’ll be releasing this project as open source soon (once I’ve made some more progress). I’ve added these components to my AndyPike.Commons assembly which will also be available to those that would like it, but the above code samples should be enough to get you going. Oh, and here is what the view looks like:


recaptcha in action

kick it on


My Archives

My Categories