Writing rock solid code with Code Contracts
As we develop applications, services, databases and so on, we often find ourselves repeating some of the same tasks. Eventually such code often gets refactored into separate libraries that are then shared across multiple projects. The utility libraries.
I am currently developing and maintaining such a library at work, consisting of dozens of classes ranging from small simple data conversion classes to complex WCF extensions, enterprise wide logging, encryption and authentication mechanisms as well as several hundreds of language extensions, all in the effort to increase my productivity and that of my coworkers.
What bothered me was that even though most of the code is covered by unit tests and seems rock solid, I know in my gut that it’s not. Code cannot be rock solid, unless you clutter the code with endless Asserts, which are then difficult to handle downstream.
Imagine you have a WCF service and a consumer, an exception is thrown in the service because the service retrieved an invalid configuration value stored in a database. This is something that was never supposed to happen.
The exception gets automagically intercepted and wrapped up in a FaultException and passed along to the client (see my previous post).
Now, the client is forced to recognize and deal with an exception that the developer of the WCF service never anticipated. Not exactly rock solid!
So how can we then anticipate all possible scenarios and create contingencies for every conceivable thing that could go wrong, and make sure that the error is understood and intelligible downstream, in the client?
Consider the following class:
(If you are reading this in an aggregator and the source code appears without line breaks, consider reading it on the website instead).
public static class StringExtensions
{
public static string ReverseString(this string value)
{
string result = string.Empty;
for (int i = value.Length - 1; i >= 0; i--)
result += value[i];
return result;
}
}
It’s a simple enough class that contains one language extension, a method called ReverseString, which takes in a string parameter and returns the string reversed. The input “Test” would yield “tseT”.
There is no validation code on the above method, if you were to pass in a null value to the method, it would cause an exception.
We could test against the parameter being null, not being empty and so on using Asserts or manual checks like so…
if (value == null)
throw new NullReferenceException("value");
This is good, and healthy coding. But it will only work in runtime. You can use unit testing to make sure your code doesn’t do anything funny, but you can never be sure that other people using your classes won’t try some funny business!
In cometh Code Contracts! Code contracts will become a part of the core of .NET 4.0, and when I say core, I really mean the core! Mscorib, to be exact! But for now, you can download the Code contract installation package from Microsoft here.
If we use code contracts, the code would look like this:
public static class StringExtensions
{
public static string ReverseString(this string value)
{
Contract.Requires(value != null);
Contract.Ensures(Contract.Result<string>() != null);
string result = string.Empty;
for (int i = value.Length - 1; i >= 0; i--)
result += value[i];
return result;
}
}
Basically, we add two “Asserts” to the code. One that requires that the parameter ‘value’ is not null, and one that promises that the return value will not be null either.
If I now try and consume this utility class from a simple console application, using the following code:
class Program
{
static void Main(string[] args)
{
string _value = null;
_value = _value.ReverseString();
Console.WriteLine(_value);
Console.WriteLine();
Console.WriteLine("Press any key to exit . . .");
Console.ReadKey();
}
}
The compiler will warn me that the call to ReverseString fails to meet the requirements, because it is passing in a null value. It will even mark the code line with a blue squiggly line so that I can see immediately when I’m up to no good when I write my code.
The solution is simple, elegant and allows your code to become absolutely rock solid with the minimal amount of effort. And that it shows me how I fail to meet the requirements of the code I’m calling at compile time will save me a lot of headache and support issues at runtime!
But wait! This is only the tip of the iceberg! The code contracts extend well beyond this mere simple demonstration, the power you can harness by using this new technology will not only greatly improve the quality of your code and allow you to eliminate the majority of problems at compile time, it will also ensure that other people who use your code will use it the way you intended and not get strange and unintelligible errors downstream.
So how does this work in a multi-tier WCF scenario, you ask?
Well, let me show you!
I created a blank Visual Studio solution and added a WCF Service Library and a Console Application to the project.
Next, I removed some of the auto-generated code and left only the GetData method.
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
Here’s where it gets interesting! You can’t add preconditions to interface implementations. Preconditions are code contracts that demand certain conditions are met before the method is allowed to execute. Such as the Contract.Requires condition.
The following code generates a compiler error.
Interface Implementation cannot add preconditions.
public class Service1 : IService1
{
public string GetData(int value)
{
Contract.Requires(value >= 0, "Parameter 'value' " +
"must be a positive number.");
return string.Format("You entered: {0}", value);
}
}
Instead, we have to go to the interface and add the preconditions. But wait, we can’t add code to interfaces you exclaim. And rightfully so, we cannot.
Instead we create a separate class to hold the code contracts and reference to it from our interface using an attribute, like this:
[ServiceContract]
[ContractClass(typeof(IService1Contracts))]
public interface IService1
{
[OperationContract]
string GetData(int value);
}
[ContractClassFor(typeof(IService1))]
sealed class IService1Contracts : IService1
{
string IService1.GetData(int value)
{
Contract.Requires(value >= 0,
"Parameter 'value' must be number " +
"greater than or equal to zero.");
Contract.Ensures(
Contract.Result<string>() != null);
return default(string); // Dummy return
}
}
Ok, great! So next we go to our console application and add a service reference to our service, and add the following code:
static void Main(string[] args)
{
Service1Client client = new Service1Client();
Console.WriteLine(client.GetData(-2));
Console.WriteLine();
Console.WriteLine("Press any key to exit . . .");
Console.ReadKey();
}
Now, if we compile, we’ll notice that code contracts aren’t kicking in, there are no compiler warnings or anything. If we run the application, however, the service will throw an unhandled exception which will thoroughly confuse the client and bork the service channel.
The problem here is that when we add the service reference, Visual Studio generates a proxy class for us, which implements a completely new interface that mirrors the one in our service, but is nevertheless not the same one. That is where we loose the reference to our code contracts. This is all of course very natural and expected. WDSL does not know anything about code contracts and has no means of learning about them across our WCF metadata exchange channel.
And since the code contracts are not implemented with attributes (would have been more elegant, but I get the problems with that approach), we cannot easily implement our own WCF metadata exchange protocol and use reflection to pass them along. Which would of course also require us to rewrite the WDSL tool. In other words, not a snowball’s chance in hell we’re doing that tonight.
No matter, your guru to the rescue!
If the problem is in how the code is generated for the service, then let’s generate it some other way, some way that is aware of the fact that a) there is an interface but no spoon, and b) the interface declaration is on our hard-drive somewhere. More specifically in another project in the same solution.
First, we move the interface declaration and code contract class into a separate class library which we’ll call Service1CodeContracts, leaving only the actual interface implementation in the WCF library.
Next, we reference this library from both the WCF service and the console application.
This means you can implement your code contracts in one place and use them on both the server and the client side.
Sneaky, I know!
Right, now on to generating the proxy class. Normally when the service reference tool generates code, it will not implement proxy classes for classes both the client and the service know about, but that does not extend to interfaces.
So even though the client now knows about the interface that is used for the service contract, that matters not a bit. Visual Studio still creates its own mirror interface.
Doh!
We could go in and manually edit the generated service reference and remove the mirror interface and instead point the proxy class in the general direction of the service interface we put in our shared class library. But that’s not a very good way of doing things, since if we update the service reference, all such changes will be lost.
Oh well, we’ll just have to implement our own way of generating the proxy class, now won’t we?
In enters T4 text templating! …which is a built-in feature in Visual Studio, if you didn’t know.
After some tinkering, I managed (with the help of Google and the T4 guru Oleg Sych) create a text template that would take in the shared class library housing the interface and code contracts and spit out a fully fledged WCF proxy class that looks like this:
[GeneratedCodeAttribute("System.ServiceModel",
"3.0.0.0")]
public interface IService1Channel :
Service1CodeContracts.IService1, IClientChannel
{
}
[DebuggerStepThroughAttribute()]
[GeneratedCodeAttribute("System.ServiceModel",
"3.0.0.0")]
public partial class Service1Proxy :
ClientBase<Service1CodeContracts.IService1>,
Service1CodeContracts.IService1
{
public Service1Proxy()
{
}
public Service1Proxy(string endpointConfigurationName)
: base(endpointConfigurationName)
{
}
public Service1Proxy(string endpointConfigurationName,
string remoteAddress)
: base(endpointConfigurationName, remoteAddress)
{
}
public Service1Proxy(string endpointConfigurationName,
System.ServiceModel.EndpointAddress remoteAddress)
: base(endpointConfigurationName, remoteAddress)
{
}
public Service1Proxy(
System.ServiceModel.Channels.Binding binding,
System.ServiceModel.EndpointAddress remoteAddress)
: base(binding, remoteAddress)
{
}
public string GetData(int value)
{
return base.Channel.GetData(value);
}
}
And lo and behold! So long as you have a reference to the shared class library in the client (no need to have any reference to the service what so ever, the generated proxy client will be generated without a hitch.
And now, back to the code contracts!
I removed the old service reference and instead used my new T4 template to generate the proxy and rebuilt the whole solution, and behold!
There we go, compiler warnings on code contracts for a WCF service!
Hopefully, Microsoft will have a look at ways to make code contracts and WCF work a little smoother in the future, but oh well, it works and it is very, very cool.
Source Code
Note, in order to compile the source code, you need the Microsoft Code Contracts Library as well as FxCop 1.35 or later (the text template uses introspection to generate the proxy class to avoid locking the service output assembly, which reflection would do).

