C# Enum Type Automatic-Figure-It-Out-er

I want this:

public enum MeowSound
{
  Angry = 1,
  Happy = 2
}

public class Cat
{
  public void Meow(MeowSound meowSound)
  {
    // Do stuff
  }

  public void AngryMeow()
  {
    // Meow(MeowSound.Angry) // I don't want this.
    Meow(Angry);  // I want this.
  }
}

That is all.

Coding on ADD

Pennies by Beige Alert. A shiny penny can distract me and totally derail my productivity for tens of minutes. Shiny pennies come most commonly in the form of a tweet.

I take a lot of steps to reduce the shiny pennies I’m exposed to.

  • I set my IM clients to not beep and flash and explode on every new message.
  • Email clients are forbidden from actively notifying me of new messages (I use Gmail anyway, so really it’s a factor of not installing those popup email notification things)
  • Twhirl, my current twitter client of choice, only notifies me on direct messages or replies, not Every. Single. Tweet.
  • I tend to put my phone on vibrate when coding.

After making that list I already forgot why I was writing this blog post, I had to go and look at FireFox to remember.

Even with all those measures, I am still going to get distracted by things, especially since I work from home. It’s important that I am able to get back on topic just as easily as I get distracted. When I get distracted, I tend to forget everything I was working on. After I clear the distraction, I switch back to visual studio and it’s like looking at a blank wall. I generally have no idea what I was working on.

There are a few things I do to combat this.  Firstly, I keep a sheet of paper next to my mouse that I use to write down what I’m currently doing at quasi-regular intervals. Nothing high level, just enough to jog my memory as to what I’m working on. “Add Submit Button to UI”, “Create IFoo Interface”, no details, just something I can glance over, find out where I am, and I can check off as I work. It’s not a list of what I need to do, it’s a list of what I’m doing.

Second, I installed TabMixPlus. It allows you to mark a tab as “Protected” so that you can’t close it, you can also lock a tab so that it can’t navigate away from a URL. I just installed it, but I intend to protect and lock the tab of the current ticket/story/bug/whatever I’m working on, so I can always have that point of reference in addition to my little page.

I’m going to get distracted, that’s a given, but having a set of techniques to let me get back to work as quickly as possible helps alleviate some of the productivity drain.

Vote: Consider Thyself Thoroughly Rocked!

I voted. SO HARD.

Actually I voted a couple weeks ago. But yeah! Voting! Awesome!  My first time evar.

Now for fun I am going to cast voting and government into the framework of a Genetic Algorithm. I’m going to draw heavily from Wikipedia, because I’m pretty sure all my other better references are… well god only knows, but it should suffice. Who needs scientific rigour?

Let’s begin with a simple genetic algorithm’s psuedocode:

    1. Choose initial population
    2. Evaluate the fitness of each individual in the population
    3. Repeat until termination:
      1. Select best-ranking individuals to reproduce
      2. Breed new generation through crossover and/or mutation (genetic operations) and give birth to offspring
      3. Evaluate the individual fitnesses of the offspring
      4. Replace worst ranked part of population with offspring

Let’s simplify and assume that our initial population are the founding fathers (Denoted), our George Washingtons’s and Benjamin Franklin’s, etc. Our iterations thusly begin. Let’s define our political population as G. Then for G we can define a fitness function F(G) that evaluaties to a vector of approval values. The interesting part comes when we think about what that function would actually look like. One term is sort of a differential equation: the popularity today depends on your popularity yesterday + what you did yesterday. Oh and the differential term could also depend on the people you surround yourself with!  It could be the heat equation with political proximity instead of spatial proximity! F would also need to a sigmoid function to account for term limits… let’s not go down this road.

Anyway, so we have a fitness function. Now we need to select our new generation. We need to vote. When we vote we’re evaluating the F(G). Once that function is evaluated, some government Machina takes the result vector and applies it to remove the unpopular and instate the popular.

This is the awesome part about our government. The process starts all over again. If the people we elect suck, we chunk ‘em to the curb, all “The fitness function has indicated you are no worthy to continue breeding”. The breeding aspect of our genetic algorithm can be cast into the framework of ideas mixing, breeding, the world evolving, people’s will being echoed through their elected representatives, all that cool shit.

Ok, from a scientific rigour standpoint, this argument sucks, but it’s fun to consider.

Vote for someone awesome today!

Windows LiveID an OpenID Provider

Microsoft is going to support the open standard OpenID by making LiveID an OpenID provider. Say Whaaat?!

Who are you and what have you done with our Microsoft?!

Windows Azure

I’m watching the PDC 08 keynote on Windows Azure, and it’s pretty cool. The speakers are kind of horrible, and the product demos were pretty crappy, but I get the idea. This is big.

Windows Azure, for all the bad presentation, is going to be really cool. I’m sure everyone and their dog is going to talk about specs and technologies, so I won’t bother with that.

An interesting thing caught my eye, they mention how it will be accessible to hobbyists all the way to enterprise customers. An interesting thing about the cloud platforms, Google App Engine, Amazon EC2, and now Windows Azure, is that it causes smalltime developers and bigtime developers to collide.

