StackOverflow - Now With More Heroin

Oh you tricksy hobbitses!

I had largely ignored StackOverflow, not because I didn’t think it could be really cool, but because I just didn’t have time.

I logged in this morning, and someone asked a question about ticket tracking, and I answered recommending Assembla.

Later I logged, in, and was notified that I’d received the Teacher Badge, because one of my answers had been upvoted.

First, let me foray into a bit of who geeks are. We can be a bit OCD. We like collecting things. We are the people that played Final Fantasy X for 120+ hours TWICE so we could get *all* the summons.

Secondly, adding badges to StackOverflow is almost pure delicious evil. It taps into every WoW/CoH/CoV playing neuron in our geeky little brains.  They’re like tiny Pokemon!  Gotta catch’em all!  I choose you Geekachu! Collectible tokens with zero real value are a geek’s Black Tar Heroin.

There are those out there right now grinding on StackOverflow trying to get that next badge.  I know it. I can feel it in the ebb and flow of geekery that powers the tubes.

MonoRail Root Directory Routing + RoutingModuleEx

This crap is so under-documented. It took me forever to figure it out.

I love the CastleProject. But damn… documentation… the hell?

If you want http://www.yourdomain.com/ to default to say “/Home/Index.castle”, then this is how I did it. I had to use both routing engines in MonoRail (Eww, people!  Seriously. Gross!) because I could not figure out how to do it with just the new one (RoutingModuleEx).

Add this to your web.config to the top of  your httpModules section. I don’t know if it has to be on top, but it worked for me, so don’t touch it!

<httpModules>
  <!-- Need routing.old for Root Routing. -->
  <add name="routing.old"
       type="Castle.MonoRail.Framework.RoutingModule, Castle.MonoRail.Framework" />
  <add name="routing"
       type="Castle.MonoRail.Framework.Routing.RoutingModuleEx, Castle.MonoRail.Framework" />

Then, in your MonoRail web.config block, add:

<monorail>
<routing>
  <rule>
    <pattern>^(/default.aspx)(.)*$</pattern>
    <replace><![CDATA[/home/index.castle]]></replace>
  </rule>
</routing>

That should work.  If it doesn’t, well damn. I might be able to help, but the Castle Project Users Group is probably way more qualified.

Note that this adds both routing engines. The new one (RoutingModuleEx) let’s you do sexy routes like so:

var engine = RoutingModuleEx.Engine;
engine.Add(new PatternRoute("/Login")
               .DefaultForController().Is("Login")
               .DefaultForAction().Is("Login"));

I think this may be one of the few resources detailing how it works: Hammet’s RoutingModuleEx Blog Post.

This is how we roll.

Bogard’s IOC Container Guidelines

Jimmy Bogard just posted some “Guidelines” (shhh… don’t say “Best Practices”) for using IOC Containers on his blog.

This type of information is *sorely* lacking, and I am tickled pink about his blog post. It’s stuff that I had to figure out on my own through shooting myself in the foot a few (ok, several) times.

Castle ActiveRecord: ValidateIsUnique Vs. Testing

In my Castle ActiveRecord project, I want to use the ValidateIsUnique attribute, but that means when testing my models I have to have bring up the entire database and initialize Castle ActiveRecord etc. even when I’m not testing my persistence layer which is slow and undesirable. I’m using ActiveRecordMediator based repositories. It really mucks up testability.

Perhaps this is just an indicator that “ValidateIsUnique” maybe doesn’t belong in my domain models? It’s a database concern I guess, but it’s terribly convenient to be able to have it there and get the error message when I’m doing form submission from MonoRail.

So, after posting to the Castle Project Users Group, and getting help from Eric Hauser and Victor Kornov on the issue, and came up with this:

/// <summary>
/// Validate that the property's value is unique in the database when saved.
/// 
/// Also supports being disabled (primarily for testing purposes).
/// </summary>
[Serializable, CLSCompliant(false)]
public class ValidateIsUniqueSometimesAttribute : AbstractValidationAttribute
{
    private static bool enabled = true;

