Card of the Day#

If you're on a Mac and love Magic: The Gathering, you can use this Dashboard widget to view the card of the day from the Wizards site. Seeing as everyone's copy of Dashcode has expired now, I doubt I'll spend any more time on it. It's basically just an Ajax request from Prototype and a regex to find the image.

I sometimes wonder if Dashcode will morph into some hybrid iPhone IDE by the time Leopard comes out, if Apple still haven't relented and allowed developers access to the gadget's native innards. It was a fairly nice piece of software while it lasted, anyway.

Update: having said I wasn't going to spend any more time on it, Wizards have changed their HTML, so I've updated the regex. This should now work again.
8/15/2007 11:01:33 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  |  Trackback

 

Worst Update Ever#

So Parallels 3.0 has continued to frustrate me. I can forgive the XNA thing - seems just as likely to be Microsoft's fault. I filed a bug (or is it 'participated' in a 'connection'?) on the atrocious Connect site, which you can vote up if you like... a few people have come here from Google with seemingly the same problem.

It's not even that ActiveSync still doesn't work, removing the only other reason I really had to buy the upgrade. It's three things, really:

  1. My virtual machines occasionally take about a minute to resume.
  2. Tonight, Parallels decided to start corrupting my Windows XP disk image, leaving me with recursive bluescreen fun.
  3. I can't even repair it, because I can't work out how to make my install disc image bootable.

So it's been disappointing. Probably nobody's fault, but I really feel like going back to 2.5. Or trying VMWare and not having my fans on the whole time even if the VM's idle etc etc. Grr.

7/2/2007 8:31:00 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  |  Trackback

 

Parallels 3.0 & XNA Studio#

I enthusiastically upgraded to Parallels 3.0, hoping to enjoy its DirectX support. XNA Studio is one of the reasons this interests me - with my MacBook I'm not expecting to write or indeed play many 3D games, but you can't run XNA projects without acceleration. However:

System.ArgumentException was unhandled
  Message="The device name is not valid. Device names are in the form \\\\.\\\\DEVICE1\r\nParameter name: screenDeviceName"
  Source="Microsoft.Xna.Framework.Game"
  ParamName="screenDeviceName"
  StackTrace:
       at Microsoft.Xna.Framework.WindowsGameWindow.ScreenFromDeviceName(String screenDeviceName)
       at Microsoft.Xna.Framework.WindowsGameForm.ResizeWindow(String screenDeviceName, Int32 clientWidth, Int32 clientHeight, Boolean center)
       at Microsoft.Xna.Framework.WindowsGameForm.EndScreenDeviceChange(String screenDeviceName, Int32 clientWidth, Int32 clientHeight)
       at Microsoft.Xna.Framework.WindowsGameWindow.EndScreenDeviceChange(String screenDeviceName, Int32 clientWidth, Int32 clientHeight)
       at Microsoft.Xna.Framework.GraphicsDeviceManager.ChangeDevice(Boolean forceCreate)
       at Microsoft.Xna.Framework.GraphicsDeviceManager.Microsoft.Xna.Framework.IGraphicsDeviceManager.CreateDevice()
       at Microsoft.Xna.Framework.Game.Run()
       at Spacewar.Program.Main(String[] args) in C:\Documents and Settings\Thom\My Documents\Visual Studio 2005\Projects\Spacewar\Spacewar\Program.cs:line 16

Google doesn't seem to know a lot about this exception, but I'm hoping someone can help. I'm downloading the refresh of XNA studio from earlier this month, so that might fix everything. I've already wasted half an hour finding out that you have to actually edit your VM to enable DirectX support - it doesn't appear by magic.

The other thing that I couldn't get to work in previous versions of Parallels is ActiveSync, so hopefully I'll have more luck there. I'm not even on a trial - I am amazed at how reckless buying a Mac makes you with software purchases...

6/14/2007 8:52:38 PM (GMT Standard Time, UTC+00:00) #    Comments [4]  |  Trackback

 

Future Values With Castle's DynamicProxy#

.NET has lots of support for asynchronous processing, which ASP.NET packages up very nicely in PageAsyncTasks. And yet I almost always find an excuse not to use them - they're hard to test, it's not instantly obvious what the logic of the page is when you have delegates and handlers all over the place, and, like, most of my code is so amazing that all I need second thread to do is watch and applaud.

But I thought I'd try something slightly more usable. I like the idea of Future Values - basically they're a placeholder for a value that sits there nervously pretending to be the result of an asynchronous call. When you finally get round to using it, and if it's ready, the future will give you an answer and relax. If not, it'll block the thread and make excuses until it's finished. What's nice about this is that in many cases, the time between first getting the future and actually using it will be enough for the operation to complete, which means no blocking will happen and you won't notice anything. This is the logic behind PageAsyncTasks - there's lots for the ASP.NET runtime and you to do between Page_Load and Page_PreRender, so there's no point twiddling your thumbs. And if it does need to block, that's fine, but you haven't had to mess about so much with callbacks and stuff.

