TELL WORDPRESS “IMPORT FROM DASBLOG”

You have been killed by a grue.

Update: donning my anti-grue kit (XSLT and Emacs), I have managed to resurrect the old posts. Much rejoicing and broken HTML.

Posted in Blogging | Tagged , , , | 2 Comments

Can haz pluginz?

require 'rubygems'
require 'active_record'

class ActiveRecord::Base
  class << self
   def method_missing_with_lol(sym)
     if sym.to_s =~ /^can_haz_(w+)?/
       send "acts_as_#{$1}"
     else
       method_missing_without_lol sym
     end
   end
   alias_method_chain :method_missing, :lol
 end
end

class Lulz < ActiveRecord::Base
  can_haz_state_machine?
end

Temporary solution for Aaron’s problem, anyway. ;)

Posted in Code, Ruby | Tagged , , , | Leave a comment

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.

Posted in Gaming, Magic: the Gathering | Tagged , , | Leave a comment

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.

Posted in Computing | Tagged , , , , | Leave a comment

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 \\.\\DEVICE1rnParameter 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 SettingsThomMy DocumentsVisual Studio 2005ProjectsSpacewarSpacewarProgram.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…

Posted in Computing | Tagged , , , | Leave a comment

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 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(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.

Posted in C#, Code, Programming | Tagged , , , | Leave a comment

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. :)

Posted in C#, Code, Programming | Tagged , , , , | 2 Comments

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

Posted in C#, Code, Programming | Tagged , , , | Leave a comment

ObjectSpaces Xml Documentation

Does anyone else have System.Data.ObjectSpaces.xml in their Frameworkv2.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

Posted in Programming | Tagged , | Leave a comment

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?

Posted in Reading | Tagged | Leave a comment