    /// <summary>
    /// When set to true (the default value), the Validator will run as expected.
    /// Otherwise the validator is disabled.
    /// 
    /// 
    /// </summary>
    public static bool Enabled
    {
        get { return enabled; }
        set { enabled = value; }
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ValidateIsUniqueSometimesAttribute"/> class.
    /// </summary>
    public ValidateIsUniqueSometimesAttribute() : base()
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ValidateIsUniqueSometimesAttribute"/> class.
    /// </summary>
    /// <param name="errorMessage">The error message.</param>
    public ValidateIsUniqueSometimesAttribute(String errorMessage)
        : base(errorMessage)
    {
    }

    private IValidator GetCorrectValidator()
    {
        if (Enabled)
        {
            return new IsUniqueValidator();
        }

        return new AlwaysReturnsNoErrorsValidator();
    }

    /// <summary>
    /// Constructs and configures an <see cref="IValidator"/>
    /// instance based on the properties set on the attribute instance.
    /// </summary>
    /// <returns></returns>
    public override IValidator Build()
    {
        var validator = GetCorrectValidator();

        ConfigureValidatorMessage(validator);

        return validator;
    }
}

I couldn’t do exactly what Eric recommended because the controller property in ValidateIsUniqueAttribute is private, so I couldn’t set it. I guess I could have gone all reflect-y on it, but that’s so rarely a good idea. So I ended up with a bunch of copy paste from ValidateIsUniqueAttribute, and I’m ok with that.

So to use it, at the beginning of the [SetUp] method in my unit tests, I just have to call ValidateIsUniqueSometimes.Enabled = false.

Yes, it’s a hack. Yes, it’s kinda gross, but it works, and I only need to use it when testing the validation logic of my Domain Models.

Oh and speaking of validation, Eric just put some really bad-ass new validation stuff into the Castle trunk. Now I have to pull castle trunk again. Grrr, damn you Castle for being so awesome.

Skidoosh!

Playing with BDD: ContextSpecification

So I’ve been messing around today with Behavior Driven Design today (Bellware Driven Design? Or is it Context/Specification?). I thought I’d share my super simple example with you today, and see if anyone wants to claw my eyes out for my obvious inadequacies.

Everyone seems to have a ContextSpecification class, but nobody really seems to think it’s terribly important to say what’s in it. That or they show the code (Thanks JP!) but then it’s missing confusing pieces (What’s a “unit_test_container”? Grr @ JP!).

Maybe it’s obvious to everyone else. That’s ok. It really really wasn’t to me.

I ghetto-rolled a ContextSpecification class for myself on top of NUnit. It probably makes the BDD Mafia want to set fire to my children, but it has worked for me. And when I say it has worked for me, I mean I’ve been using it at least 2 hours now. Here it is:

[TestFixture]
public abstract class ContextSpecification
{
    [SetUp]
    public void SetUp()
    {
        EstablishContext();
        Because();     }

    [TearDown]
    public void TearDown()
    {
        AfterEachSpecification();
    }

    protected abstract void Because();
    protected abstract void EstablishContext();

    protected virtual void AfterEachSpecification()
    {
    }

    protected InterfaceType Dependency<InterfaceType>()
    {
        return MockRepository.GenerateMock<InterfaceType>();
    }

    protected InterfaceType Stub<InterfaceType>()
    {
        return MockRepository.GenerateStub<InterfaceType>();
    }
}

So the SetUp method calls EstablishContext() and Because(). Simple.

I was testing this stupid little PasswordService of mine, so I created a PasswordServiceSpecification that setup some mocking and stubbing using our friend Rhino Mocks 3.5 “Now with extra => operators”.

public abstract class PasswordServiceSpecification : ContextSpecification
{
    protected IPasswordService passwordService;
    protected IPasswordStrengthService passwordStrengthService;
    protected IPasswordHashGenerator passwordHashGenerator;

    protected override void EstablishContext()
    {
        passwordHashGenerator = Stub<IPasswordHashGenerator>();
        passwordHashGenerator.Stub(x => x.CalculatePasswordHash(string.Empty))
            .IgnoreArguments()
            .Return(Password.InvalidPassword);

        passwordStrengthService = Stub<IPasswordStrengthService>();
        passwordStrengthService.Stub(x => x.CheckStrength(string.Empty))
            .IgnoreArguments()
            .Return(PasswordStrength.Strong);

        passwordService = new PasswordService(passwordStrengthService,
            passwordHashGenerator);
    }
}

Ain’t she a beauty? That’s really not terribly important, but I wanted to show it, because I hate it when people assume that I don’t care about some bits of the code. Finally, we have actual specifications.

public class When_setting_a_users_password : PasswordServiceSpecification
{
    private Person user;
    private string newPassword;

    protected override void EstablishContext()
    {
        base.EstablishContext();
        user = Dependency<Person>();
        newPassword = "password";
    }

    protected override void Because()
    {
        passwordService.SetUserPassword(user, newPassword);
    }

    [Test]
    public void Should_check_the_password_strength()
    {
        passwordStrengthService.AssertWasCalled(x => x.CheckStrength(newPassword));
    }
}

I’m told that it’s relatively important for the Because to be a single line of code, and the Tests (Should_*) to be a single line of code. It makes sense to me because if it’s a single line of code then you’re explicitly stating “this thing causes this other thing”.  Of course I don’t want to be too dogmatic about that because I can see that becoming pretty clusterfracky when the Should_* gets complicated.

I have a problem though. I wanted to check and see if an exception is being thrown, so I happily wrote this test:

public class When_setting_the_password_on_a_null_user : PasswordServiceSpecification
{
    private string newPassword;

