Deserializing interfaces with Json.NET

Using Json.NET with concrete types is very simple: Just give your object to JsonConvert.Serialize() and give your string to JsonConvert.Deserialize() to get back an instance. Wonderfully simple and convenient.

When you are working with your objects as interfaces, things are only a little more complex during deserialization. With simple objects can simply point the JsonConvert.Deserialize() method to an implementation of your interface. Otherwise, the framework does not have a concrete class to instantiate.

You can just call JsonConvert.Deserialize() to deserialize one of these.

However, what if there are multiple implementation types involved?

You need to tell JsonConvert about your implementation of IMyTransferType as well as the IMyInnerType, but JsonConvert.Deserialize only allows you to specify the parent-most type. To accomplish this, you just need to write simple custom converters. Simply create one class for each of your interface types, inherit from CustomConverter, and have its Create method return a new instance of an implementation:

Use a JsonSerializerSettings class with these classes added to its Converters collection when invoking the JsonConvert.Deserialize method:

Now, JsonConvert will know how to deserialize the child objects as well as the parent-most object.

Moving graphics with trigonometry

Notice: This is intended to involve only very basic concepts.

No matter the scope, most “game” programming these days involves moving pictures around on a computer screen, and performing this task can be very easy with a little basic math (specifically, trigonometry). Small two-dimensional graphics in games are usually called “sprites”, and in this exercise we’ll simply move a sprite.

We will be plotting a trajectory of a sprite across our screen, and to do this we keep track of

  1. the sprite’s position (a single point containing its X and Y coordinates),
  2. a velocity,
  3. and an angle at which to plot the distance the sprite travels.

Our game will draw the sprite to the screen as fast as it can, and we will know how much time has elapsed since the last time we drew the sprite. So, we will be provided the final number we need to plot our new sprite position: elapsed time.
We are calculating a distance vector, which is basically a line from one point to another. If our sprite’s velocity is five pixels per second, and one second elapses, it will travel a distance of five pixels. However, what is the new X,Y position of that point? It depends on the angle!

To calculate the amount along the X and Y axes our sprite has traveled, perform two simple calculations:

pointsAdd these values to the previous X,Y position of the sprite and you’ll have the new position of the sprite. The diagram assumes a starting position of (1,1), and shows two distance vectors: The red is with an angle of π/4 radians (or 45º from vertical), while the green is an angle of π/2 radians (or 90º from vertical). Both have the same velocity magnitude.

To add a little simple rebound off the sides of the screen, make sure that the X and Y coordinates of the sprite are not beyond the edges. For a screen 800×600 pixels, where directly up is an angle of 0, simple reverse the angle when the sprite goes off the left or right of the screen, and subtract the angle from PI when it goes off the top or bottom.

To slow the sprite down at a certain rate of deceleration, simply subtract from the velocity an amount that is multiplied by the elapsed time:

This isn’t the most accurate of physics demonstrations, but surprisingly advanced games can be built around calculations as simple as these.

Next we’ll discuss how to derive a distance from two points, and soon go over some handy linear interpolation.

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.


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

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.

Happy sandboxes and svn switch

I encourage everyone I work with to keep all of their development code in a source repository, even one-off dead-end prototype code they’re not going to check back into a main development tree. If you know you’re going to do destabilizing work, of course you’ll create a sandbox branch from the development branch and then do your work; we all know this. So, what happens if you inadvertently end up with a dead-end prototype in your working source checkout, and you didn’t have the foresight to start with a branch? It’s easy to make it as if you had.

Disclaimer: Of course, if this all fails you could lose a lot of work, so you might want to generate a quick diff or backup just in case. Just be careful.

  1. Create a development branch in our repository on the server. We are using Windows and TortoiseSVN, and our working code is from the branch at svn://svnserver/MyProject/Trunk at revision 1942. So, we use the Repo-browser in TortoiseSVN to find Trunk, select revision 1942 from the upper right-hand corner of the dialog, and then select “Copy to…” with a new location at svn://svnserver/MyProject/Sandboxes/bojordan/DeadEndPrototype. We now have a new branch, but our working code still belongs to Trunk.
  2. Right-click on my top-level checkout directory, select “Switch” from the TortoiseSVN options, and select the new branch in the “To URL:”. We know HEAD is fine, as we just created the new branch.
  3. Now, the next time we commit our code, we’ll check it back into the new branch. Glee!

Just remember: No more stale development tree archives on your development machines means cleaner, uncluttered living, and might get you one step closer to a 16 minute 5k. Or, maybe not, but you’ll still be happier.

C# tip: Formatting currencies

Another simple C# tip I keep forgetting: Need to format a decimal for a specific currency? What about only showing the whole dollar amounts? Use the Decimal.ToString() overload that takes a format string and a CultureInfo instance. Here’s how:

C# tip: Think of anonymous methods as static

Anonymous methods in C# can make your code more readable, and they are very convenient. They also have magic powers. For example, when first using them they appear to magically persist local variables! Magic, you say? To show this let’s create a delegate and assign a anonymous method to it, and within the anonymous method we access a local variable:

Magically, the value in local variable i is printed to the console! How does this happen? It’s not quite magic; a closure containing the variable is conveniently created on the heap for the anonymous method referenced by the delegate, giving our formerly stack-based value type a nice long life.

Warning: Prepare for disappointment if you expect to create multiple instances of an anonymous method, each with different version of local variables. Examine the following:

Contrary to what you might expect, the console does not print 0, 1, and 2. Rather, it prints 2 three times. Why? A single closure is created for an anonymous method in C# code, even if it is referenced multiple times. Therefore, think of an anonymous method (and the closure containing any formerly local variables it references) as static; any modification of the local variable is reflected anywhere it is referenced, even though it’s a value type and it’s modified after the anonymous method is referenced.

If you want different behavior, you must avoid using local variables and pass state into the method yourself. A struct containing the delegate and its data works nicely:

C# tip: Reading settings from a different App.config

If you’ve used a standard C# App.config, you’re familiar with the ConfigurationManager object in System.Configuration:

This reads, by default, from a file similar to your application’s executable; if your executable is “MyApplication.exe”, your config file is “MyApplication.exe.config”. If you want to read from a different file, or just name your config file differently, and still have the same convenience, you have a few options. First, you can use the exact code as before, but set a property in your app domain to reroute the static ConfigurationManager calls:

You can use a slightly different strategy that is almost as convenient, and may be more flexible in some situations. If your config file is named “SpecialConfig.config”, create an instance of Configuration from the ConfigurationManager as follows:

If the file does not end in “.config”, you need to create an ExeConfigurationFileMap and use a slightly different call:

You could get the value in a single line of code, but keep in mind you’re risking a null reference exception if the value isn’t present. To be safe, do something like the following:

C# tip: Checking for empty strings

A common task for any C# programmer is to check the contents of strings. Is a given string initialized, and if so, is it empty? Consider a common check:

This technically works fine, assuming the string was initialized. The following check is theoretically a little more memory-efficient, but is equivalent due to JIT optimization:

I personally think string.Empty is a tiny bit more readable than “”, but that’s subjective. Technically, checking the length of the string is the shortest code path:

Keep in mind that, while strings are special objects with an intern pool, they are objects nonetheless, and will be null references until they are initialized. Your code must take this into account, or you will be faced with sloppy null reference exceptions. One also could argue that code flow based on differences in null vs. empty strings is bad practice in the first place.

I believe using the string.IsNullOrEmpty() method is the best habit to form when checking strings:

Check explicitly for null or string.Empty only in special cases. Remember, good code habits are contagious.