Hobbyists don’t typically have access to enterprise class resource, SANS, Racks upon Racks of Blade Servers, etc. etc. Now we have a unified platform for deploying my recipe catalog as well as an enterprise accounting system. The value for the small fish is that they don’t have to deal with managing their own servers. For the big fish, the value is the near infinite scalability the platform provides through a commoditization of a lot of technology and knowledge in horizontally system scalability.

The small fish can get away with a hosting company, but for startups, knowing that the systems they build can scale through their (hopeful) successes…  That’s pretty big.

NH-1520 or: Oren is a Machine

Please direct your attention to http://jira.nhibernate.org/browse/NH-1520.

It’s a simple bug, annoyed me a few months back, but I didn’t get a chance to investigate further until recently, when I was reminded of it by someone posting on the Rhino Tools Dev Google Group who was experiencing similar pains.

The impressive thing to notice about this JIRA are the timestamps.

  • 4:35PM Reported
  • 4:40PM Ayende Accepts Ticket
  • 4:43PM Fixed
  • 4:45PM Closed

That, my friends, is open source. And further proof that Oren isn’t quite right. I think he may be a set of triplets, masquerading as a single person.

Let’s all take a moment to thank our open source contributors and maintainers. They rock so hard.

Capture.Exception - BDD-esque w/ NUnit or: The Ikea Nightstand

UPDATE: After some feedback from Scott Bellware, Check below for the updated version.

I’ve been experimenting with BDD (or at least a BDD-inspired syntax, so as not to invoke the rage of the BDD mafia). I wove my own Spec class on top of NUnit back in this blog post. If you recall, I had encountered a problem however:

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

This code doesn’t work. If I’m testing an error, and my Because throws the error, it asplodes. The exception isn’t generated in the [Test], it’s generated in the [SetUp] and NUnit doesn’t like that.

I was irritated. So I hacked something together. Something dark and horrible.

public class When_adding_a_null_Node_to_a_Graph : FeatureSpecification
{
    private CapturedException capturedException;

    protected override void Because()
    {
        capturedException = Capture.Exception(() => graph.AddNode(null));
    }

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Should_throw_an_exception()
    {
        capturedException.ReThrow();
    }
}

It’s a little… malevolent. But it works, and well, that’s ok with me. My ivory tower is more like an ivory nightstand. I put my phone on top of it, and my keys, and there’s a lamp with a cute picture of a kitten chewing on a puppies ear. And it’s not ivory, it’s Ikea.

So what powers my Ikea Nightstand? This:

public static class Capture
{
    public static CapturedException Exception(Action action)
    {
        var asyncResult = action.BeginInvoke(null, null);
        asyncResult.AsyncWaitHandle.WaitOne();

        return new CapturedException(action, asyncResult);
    }
}

public class CapturedException
{
    private Action action;
    private IAsyncResult asyncResult;

    public CapturedException(Action action, IAsyncResult asyncResult)
    {
        this.action = action;
        this.asyncResult = asyncResult;
    }

    public void ReThrow()
    {
        action.EndInvoke(asyncResult);
    }
}

I’m abusing just about everything here. CPS is going to knock on my door and ask me where my children are. My casual reply? “The wood chipper, where they belong.”

UPDATE: I GOT SCHOOLED!

Scott Bellware commented below about how I should just use an assert once I’ve captured the exception to make things more legible. Consider it done!

public class When_adding_a_null_Node_to_a_Graph : FeatureSpecification
{
    private Exception capturedException;

    protected override void Because()
    {
        capturedException = Capture.Exception(() => feature.AddNode(null));
    }

    [Test]
    public void Should_throw_an_exception()
    {
        Assert.That(capturedException, Is.InstanceOfType(typeof(ArgumentNullException)));
    }
}

And the accompanying new Capture.Exception():

public static class Capture
{
    public static Exception Exception(Action action)
    {
        try
        {
            action.Invoke();
        }
        catch (Exception e)
        {
            return e;
        }
        return null;
    }
}

Much simpler. Much cleaner. Much better.

Thanks, Mr. Bellware!

MEF, MS-LPL, MS-PL, IServiceLocator, Oh My!

Microsoft recently release the Managed Extensibility Framework on CodePlex under an open source license, the MS-LPL. There were some issues with the license selected for release, and it looks like Glenn Block spearheaded an effort to rerelease the MEF under a more permissive license, the MS-PL.

That’s pretty cool. From what I understand the MEF is this sort of service locating dll loading extensibility-fu framework. Here is a pretty simple introduction to it. It looks powerful.

Now, push that onto the stack, and think about JQuery being included in a release of MS software. Woah! Can you say, “Holy Crap!” because I can. Microsoft is including an open source library as part of various Visual Studio, ASP.NET MVC packages!  That’s frickin’ huge! I can’t think of any other open source library ever included in a Microsoft release.

Now, push JQuery onto the stack and read this. Microsoft collaborated with leaders of the open source community to jointly design and develop CommonServiceLocator, a shared interface for service locators/IoC Containers. Everyone writes one of these interfaces/static gateway doohickies at some point in time, so a single one jointly developed by the people who wrote our IoC containers with an apparent nod of support from Microsoft itself makes my head spin.

It’s a lot harder to blindly hate Microsoft these days. In a time when Apple is treating their development community like complete fecal matter, we have to acknowledge and recognize efforts by Microsoft to reach out to us, listen to us, and attempt to give us the tools we need to do our jobs.

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!