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.

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

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.

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.

Safer C# String.Format()

Formatting strings using the String.Format method is straightforward and efficient, but there is a loose coupling between the number of replaceable tokens in your string and the number of strings you provide to insert. If you get the count wrong (which can often happen during maintenance cycles as strings change), your code must deal with an exception. This all gets worse when your strings come from localized resources, as this opens the door for many more errors.

Ideally, I’d like to be able to catch all bungled calls in testing. As a rule I don’t like eating exceptions, but as a quicker stop-gap solution I opt to wrap the calls to String.Format with an unhandled try/catch and rovide a hard-coded fall-back string that I know will keep the code from failing.