C# tip: Touching brain with reflection

In the interest of speed, I’ll start with a list of truths I won’t be discussing at length:

  1. Some day you will need to address a problem in someone else’s libraries without the luxury of patching and recompiling their code.
  2. Most people know .NET reflection allows you to interact with types you didn’t have access to at compile time. It also allows you to interact with types you don’t have permission to directly address in code (internal classes, private members, etc.).
  3. .NET Reflector is an essential tool for any C# developer who uses someone else’s API. Which is everybody.

Using reflection to read members and invoke methods is easy:

  1. Get an instance of System.Type from your object. All objects have a GetType() method.
  2. Call Type.InvokeMember(), passing in the instance you’re wanting to manipulate as well as the name of the member and access flags.

Real-world

The XNA framework is a delightful graphics and games programming API by Microsoft, which is free (as in beer) but not open-sourced, and is officially unsupported. I play a bit with XNA and recently came across a serious performance killer in XNA 2.0 (which I’ve been assured is fixed in 3.0 final; forum post here and bug report here). Basically, there is a leaky dictionary embedded two internal classes deep that never gets cleaned up, framerate goes poop in a little while if you’re loading and unloading content like crazy.

So, inside the public GraphicsDevice class, there is an instance of an internal DeviceResourceManager, and inside this is the collection of internal ResourceData structs which never gets cleaned up. Once the content that’s being tracked has been disposed, its ResourceData instance can go away, so we’re going to periodically poke into this collection and flush items that are slowing down access to the collection.

In our code, we have easy access to the public GraphicsDevice. So, let’s get access to an instance of the internal DeviceResourceManager inside of it, which is a private instance named “pResourceManager”:

So, we have access to a private instance of DeviceResourceManager. Now, we go inside it in the same way to get the private collection:

Inside the class there is a sync object for locking as we address the dictionary, but now we know how to get access to that and use it. Then, we can iterate over the objects in our dictionary and remove the ones that are no longer in use.

That’s all the magic. Use this sparingly, as the performance of addressing objects via reflection is horrendous, and it’s always dangerous to subvert API access declarations. However, it might be just the thing that saves you in a pinch.

For the curious, the continued code for the XNA 2.0 leak work-around:
Continue reading C# tip: Touching brain with reflection

Davidson Half-marathon


All out at the Davidson half-marathon finish
(thanks to Jeri for picture)

Fun race last weekend in Davidson. Most of Crazy Legs showed up and we even got a few age group awards. I was 13th overall with a 1:25:35, good for an age-group second in my first race in the 35-39 group (congrats to fellow CL Paul Gonzalez for getting first about a minute ahead; I was no match for him in on the hills).

C# tip: Dependency Injection on the cheap

I want to keep this post short, so I won’t go into why you should design your code around interfaces, or why injecting dependencies at runtime is such a good idea. Rather, if you’re using .NET and want to quickly use Dependency Injection in your design, but are hesitant to adopt yet another framework (like Spring.NET, which I heartily recommend) for whatever reason, look to System.Activator.

In the way I usually use Activator, you need:

  1. The path to the assembly containing your implementation. The magic here is that you don’t need this referenced anywhere in the original application (you know, Dependency Injection and all).
  2. The name of the implementation class you want to load. I’m actually going to traverse all of the types in the injected assembly, which isn’t necessarily the most secure or efficient way to do things, but it is convenient and works well.

Namespaces used:

  1. System.Activator, to create the instance from a loaded assembly
  2. System.IO.FileInfo, to conveniently get the full path to the assembly you want to load
  3. System.Reflection.Assembly, to load your assembly (inject the dependency) into the current app domain

Some code:

Now, as I said before, look into using a lean, established, flexible, robust DI framework like Spring. However, if that’s not an option for whatever reason, you can still build your apps around a nice DI pattern. Future migration to Spring will be a snap.

Blue Ridge Relay 2008

Last weekend was the Blue Ridge Relay, which is 209 miles and 24+ hours of sick quad- and hamstring-bashing. Our Crazy Legs team showed up with a full twelve-person roster, and pulled out an impressive seventh-place (out of 75+ teams) in 26:45.


The view from “Goat Hill”, somewhere in the Blue Ridge Mountains

I ran position eight, with a first leg of 4.5 miles (moderately hilly), which I tried to run at my 5k pace. My overnight leg was 8 miles (nightmare dark mountain up, up, up, then screaming down), during which I experienced repeated heartburn worse than any college beer and wings episode. A sunburn and a general lack of sleep during the preceding week almost got the better of me before the night run, but passing a bunch of people delivered enough oh-so-lovely adrenaline to keep the feet turning over.


Mike “Goat” Smith cranking Goat Hill

At the top of Goat Hill, I got the hand-off for my last leg, which was 9.4 miles downhill with over 2000 feet of descent. I cranked it as best I could, averaging sub-6s. My quads were destroyed for a week.

Prior to downhill bash (thanks Cheryl for the pic)


Coach Tino rounding the corner for the finish

The finish was in downtown Asheville. Luckily, the downtown Y allowed participants to shower afterward, so everyone was able to survive the ride back to Charlotte.

Two vans’ worth of Crazy Legs

I’d go on about how fun the team was, but it would mostly be “you had to be there” stuff. Which, of course, is what makes these sorts of things worthwhile. I fully expect to run this event again, probably with much the same crew, and preferably as an ultra team (running more, but avoiding all the waiting around). Also, I’ll get more than three hours of sleep the night before the race next time.

I have a bunch more pictures at this link, and Mike’s Flickr archive is at this link.