Wednesday, 19 December 2007

The end of the year

And all of a sudden it's Christmas. In just three days I hop on a plane and fly back to Australia for the holidays, so this will most likely be the last post of 2007. 14 posts do not make a blog, so there will be plenty more to come in the new year.

I will return to the topic of Exception Shielding and I am planning a series of posts on system testing, test driven development, and integration testing as this is a hugely important and also very difficult topic. In addition to that I'll write about Commerce Server (I'm really only working on the fringes of CS at the moment so these posts may be sporadic) and SOA and any other interesting topics as they come up.

To those of you that have visited (about 20 individuals from across the globe according to FeedBurner), thank you for stopping by - and I hope you'll come by again in the next year.

Merry Christmas and a Happy New Year to all!

B for Baba Nation

It took me near on three weeks to get through all the artists on my iPod starting with "A" - and I'm afraid I've killed the challenge already. The urge to listen to music that would otherwise be months down the track (no pun intended) is just too great, and I'm struggling to find good reasons to be disciplined.

But I made it all the way through the "A"s and I started on the "B"s... but it was BackStreet Boys that killed the desire. So now I'm no longer listening in sequence. But I will try and listen to all those albums I've ignored for so long.

A time for System.Reflection

In developing a class that holds search criteria for a generic application search tool I needed to do two things: apply wildcards to the search criteria, and sanitize the search input data. As the class that holds the search criteria is basically a collection of protected or private data members and a set of public properties to expose them (and since there will not necessarily be only one single class of this type, setting up this functionality by calling each property explicitly could be really tedious - not to mention hard to maintain.

So a different measure was clearly called for. I decided to do this through reflection, and letting the class reflect upon an instance of itself and subject the relevant properties to treatment by a set of methods.

I'll show a simplified example here (don't worry, I'll leave in all the relevant bits concerning reflection). The requirements for the class, aside from holding and exposing search criteria, is that it exposes a method that you can call to sanitize the data it holds, and another method you can call to apply wildcards to the criteria.

The example class I'll use looks like this:

public class SearchCriteria
{
private string _firstName;
private string _lastName;
private string _email;

public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}

public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}

public string Email
{
get { return _email; }
set { _email = value; }
}

}

It's very simple. No constructor, only three private fields and three public get/set properties. The real-life class has lots more properties but there's no need to bore you with those here - it's an example after all.

We need to both sanitize the properties and apply wildcards to them. We'll provide two public methods (Sanitize() and ApplyWildCards()) that will do the work on the properties. And this is how it looks:

using System;
using System.Reflection;

public class SearchCriteria
{
private string _firstName;
private string _lastName;
private string _email;
private delegate void ActionDelegate(PropertyInfo prop);

public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}

public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}

public string Email
{
get { return _email; }
set { _email = value; }
}

public void Sanitize()
{
ModifyProperties(new ActionDelegate(Sanitize));
}

public void ApplyWildCards()
{
ModifyProperties(new ActionDelegate(ApplyWildCards));
}

private void ModifyProperties(ActionDelegate actionDelegate)
{
foreach (PropertyInfo prop in GetProperties())
{
if (prop.PropertyType == typeof(String))
actionDelegate(prop);
}
}

private PropertyInfo[] GetProperties()
{
return typeof (SearchCriteria).GetProperties();
}

private void Sanitize(PropertyInfo prop)
{
//......
}

private void ApplyWildCards(PropertyInfo prop)
{
//......
}
}

At the core of this we have the method called ModifyProperties which consumes a delegate of type ActionDelegate which is defined at the top as private delegate void ActionDelegate(PropertyInfo prop). If you look carefully you'll see that the methods Sanitize(PropertyInfo prop) and ApplyWildcards(PropertyInfo prop) both match the delegate's definition. This is in fact what allows us to pass references to these methods into ModifyProperties via Sanitize() and ApplyWildCards(). All that the ModifyProperties method does is loop through a collection of properties which is returned by the GetProperties() method and call the appropriate method (Sanitize or ApplyWildCards) via the delegate that was passed in.

I've taken out the details of Sanitize(PropertyInfo prop) and ApplyWildCards(PropertyInfo prop) because it isn't really relevant here.

Simple, isn't it? It's quite neat, I think. Now there is one thing to note here. ModifyProperties only looks at string properties, so if you have to sanitize properties of an other type you'd have to do change the code. Probably it would be wiser to create a custom attribute class and mark up the properties that can be sanitized instead of relying on property type.

Obviously this is a simple example and a first pass at creating a solution and I've not taken into consideration things such as sanitation requirements changing based on context etc., but that's fairly simple to slot in. Hopefully this has been a useful and simple real-world example of how you can use System.Reflection.

Happy coding!

Tuesday, 11 December 2007

The Endians are coming!

I was working on a piece of kit for password hashing the other day and realised that I didn't really known what the term endianism refers to. So I looked it up.

I was pleasantly surprised to find that the term, which is now an IT term more than anything, harks back to the story of Gulliver's travels.

