Thom Lawrence

NHibernate-friendly Types

September 11, 2006 · No Comments

It’s probably a combination of laziness and plain bad form to try and map too many BCL types to your database, but if you’re interested, I’ve gone through a few important assemblies and compiled a list of classes that:

  • Are visible outside their assembly
  • Are neither abstract nor sealed
  • Are non-generic
  • Have a public or protected parameterless constructor

My assumptions might be wrong here, but I expect this to be enough for NHibernate to be able to save objects of those classes, and more importantly load and proxy them.

This is the list: PersistableTypes.txt. And here’s the code:

class Program
{
        static void Main(string[] args)
        {
            foreach(string assemblyName in GetAssemblyNames())
            {
                Assembly assembly = Assembly.Load(assemblyName);
                Type[] types = assembly.GetTypes();
                foreach (Type t in types)
                {
                    if (IsProxiable(t))
                        Console.WriteLine(t.FullName);
                }
            }
        }

        private static string[] GetAssemblyNames()
        {
            return new string[]
            {
                "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
                "System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
                "System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
                "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
                "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
                "System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            };
        }

        private static bool IsProxiable(Type t)
        {
            return !t.IsAbstract && !t.IsSealed && t.IsVisible && !t.IsGenericType
                && HasProxiableInitializer(t);
        }

        private static bool HasProxiableInitializer(Type t)
        {
            return Array.Exists(t.GetConstructors(),
                IsProxiableInitializer);
        }

        private static bool IsProxiableInitializer(ConstructorInfo ctor)
        {
            return ctor.GetParameters().Length == 0 &&
                (ctor.IsPublic || ctor.IsFamily);
        }
    }

Should be some fun stuff in there - I wonder if a Web Form and the complete hierarchy of its controls can be persisted nicely?

→ No CommentsCategories: C# · Code · Programming
Tagged: , , ,

ObjectSpaces Xml Documentation

September 11, 2006 · No Comments

Does anyone else have System.Data.ObjectSpaces.xml in their Framework\v2.0.50727 directory?

I’ve never had the ObjectSpaces bits on this machine, so I assume this is just a standard bit of cruft that comes with the framework.

Anyhow, I know Paul Wilson drew a lot of inspiration from ObjectSpaces, and while the documentation’s mostly filler text, I thought I’d attach it here just incase nobody’s noticed this historical footnote hanging around on their machine.

System.Data.ObjectSpaces.xml

→ No CommentsCategories: Programming
Tagged: ,

Amazon PhD’s In User Land

September 7, 2006 · No Comments

Hello, sir! So you’d like to buy a book?

Perhaps you’d like a list of Statistically Improbable Phrases (SIPs) to inform your choice:

obj ectdatasource, dui ante, horrible chemical taste, same master page, most active threads, polls module, ascx user control, forums module, articles module, custom base class, active polls, int votes, model design pattern, sitemap file, ect base class, poll box, specified poll, object sender, persistent shopping cart, custom configuration section, membership module, aspx page, designing the database tables, querystring parameter, skin file

Anything take your fancy? No? Can I tempt you with some Capitalized Phrases (CAPs)?

Visual Studio, News Header, The Beer House, Web Parts, Parameter Name, Template Monster, Tools Help Back, Cancel Figure, Property Description, Server Explorer, Server Express, Page Language, Smart Tasks, Edit Profile, Column Name, Error List, Marco Bellinaso, Application Extension, Databound Databound Databound, Ready Figure, Solution Explorer, Edit Delete Select, Register Src, Internet Explorer, Generate Local Resource

I’m sure sir can agree that with a Fog Index of 14.0 and a comfortable 1,350,320 characters, this would be a fine addition to any bookshelf.

Still not interested?

Sir?

Sir?

Sigh. What does that always happen?

→ No CommentsCategories: Reading
Tagged:

Safety! Implicit Operator!

August 16, 2006 · No Comments

Despite all the effort involved, operator overloading in C# is a nice syntactic hug you should always try and give your code. While that usually just gets you a bunch of boring comparison operators which you are forbidden to use in interesting ways, there’s other stuff too. Obviously C#’s not quite as flexible as Ruby, where you just seem to be able to mash the keyboard with your hands, and define a ‘mash hands with keyboard’ method on your class that gets called when the mashing occurs, but it does have something interesting in the implicit operator.

The implicit operator is what C# uses when you try and cast an object to another type. Normally you’d just go (Foo)bar to get yourself a Foo, which is what the stinky explicit operator lets you override. But if you don’t specify the cast, you can just write foo = bar. If the two types don’t match, everything explodes… unless you’ve written yourself an implicit cast operator:

public static implicit operator Foo(Bar bar)
{
    return Foo.FromBar(bar);
}

This is basically overriding the assignment operator, right? Well, unfortunately you can’t override the very important case of assigning a Foo to a Foo, or a Bar to a Bar. But everything else is fine.

Suddenly, it’s really easy to introduce Whole Values into your system. If you’ve been using strings to keep postcodes, you could write something like:

class Postcode
{
    private static readonly Regex _pattern;
    private string _postcode;