I wanted this to be as transparent as possible, and I'd never played with DynamicProxy before, so I thought it would be a good experiment. I basically wanted to come up with a solution to the following type of problem:

public class SlowService
{
public Result DoSomething()
{
Thread.Sleep(5000);
return new Result("Done!");
}
}

You know the sort of thing, some web service that goes off to calculate the answer to life, the universe and everything and all you've got is a spinny thing going ape in your browser while you wait. No more! Behold the AsyncProxyness:

public class AsyncProxy : IInterceptor
{
private readonly ProxyGenerator _generator = new ProxyGenerator();

public static T Create<T>(T target)
{
ProxyGenerator generator = new ProxyGenerator();
return (T)generator.CreateProxy(typeof(T), new AsyncProxy(), target);
}

public object Intercept(IInvocation invocation, params object[] args)
{
InvocationDelegate asyncInvocation = invocation.Proceed;
Type returnType = invocation.Method.ReturnType;
if (returnType == typeof(void))
{
asyncInvocation.BeginInvoke(args, delegate(IAsyncResult result) { asyncInvocation.EndInvoke(result); }, null);
return null;
}
else
{
IAsyncResult result = asyncInvocation.BeginInvoke(args, null, null);
Future future = new Future(asyncInvocation, result);
return returnType.IsInterface
? _generator.CreateProxy(returnType, future, Activator.CreateInstance(returnType, true))
: _generator.CreateClassProxy(returnType, future);
}
}
}

internal delegate object InvocationDelegate(params object[] args);

This allows you to create a proxy for a type, that turns all its methods (or at least the virtual or interface defined ones DynamicProxy lets you monkey with) into asynchronous calls. And instead of returning the result of the call, it gives you back a Future object that'll stand in for the result of the call until it's finished:

internal class Future : IInterceptor
{
private readonly InvocationDelegate _asyncInvocation;
private readonly IAsyncResult _result;
private object _invocationTarget;

internal Future(InvocationDelegate asyncInvocation, IAsyncResult result)
{
_asyncInvocation = asyncInvocation;
_result = result;
}

public object Intercept(IInvocation invocation, params object[] args)
{
if (_invocationTarget == null)
{
lock (this)
{
if (_invocationTarget == null)
{
object target = _asyncInvocation.EndInvoke(_result);
Thread.MemoryBarrier();
_invocationTarget = target;
}
}
}
invocation.InvocationTarget = _invocationTarget;
return invocation.Proceed(args);
}
}

Hopefully that double-checked lock is correct. Looks clever though, right? Anyway, all this says is that when someone finally needs to do something with the result of our slow call, we'll wait for the asynchronous delegate to finish (blocking if necessary) and then pass the method invocation through to the actual result of that call. Once that's done, the Future is just a completely transparent proxy for the returned object. This all allows you to do things like this:

class Program
{
static void Main(string[] args)
{
ISlowService service = AsyncProxy.Create<ISlowService>(new SlowService());
Console.WriteLine("Look, ma!");
Result r1 = service.DoSomething();
Result r2 = service.DoSomething();
Result r3 = service.DoSomething();
Console.WriteLine("No blocking!");
Console.WriteLine("Results: {0}, {1} and {2}", r1, r2, r2);
Console.ReadLine();
}
}

public interface ISlowService
{
Result DoSomething();
}

public class SlowService : ISlowService
{
public Result DoSomething()
{
Thread.Sleep(5000);
return new Result("Done!");
}
}

public class Result
{
private string _message;

protected Result() { }

public Result(string message)
{
_message = message;
}

public override string ToString()
{
return _message;
}
}

Which all seems to work. I've not tested or benchmarked anything, so don't trust me just yet. I should also point out that in DynamicProxy2, this won't work, because it relies on creating a delegate to point at the Proceed method of the interceptor. In the new version, an invocation and its return value are spread across bunch of properties instead of the easy-to-use one liner we currently have. But at the very least, we have here a really simple API to get you thinking about a cool pattern.

5/29/2007 7:20:53 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  |  Trackback

 

Perfidy: Performance Testing In NUnit#

Unsatisfied with calling QueryPerformanceCounter and being done with it, I spent today coming up with a fluent interface for performance testing in NUnit:

    using (At.Most(5).Seconds)
    {
        // Stuff that should take under 5 seconds
    }

    using (At.Most(1).Minute.GiveOrTake(10).Seconds)
    {
        // Stuff that should take under 70 seconds
    }

    Using.At.Most(10).Seconds.For(1000).Iterations.Do(delegate()
    {
        // Stuff that should take under 10 seconds for 1000 iterations
    });

    Using.At.Most(5).Seconds.For(20).Threads.Do(delegate()
    {
        // Stuff that should take under 5 seconds when run inside
        // 20 parallel threads
    });

It's basically a wrapper around NUnit's Assert.Less() and I call it Perfidy (which I thought was a good word for code that treacherously refuses to pass its tests). You can grab a very rough version here: Perfidy.zip