In short, endianism refers to the order in which bytes are stored; whether the "big end" is to the left or to the right. Big-endian stores the "big-end" to the "left" (or first), and Little-endian stores the "big-end" to the right (or last). You can read a pretty good explanation of it here, and if you're interested in Jonathan Swift and how he originated the term you can read about that here.

Throw your own SqlException

Last week I was faced with a very specific problem; I needed to throw a SqlException. One of my TestFixtures required several tests in which SqlExceptions were thrown, all with different error codes (accessible via [exceptioninstance].number).

The problem was simple: you cannot instantiate a SqlException as you would an object from a class with public constructors. SqlException's construct is internal.

So what do you do? Well - my first pass at this worked for some scenario but not for others. In my tests I would create a SqlConnection instance with a bogus connection string and attempt to open it. This would throw a SqlException.

I set the "Connect Timeout" attribute of the connection string to "1" in order for Connection.Open to time out quickly.

However, this throws a specific SqlException and you really have no control over the state of the exception at all. So if you need to throw a SqlException with a specific error code you're kind of screwed.

Well, not really. This article gives an excellent example of how, using reflection, you can create your own specific SqlException. I've employed this approach with excellent results, and my tests are much faster than when I induced the exceptions with SqlConnections.

Monday, 10 December 2007

VS2005 Service Reference Wizard

I've posted a couple of times (here and here) about building WCF proxies through pre-build events. The Add Service Reference function in Visual Studio is handy for this but has some limitations (read about them in the previous posts). Generally speaking, though, the Add Service Reference function does exactly what you need, at least to get yourself up and running and your program speaking to a service.

But there's an issue. I call it a bug. And it is mighty annoying. It has wasted two afternoons of my time already. Once when I first came across it and a second time when a colleague, three weeks later, had the same problem and I could not remember what I'd done to fix the issue. Now I'm writing it down once and for all.

Using the Add Service Reference tool, if you add a URL pointing to a service's WSDL the tool will appear to find the service, but the actual generation of the proxies will fail. Why? Because the address of the WSDL is not technically the address of the service. Bloody hell - you'd think they could have fixed that issue, wouldn't you?

So make sure you remove the ?wsdl from your service reference URL.

If you're having other issues with the Add Service Reference tool that sound like there's a Content Type issue, it's likely that some of the references in your WSDL are not accessible to svcutil.exe. You can check this by adding ?xsd=xsd0 to the service reference URL (in a browser). If you get a 404 Not Found message it's likely that the account used to host your service (the one associated with the service's application pool) does not have read access to the Windows temp directory. This doesn't seem to be documented anywhere, and I found the solution on Erwyn van der Meer's blog.

Wednesday, 5 December 2007

Exception Shielding

One of the very important aspects of a robust service architecture is the concept of exception shielding. In short, exception shielding deals with the explicit boundaries between a service and its consumers (clients), and how exceptions raised within the service are handled and presented to the client. Although conceptually simple, it's not a straightforward topic when it comes to implementation. Microsoft has posted a good introduction to the concept. Shortly I'll be posting more on the topic as my own solution takes form.

A for Alanis

So, I set out to complete the iPod challenge. I don't think I'll last. Not because I have boring music on my iPod, but rather that my listening patterns really depend on my mood and what I'm doing. Today I would have preferred to listen to Roger Waters but if I keep this up I will not listen to his music until April.

So far I've listened to a-ha, Aaron Copland, Aaron Neville, ABBA, AC/DC, Ace of Base, Adrian Martinez, Aimee Mann, Air, Al Green, Al Martino, and Alanis Morissette. The song count is 282/9087.

I might break with the pattern and ensure that I listen to the artists and all their albums in alphabetical order - but I'm not sure I can do this if I cannot skip ahead to other artists that I feel like listening to.

Pre-build events, client proxies, and common libraries

Previously I posted about WCF client-proxies and how pre-build events can be used to generate these every time your client project builds.

The post sets out that the client and service share a common library of domain/business objects, and svcutil is instructed as such using the /reference flag. This approach works fine, however, you may run into problems when the shared library changes. This happened to me repeatedly during a period where I had to modify the common library which contains the classes (marked up with the [DataContract] attribute).

The problem is that the pre-build event on the client project references a running version of the WCF service. When the service interface changes, or in particular when the DataContracts that the service consume or return change, there's a discrepancy between the library referenced by the library and the library referenced by the client.

Even if you ensure that you update the client's common library code prior to the build, the pre-build event may fail. Why? Because the call to svcutil that creates the client proxy runs before the changes to the common library (in the client) are compiled.

That particular aspect of this approach isn't great. However I found that if I make the changes to the common library through the client solution and then pull these across to the service things work just fine. With SVN this is easy. The common library is a SVN external to both the client and service SVN repositories, and I can easily commit changes made through the client solution and update the service solution (I typically work on the client in one instance of Visual Studio and the service in another).

Having said all this and gone through a great deal of trouble to get everything working with pre-build events in Visual Studio 2005, it appears that the solution to this particular problem really lies with Visual Studio 2008.

Happy coding!