    static Postcode()
    {
        _pattern = new Regex(
            "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z-[CIKMOV]]{2}$",
            RegexOptions.Compiled);
    }
    private Postcode(string postcode)
    {
        _postcode = postcode;
    }

    public static implicit operator Postcode(string postcodeString)
    {
        return Parse(postcodeString);
    }

    public static implicit operator string(Postcode postcode)
    {
        return postcode == null ? string.Empty : postcode._postcode;
    }

    public static Postcode Parse(string postcodeString)
    {
        Match match = _pattern.Match(postcodeString);
        if (match.Success)
            return new Postcode(match.Value);
        else
            throw new FormatException("Invalid postcode");
    }
}

And now you can say:

Postcode postcode = Console.ReadLine();
string postcodeString = postcode;

Now you have some validation, a named type that better describes what we’re modelling, and we still get to keep using strings when we need them.

But we can add even more into that little ‘=’ operator. Joel spolsky uses turbo mega Hungarian notation to stay safe. Here’s how we can do it in C#:

class SafeString
{
    private bool _safe = false;
    private string _value;

    private SafeString(string value)
    {
        _value = value;
    }

    public static implicit operator SafeString(string value)
    {
        return new SafeString(value);
    }

    public static implicit operator string(SafeString value)
    {
        if (!value.Safe)
            throw new SecurityException("String has not been cleaned");

        return value._value;
    }

    public void Clean()
    {
        // Strip nasty characters!
        _safe = true;
    }

    public bool Safe
    {
        get { return _safe; }
    }
}

Now we can’t get the string back out until we clean it:

private static string ReadUnsafe()
{
    Console.Write("Do Your Worst: ");
    SafeString safe = Console.ReadLine();

    try
    {
        return safe;
    }
    catch (SecurityException)
    {
        Console.WriteLine("Unsafe!");
        return null;
    }
}

That’ll break every time, you don’t have to look at any weird variable prefixes or anything. You just have to do this:

private static string ReadSafe()
{
    Console.Write("Do Your Worst: ");
    SafeString safe = Console.ReadLine();
    safe.Clean();
    string value = safe;
    Console.WriteLine("Safe!");
    return value;
}

I’m not saying this is ground-breaking stuff, and it doesn’t do anything you couldn’t do with methods named FromSomething and ToSomething (which the MSDN article at the top asks you to do anyway). But when you find yourself pumping out ints, strings and such like there’s no tomorrow, remember that you have a simple way to capture that information into something more meaningful. Plus, ‘public static implicit operator’ sounds dead clever, right?

→ No CommentsCategories: C# · Code
Tagged: , , ,

Home

August 10, 2006 · No Comments

Having had the best day ever at work, it was enhanced even more when for some reason (random stock photography, presumably) Joel Spolsky plonked a picture of the Canterbury Starbucks in one of his articles on management styles. It’s a lovely, twisty old building next to the entrance of the cathederal, with many comfy nooks and crannies. But despite Joel’s praise of Starbucks’ system, I’ve never got a cup of coffee there in under ten minutes.

→ No CommentsCategories: Food & Drink
Tagged: , ,

You Know, For Men

August 5, 2006 · No Comments

Coca-Cola Zero. It’s Diet Coke, but for men. It even comes in a penis-shaped bottle. I’m not sure I get it, but it sure is manly.

→ No CommentsCategories: Food & Drink
Tagged:

Linux ThinkPads, Again

August 5, 2006 · No Comments

DesktopLinux.com hails Lenovo’s decision to preload SUSE on its T60p as a breakthrough:

For years, the holy grail of the Linux desktop has been to get a major computer vendor to commit to preloading a Linux desktop. It finally happened.

Actually, it happened in around 2000 (as Steven J. Vaughan-Nichols probably could have read in the article he helped write on eWeek), when IBM was boasting hardware certification from Red Hat and offering Caldera OpenLinux on its A and T series laptops. You can see an archive of IBM’s Linux ‘Software Alliances’ page.

Either way, why’s this such a big issue? Either they’re saying:

  1. People who want Linux don’t know how to install it or can’t do it quickly, which isn’t true.
  2. They can only give good driver support by pre-loading a customised distro, which you’d hope in 2006 would be doubtful.
  3. They are going to offer exceptionally good desktop support for Linux, which could well be true.

But none of these is a particularly Earth-shattering kaboom. I find it hard to believe that Linux ThinkPads being available again (to people who can’t be arsed installing Linux on one themselves, or buying in volume) could change the PC landscape as much as, say, Intel Macs, despite the ongoing mythology that Linux is really, really, everso close to conquering the desktop this time.

→ No CommentsCategories: Computing
Tagged: , ,

Sci-Fi/Fantasy Cartoon Classics

July 19, 2006 · No Comments

Wing Commander: Academy turns out to be the best science fiction cartoon series ever, with classic overacting from Mark Hamill, Malcolm McDowell, Tom Wilson et al, battling the evil Kilrathi in the classic WC1/WC2 era.

Conan the Adventurer remains my favourite fantasy cartoon of all time, although I’ve made no effort to find it on BitTorrent, so it might actually be rubbish. I remember it fondly though.

→ No CommentsCategories: TV
Tagged: , ,

Kevin Bacon

July 19, 2006 · No Comments

It seems that one of the central rules of the 15-minute project is that nothing is ever shameful. So I will try not to lose sleep over this next thing.

If time had allowed, I wanted to create a complete solver for the Kevin Bacon game. You know, that thing where you pick two actors and try to work out the films that connect them. Well, this doesn’t do that. I had some code in a console application that I thought did it (it’s just a simple breadth-first search, right?), but it quickly got itself in an infinite loop and died. So I got rid of that, having already spent more than the 15-minutes I allotted myself, and you’re left with this.

If you extract everything and then find and run WindowsClient.exe, you should be able to enter an actor or actress’s name and click on the toolbar icon next to it. Double clicking their name gets their films, double-clicking a film gets its cast, and double-clicking members of the cast gets their films. And so on. It’s all driven by some dreadful screen-scraping of IMDB, and doesn’t cope at all well when your search matches multiple actors (or none at all).

I’m sorry. This is a form of therapy.

→ No CommentsCategories: C# · Code · Programming
Tagged:

Limone!

July 19, 2006 · No Comments

This should be bearable, no?

I’m not really a holiday kind of person. I don’t find it hard to relax at home, I just need TiVo and the interweb. And maybe some wine. We have a balcony, and with the Sun lately and my new olive tree, you can sort of screw your eyes up and imagine you’re around the Mediterranean. But somehow every other person we know has been to Lake Garda, and they all think it’s grand. So while it makes me feel unoriginal that everyone else in the world seems to have been there, I’m pretty excited.

All I have to do is not worry about work.

→ No CommentsCategories: Travel
Tagged: ,