Friday, August 18, 2006

Reflecting Generics

I had an interesting problem today, how do you find out if an object is a subclass of a generic type? If you've simply got an instance of a generic type...
List<int> myobject = new List<int>();
You can find that myobject is a List<> by using the method GetGenericTypeDefinition():
if(myobject.GetType().GetGenericTypeDefinition() == typeof(List<>)) { ... }
But say you've got a type that inherits from a generic type:
public class A : List<int> { }
Now if you've got an instance of A:
A myA = new A();
You can't call GetGenericTypeDefinition(), it complains that myA.GetType() is in an incorrect state. Similarly, asking this:
myA.GetType().IsSubclassOf(typeof(List<>))
returns false because myA is a subclass of List<int>, but not List<>. I couldn't find any way of doing this without manually walking up the class hierarchy. In the end I gave in and wrote a this little recursive function:
public bool IsDerivedFromGenericType(Type givenType, Type genericType)
{
    Type baseType = givenType.BaseType;
    if (baseType == null) return false;
    if (baseType.IsGenericType)
    {
        if (baseType.GetGenericTypeDefinition() == genericType) return true;
    }
    return IsDerivedFromGenericType(baseType, genericType);
}
I guess where I was going wrong was thinking that List<int> 'inherits' from List<>, but of course it doesn't. It's an entirely unrelated hierarchy. Generics are not inheritance. I spent some time digging through the newsgroups looking for an answer to this and there's quite a lot of confusion around this issue. A really common misconception is to think that, for example, List<int> inherits from List<object> and that you can downcast like this..
List<int> myIntList = new List<int>();
List<object> myObjectList = (List<object>)myIntList;
It doesn't work.

Tuesday, August 15, 2006

A nice soap test tool: SoapUI

Do you manually code test harnesses for your web services? It's a real pain, and because every web service is defined by its wsdl you shouldn't have to do it. I've been using a soap test tool called SoapUI for the last few weeks. It makes experimenting with raw web service requests a breeze. You just have to give it a wsdl url and it will construct an example request which you can fill in with some test values. Then it's just a question of waiting for the response. It saves all the different requests you make in a project file and you can change the endpoint to try out different deployments. It's also got facilities to do load testing and generate statistics for web services, but I haven't had a need to use that yet. The only downside about this tool is that it's got a nasty javaesque interface, cross platform UIs always suck, but this one is not too bad.

Friday, August 11, 2006

Functional Programming

I've just read a really good blog on functional programming by defmacro.org (I couldn't find his/her name on the blog anywhere). I didn't know that Alan Turing, Kurt Godel and John von Neumann all worked together at Princeton. I guess it makes sense that those three guys would know each other, but just imagine being able to listen in to their conversations. Hmm, probably completely over my head:) Anyway, there was a fourth guy, who I'd not heard of before, Alonzo Church. He invented an alternative to the Turing machine called lambda calculus. Of course the Turing machine went on to be the basis of pretty much all modern computers, but Alonzo wasn't entirely forgotten. In the late 50's LISP was invented as a programming language that implemented lambda calculus and is still with us. It's never really been mainstream, but the Emacs text editor is written in LISP, for example. One think that I've read in several places about LISP is that it makes some things, like creating domain specific languages much easier. So why is functional programming interesting? And what can you do that you can't do with imperative programming languages like the C* family? Well, it all goes back to the lambda calculus. I don't want to repeat defmacro's excellent article, but you can do all kinds of cool stuff, like mathematically redictable unit testing, simple parallel processing with no chance of race conditions, and even hot deployment where you can drop in code changes to a running program. Also because of the nature of functional programs (they are, in effect, a single function) you can use the lambda calculus to do automated optimisations to your program or do lazy execution. Also, because a functional language's state is always represented by its stack, unlike an imperative language where the state is a combination of the stack and the heap, you can use 'continuations' to halt and restart your program, or even pass your program's state to a separate program (it's also what allows for hot deployment). Now that C# is begining to get some funcional programming constructs (lambda expressions, expression trees, delayed execution), functional programming is going to become a mainstream concern for dot net developers. Joel Spolsky, has a nice post, Can your programming language do this? It shows some stuff that becomes much easier once functions become first class citizens, and there's a post about it on the powershell blog, showing some of the powerfull functional features of that language. If you look at everyone's current favorite language, Ruby, it already does all this stuff, as well as providing a full compliment of object oriented features. Unfortunately, some of the really cool stuff I mentioned above, like parallelisation or automated optimisations, can only be done with 'pure' functional language like Haskell or Erlang. It's making me think that I'd like to dig into a good Haskell book sometime.

Wednesday, August 02, 2006

Writing web services contract first using WSCF

Web service gurus will always tell you to write web services "contract first". This means defining the schema for your service types, your messages and wsdl definitions before creating your implementation, which is the exact opposite of what you do when you work with Microsoft's tools. The visual studio way of doing it treats the wsdl as a behind-the-scenes artifact that the developer shouldn't need to worry his little head about. If you're using the Visual Studio tool set end-to-end you don't need to be bothered with wsdl or any of the other nasty angle bracket stuff to do with web services. The problem comes when you need to support interoperability with non dot net applications, then attributing your dot net types to produce the correct wsdl schema can be quite tricky. It would be much nicer if you could write your schemas, message definitions and wsdl first and then generate most of the boiler place asmx code from the wsdl. I was recently introduced, by the software architect where I'm contracting at the moment (hello Shelly), to WSCF (Web Service Contract First) which is a free tool that does just that. It's a free download from thinktecture, they're the consultancy headed by Ingo Rammer the remoting guy. It works as a visual studio plug in, all you have to do is write your xsds that define your types and messages (I use xml spy for doing that) and then you just right click on the message xsd file in the solution explorer, and choose 'Create WSDL Interface Description', a nice wizard pops up where you choose some defauls and then whoosh, there's your wsdl. After you've got the wsdl file you can right click on it and choose 'Generate Web Service Code', again a nice wizard pops and before you know it, you've got all your service types and framework generated in C#. Very nice. Thinktecture have also gone to the effort of writing a really nice walk-through for WSCF that gets you up and running really fast, it only took me a couple of hours to produce my first web service with this method yesterday.