Enumerating Registered Components in Windsor

Today I had occasion to want to know what’s in my IoC container (mine being Castle Windsor).

I poked and prodded to no avail, and finally ended up asking the Castle Project Users Google Group. The illustrious Hammet replied pointing me in the right direction, and this is what I ended up with:

public void LogComponentsInContainer(IWindsorContainer container)
{
    INamingSubSystem naming = container.Kernel.GetSubSystem(SubSystemConstants.NamingKey) as INamingSubSystem;
    foreach (var handler in naming.GetHandlers())
    {
        Log.Debug("Registered on IoC: {0}, {1}, {2}",
            handler.ComponentModel.Name,
            handler.Service.FullName,
            handler.ComponentModel.Implementation.FullName);
    }
}

It’s kinda icky, but it got ‘r did. I just wanted to log the registered components on startup so I could debug a silly Binsor issue.

Mocking Out RedirectToReferrer in Castle MonoRail

GRRRRRRRRRR!

In my version of the trunk I’m working against, r5299, I had to do this to mock out RedirectToReferrer. I think it’s been changed in recent commits, I’m not sure.

[TestFixture]
public class LoginControllerTests : GenericBaseControllerTest<LoginController>
{
    private string referrer = "http://www.example.org";
    protected override IMockRequest BuildRequest()
    {
        var request = new StubRequest(Cookies);
        request.UrlReferrer = referrer;

        return request;
    }

    protected override IMockResponse BuildResponse(UrlInfo info)
    {
        var response = new StubResponse(info,
                                        new DefaultUrlBuilder(),
                                        new StubServerUtility(),
                                        new RouteMatch(),
                                        referrer);
        return response;
    }

etc. etc.

It’s oddly the Response that you need to molest to get the RedirectToReferrer to work. I had to crawl around in the monorail sources to figure it out.

Cheers!

With.Timeout

So Tim Erickson and I have been going round and round on Twitter about how to add a generic Timeout mechanism to procedure calls.

Tim wants to wrap a using block in some sort of dark CLR magicks involving things I’ll probably never understand. I’m much less clever, so I opted for stealing the crap out of Oren’s syntax for his fabulous With.* stuff in Rhino.Commons.

This is what I ended up with:

public class With
{
    public static void Timeout(Action action, int timeoutInMilliseconds)
    {
        var latch = new AutoResetEvent(false);
        var asyncResult = action.BeginInvoke(ar => latch.Set(), null);

        latch.WaitOne(timeoutInMilliseconds, false);

        if (!asyncResult.IsCompleted)
        {
            throw new TimeoutException("The specified Action has timed out.");
        }

        action.EndInvoke(asyncResult);
    }
}

And tests/examples:

[TestFixture]
public class WithTimeoutTests
{
    [Test]
    public void ShouldPerformAction()
    {
        var actionWasPerformed = false;
        With.Timeout(() => actionWasPerformed = true, int.MaxValue);

        Assert.That(actionWasPerformed, "Action Was Not Performed.");
    }

    [Test]
    [ExpectedException(typeof(TimeoutException))]
    public void ShouldTimeoutLongOperation()
    {
        With.Timeout(() => Thread.Sleep(int.MaxValue), 1);
    }

    [Test]
    [ExpectedException(typeof(Exception))]
    public void ShouldPassThruThrownExceptionsFromAction()
    {
        With.Timeout(delegate { throw new Exception("Test"); }, int.MaxValue);
    }

    [Test]
    public void StupidUselessTest()
    {
        var timeout = 100;
        for (int i = 0; i < 100; i++)
        {
            try
            {
                With.Timeout(() => Thread.Sleep(timeout), timeout);
                Console.WriteLine(i + " Did Not Timeout");
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(i + " Timed out");
            }
        }
    }
}

I’m anxious to see Tim’s solution. I’ve gotten a lot more used to it, but the anonymous delegate/lambda syntax in C# still bugs the crap out of me.

import Rhino.Commons from Rhino.Commons

Holy Frakin’ Frakity Frak!

Perhaps it’s my own fault for using Binsor without being familiar with Boo, but I just ran into a doozy of a PITA.

I was trying to add an ThreadSafeQueue from Rhino.Commons into my container, but Binsor kept complaining that IQueue and ThreadSafeQueue were invalid identifiers. I had done an “import Rhino.Commons” but that wasn’t working.

Two hours and much yelling later, I discovered that since there is a Rhino.Commons is in multiple DLL’s, I have to specify which Rhino.Commons namespace of which individual DLL (in this case Rhino.Commons.dll) to import into my Binsor script like so:

import Rhino.Commons from Rhino.Commons

Friction.

Btw- I can’t thank Oren enough for releasing the Rhino.Tools/Commons/Whatever. ThreadSafeQueue is something I used a lot in Java (well BlockingQueue), then I come to .NET land and there’s nothing like it in the stdlib.  Der fick?

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!