    protected override void EstablishContext()
    {
        base.EstablishContext();
        newPassword = "password";
    }

    protected override void Because()
    {
        passwordService.SetUserPassword(null, newPassword);
    }

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Should_throw_an_exception()
    {
        // Do Nothing
    }
}

Too bad it doesn’t work for beans. Since the Because() is called by ContextSpecification.SetUp(), the exception is caused before the test is actually run, so the ExpectedException(…) doesn’t catch the exception thrown in the Because(). I didn’t much like the syntax anyway, but I didn’t really know where to go from there.

I briefly forayed into capturing exceptions from Because’s, but then realized that was a horrible idea.

I emailed Jimmy Bogard about it, because he seems smart. He said he might blog a solution to my woes. Wouldn’t that be hot?

PS- Is it weird that I was a little scared to put Bellware’s name in my blog post, for fear of having my face melted off? I’m pretty sure I’m one of the “noname bloggers” though, so I think I’ll be ok.

PPS- Wow this code is really hard to read. I’m sorry about that. Anyone want to recommend a syntax highlighting code snipped plugin for livewriter that plays nicely with WordPress?

use Lingua::Romana::Perligata;

Lingua::Romana::Perligata, when Perl is just too readable.

#! /usr/local/bin/perl -w

use Lingua::Romana::Perligata;

maximum inquementum tum biguttam egresso scribe.
meo maximo vestibulo perlegamentum da.
da duo tum maximum conscribementa meis listis.

dum listis decapitamentum damentum nexto
    fac sic
        nextum tum novumversum scribe egresso.
        lista sic hoc recidementum nextum cis vannementa da listis.
    cis.

Restrict Action to a Particular Type of HttpRequest in Castle MonoRail

This is one of those things that apparently everyone just knows, but I didn’t, and haven’t, for the past 3 months of doing MonoRail development. Color me stupid. Hopefully someone else out there can benefit from this.

If you want to restrict a certain action to only be available via a particular type of http request (POST, GET, etc), all you have to do is add an AccessibleThrough attribute to your action, like so.

[AccessibleThrough(Verb.Post)]
public void Delete(int id)

Yup, that’s it! I started down this path of parsing strings and case insensitive comparisons all the while thinking "This has got to be easier". Turns out it is.

FormHelper.Select with Enum

If you’re using Castle Monorail, and trying to use the FormHelper to create a form select janger from an enumerated type, you may or may not be confused as I was.  It’s not obvious, and I couldn’t find many good docs, outside of a forum post.

This is how to do it. First, you have to pass the Enum type into your view data (here: MemberRoles).

public void Edit([ARFetch("mid")] MembershipInformation membership)
        {
            PropertyBag["MemberRoles"] = typeof (MemberRole);
            PropertyBag["membership"] = membership;
        }

Then you have to wrange with FormHelper. I have a love-hate relationship with FormHelper. It can be really frustrating sometimes. Anyway, here’s the syntax for how to make your select statement.

$FormHelper.Select("membership.MemberRole",
    $FormHelper.EnumToPairs($MemberRoles),
    $DictHelper.Create("value=First", "text=Second"))

What FormHelper.EnumToPairs does is create an array of Pair<int, string> objects. The Pair<> object has 2 properties, First, and Second. First, in this case, is an integer with the enum value, Second is a string of the enum’s name. So you pass that bad boy into your FormHelper as the array of select thingies, and then tell it to use the "First" property as the value of the select and the "Second" as the text to display.

Magic!  Painful, painful magic! Maybe I should write my own FormHelper.EnumSelect thing.  Hrmm…

StringClob FTL

Found another Castle ActiveRecord/NHibernate gotcha today.

I had string columns being noisily truncated in my ActiveRecord types. Grr. I google and find a solution in the ActiveRecord FAQ: add a ColumnType="StringClob" to the property attribute.

[Property(ColumnType="StringClob")]
public String Contents
{
    get { return _contents; }
    set { _contents = value; }
}

Silly me though, I expected that to actually work as advertised. It doesn’t.

When you use ActiveRecord to create your schema, it will create the above column as a NVARCHAR(255). OMGWTFBBQ?!

The solution is to add an SqlType = "NTEXT" to your attribute as well.  Mmm, cryptic.

[Property(ColumnType = "StringClob", SqlType = "NTEXT")]
public string Description { get; set; }

Please refer to the following for further discussion of the issue.

Best Books EVAR!

I’ve been wanting to post a list of software engineering books I like, but, while I still may do so, some Jurgen Appelo fellow just posted a pretty good list to start off with, so huzzah for you.