I suppose this kind of thing doesn't really qualify as unit testing, and it's not deterministic. But if you're fairly generous with the limits and get your tests up and running early in a project, you at least know vaguely where you're going to suffer.

I've not included any tests for the tests. I wasn't sure if NUnit gives you a way to say 'give me a green bar if this test fails', and to test everything takes a fair coffee break, as there are lots of Thread.Sleep()s around. If anyone spots anything obviously wrong, or knows of another library that does the same sort of thing, I'd love to hear about it. Especially if it has pretty syntax. :)

9/17/2006 1:29:19 AM (GMT Standard Time, UTC+00:00) #    Comments [0]  |  Trackback

 

NHibernate-friendly Types#

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<ConstructorInfo>(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?

9/11/2006 9:42:33 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  |  Trackback

 

ObjectSpaces Xml Documentation#

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

9/11/2006 9:03:58 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  |  Trackback

 

Amazon PhD's In User Land#

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?

9/7/2006 10:32:26 PM (GMT Standard Time, UTC+00:00) #    Comments [1]  |  Trackback

 

Safety! Implicit Operator!#

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?

8/16/2006 8:03:52 PM (GMT Standard Time, UTC+00:00) #    Comments [1]  |  Trackback

 

Home#

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.

8/10/2006 9:31:05 PM (GMT Standard Time, UTC+00:00) #    Comments [1]  |  Trackback

 

You Know, For Men#

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.

8/5/2006 11:58:32 AM (GMT Standard Time, UTC+00:00) #    Comments [1]  |  Trackback

 

Linux ThinkPads, Again#

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.

8/5/2006 5:41:36 AM (GMT Standard Time, UTC+00:00) #    Comments [0]  |  Trackback

 

All content © 2008, Thom Lawrence
On this page
Links
Calendar
<July 2008>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
Archives
Sitemap
Blogroll OPML
Interesting
 Ajaxian
 Alex Barnett
 Andres Aguiar
 Andrew Conrad
 Andrew Stopford
 Anil Dash
 Ben Hammersley
 Ben Riga
 Bird Flu Monitor
 Brad Abrams
 Brian Oberkirch
 Bubble 2.0
 Channel9 (Videos)
 Charles Petzold
 Chaz Blogs
 Chris Bilson
 Cliff Atkinson
 Code Better
 Coding 4 Fun
 Curt Rosengren
 Cyrus' Blather
 Dave Astels
 Dave Hoover
 David J. Anderson
 David J. Anderson (Articles)
 David Parmet
 Dimitri Glazkov
 Dinesh Kulkarni
 Doc Searls
 Doc Searls (IT Garage)
 Domain Driven Design (Yahoo)
 Doug Rohrer
 Edward Jezierski
 Eric Gunnerson
 Eric Lippert
 Eric Means
 Ethan Johnson
 Evelyn Rodriguez
 Extreme Programming (Yahoo)
 Fabrice Marguerie
 Fernando Daniel Simonazzi
 Fred Gratzon
 Fredrik Wackå
 Fritz Onion
 George MacDonald
 Hamish Newlands
 Hank Roark
 Harry Pierson
 Henry Blodgett
 Howard Mann
 Ian Cooper
 Ian Landsman
 Ingo Lundberg
 James Avery
 James Cherkoff
 James Winters
 Jeff Atwood
 Jeff Perrin
 Jelle Druyts
 Jennifer Rice
 Jobs Blog
 Joe Duffy
 Joel Pobar
 John Rusk
 Jon Tirsen
 Josh Ledgard
 Kevin Briody
 Krzysztof Cwalina
 Krzysztof Kowalczyk
 Lifehacker
 Marcus Perryman
 Mark Bower
 Matt Warren
 Matthew Adams
 Merlin Mann
 Mike Gunderloy
 Mini-Microsoft
 MS Mobiles
 Nick Bradbury
 Omar Shahine
 Oren Eini
 Paul Gielens
 Paul Stovell
 Paul Wilson
 Peter Bromberg
 Peter Merholz
 Raymond Chen
 Rick Byers
 Rico Mariani
 Ron Jacobs
 Roy Osherove
 Sam Gentile
 Sam Newman
 Sanaz Ahari
 Sara Ford
 Sascha P. Corti
 Scott Bellware
 Scott Berkun
 Scott Densmore
 Scott Guthrie
 Scott Hanselman
 Scott Mitchell
 Scott Watermasysk
 Scott Wiltamuth
 Seth Godin
 SharpDevelop
 Simon Harriyott
 Sivaramakichenane Somasegar
 Steal This Brand
 Steve Cook
 Steve Gillmor
 Steve Maine
 Steve Rowe
 Stuart Kent
 TestDriven.com
 To-Done
 Tom Evslin
 Tom Hollander
 Tom Krueger
 Vaderpi
 Wesner Moise
 Windows Mobile Team Blog
 Wojtek Kozaczynski