Tuesday, July 26, 2011

Book review: Professional F# 2.0

In one of my last posts I wrote about a F# application written test first. While working on this application I read the book 'Professional F# 2.0' from Wrox. Personally I believe the Wrox books are most of the time the best books you can find on a subject, especially their 'Professional' series.They go very deep into each subject and give you all the details you need to know. So here is what I think about the Professional F# book, by Ted Neward, Aaron Erickson, Talbott Crowell and Rick Minerich.



The book begins with an extensive explanation of the different F# language constructs you can use. The same explanation you would get in a typical C# book, in fact. While this section gives you all the necessary language details: what types look like in F#, how certain constructs, like ifs and whiles, need to be written. It lacks, however, the basic explanation of how a language like F# should be used. As a reader you don't get much of a clue why these kinds of constructs might be useful. The few points where you do get some extra info on the style in which to write F# code, a reader without any knowledge of functional programming, will be nonplussed about why certain things are done in a certain way. That really is a shame, because I think a lot of readers will drop off once they see the extensive differences in language constructs they need to overcome when coming from a more traditional language.

I was hopeful though that in 'Part III: Functional Programming' there would actually be some good information about how to program using a functional style. But alas, again the author goes on and on about language constructs, what functions look like and how you write them, not how you use them properly. Some more advanced topics also come into play, like closures. Not that this is so extremely advanced, but it is a concept you don't hear every day, you use it quite often, though, even in C#, but you don't always think of it as being a closure. The explanation the author gives for the closure concept, however, is quite difficult to understand, up to the point where I had to use Google to get the right explanation. Same goes for the principle of currying, which, in my opinion, is explained the wrong way.

As for the F# language itself, it adds quite a lot of special constructs you do need to get used to. Especially when writing your first F# program, be sure to have a language reference nearby. For such a reference, this book is ideal. It explains all the little tidbits you need to know. But still, in my opinion, F# adds a lot of unnecessary language constructs. When you are, for instance, defining a recursive function, you are obliged to use the rec keyword, otherwise the compiler won't allow you to call yourself. Coming from a Lisp kind of language, this adds noise to your code (although I have to admit Scheme has its own weird language constructs).

Since this book was quite a disappointment for me, I would gladly like to guide you to some other useful resources:

  • The MSDN library will not be of much help. It will give also you a lot of info about the language, as this book does, but it doesn't say much about the programming style to use. What you can find on the MSDN site, however is how to get started setting up your first F# project in Visual Studio. This was something I struggled with in the beginning of programming F#, how a project is structured.
  • Tryfsharp: This site by the Microsoft research team lets you go through an interactive tutorial in which you can immediately try out different examples in an F# interactive console. In their tutorial they explain all the important F# constructs that are different from the other programming languages you come across (without too much other explanatory crap that you do not need to know). The examples given are also quite easy to follow (with some small exceptions). The examples given were also quite close to the examples you will find in introductory books on functional programming style. This site is based on the book 'Programming F#' by Chris Smith (O' Reilly). I actually good much better information on this site than in the Wrox book.
  • fsharp community samples: These can be found at codeplex. You can find some samples here, but also quite some links to other resources and blogs. Good starting place, if you ask me.
  • F# wikibook: Explains not only the basic concepts, but also some advanced topics such as advanced data structures in F#, which, after you've gone through the introductory stuff are quite useful.
With all this material I now hope to get a better Game Of Life written. I will probably throw away what I already have and not try it with a class, but with only functions. We'll see where this ends.

Tuesday, July 19, 2011

Cross Platform Mobile Development

At this years NDC conference, I followed a couple of talks about mobile development. It was announced there that the people behind MonoTouch and MonoDroid were moving to a new company named Xamarin. Well, as of yesterday, they have actually made the move and all sources for doing cross platform development can be found at their site.

They are actually providing a really cool way of doing cross platform development. You don't need to learn a whole lot of Objective-C or Java to develop applications for iPhone or Android, but you can develop in C# .Net, the language you use for doing Windows Phone 7 development. The only thing you still need to provide, that is specific for the iPhone and Android devices, is the user interface specific for each device. If you develop your applications wisely, though, - that is, using one of the MV* patterns - this is a walk in the park.

For iPhone development you will need a MAC, because the iPhone SDK only works on iOS. You can then install Mono and MonoDevelop (instead of Visual Studio) for OSX to start developing. For people like me, who are used to tools like ReSharper, you will, however, again need to learn how to type.

For Android development, the Java SDK is needed, and again MonoDevelop or Visual Studio 2010. With some handy project linking in Visual Studio, you can easily provide a shared code base for all three platforms. On this, watch the NDC talk, by Jonas Follesoe, about cross platform development!

The good news also is, that Xamarin offers both MonoTouch and MonoDroid as a free trial version that doesn't expire. The only drawback to the trial is that you can't deploy to actual iPhone or Android devices, only to their respective emulators. But this should be enough to get you started. Once you want to try out specific features the emulators don't offer (like gps, camera, ...) you will need to move to a paid license (or once you want to deploy to the marketplace, that is).

You will however need a little bit of extra effort if your initial WP7 projects are hosted on TFS. MonoDevelop for now does not offer a build in way for synchronising projects with TFS. You can use Microsoft Visual Studio Team Explorer Everywhere 2010, which offers a command line utility for connecting to TFS. Also SvnBridge gives you an SVN kinda way for connecting to TFS. And also, you could move your code base to SVN or GitHub (I love that place, not only for its name) alltogether.

This weekend there is also the MonoSpace conference in Boston going on, specifically for Mono development. They have a couple of sessions on mobile development as well. I hope they will put videos on-line of their talks.

Since I don't own a MAC (yet), I will try out the MonoDroid SDK in the next couple of weeks. Be sure to check back in to watch the progress (and the walls I will probably hit).

Tuesday, July 12, 2011

Going to the Opera

I recently installed the Opera browser on my laptop. Main reason for this was the fact that I thought the Opera guys gave some really good HTML 5 talks during this years' NDC conference. And they just looked like really nice guys (I'm allowed to judge people on nicety). The Opera browser is also pretty far in implementing HTML 5 features as well, so might be interesting to try it out.

So, after installing this browser, I only used it for a day or so. Good points were its speed, which is faster than IE, faster then Firefox and faster than Chrome, this last one, up until now, being the fastest browser I used thus far. Bad points however are the way it treats shortcut keys. Ctrl click, opens a new tab, like Chrome, but also immediately places focus on this tab, unlike Chrome. To open the tab in the background on Opera, you need Ctrl Shift click, something I am not used to. This, sadly enough, was actually the main reason to have me use Opera only for a day. On a side note, one thing to always keep in mind when designing user interfaces: don't change the way things look and feel for a user too much (did you hear me, Office guys?), they get scared and run.

But then recently I gave it another shot. I primarily tried it out again because my laptop while running an instance of Visual Studio, a VM and Chrome with a couple of tabs opened, was getting really, really really slow. Looking at my CPU usage I saw that Chrome was actually using more resources than my Visual Studio while compiling. Some googling showed me that Chrome uses a sandbox for each tab, which also means it uses the same amount of resources for each tab, since resources are not shared. This has the advantage that when one tab crashes, it doesn't crash your other tabs. A phenomenon I haven't really experienced yet (in my case my other tabs actually did crash as well. not good!). This has the disadvantage of eating CPU cycles like a madman if you like to have many tabs open all the time.

So I reconfigured Opera as my default browser and immediately got annoyed again by the missing ctrl click. There are some workarounds for this (google them, you'll find them), but they didn't really work for me. Altering your shortcuts in the advanced preferences didn't do the trick. And the JavaScript solution that you can add didn't work either (my clicks stopped working altogether). I do find the fact that you can add your own JavaScript code to this browser pretty cool, though. Anyhow, while trying this out, I restarted my browser a couple of times and during my last restart I got the message that there was an update ready to install. This, I must say, I didn't really like, I like the fact that Chrome installs updates in the background and that I'm not bothered by this. My initial annoyance with update windows probably stems from the iTunes app that starts nagging about updates every friggin' time you start it.

So I installed the update, reopened the Opera browser and as a miracle I now have ctrl click open tabs in the background. I went from version 11.11 to 11.50, so I skipped a few versions as well, it seems. I suppose this is a new feature, I have no idea, but I'm happy with it. And the most important thing: my laptop doesn't become overly slow while I leave some browser tabs open all day. And apart from this, Opera offers pretty much the same features as Chrome. So for now, I'm sticking with it!

---

On a side note: I have been using Opera now for a week or two. I am still very happy with its performance (read this as: the performance of the rest of my system). But there are some drawbacks, though. Not all CSS is rendered as it should be. My own blog for instance doesn't render correctly using Opera and when I watch my blogs' statistics, they are just not shown in Opera. Also, yesterday, I was editing a new blog post, only to find out today that the autosave or Ctrl + S, which works just fine in Chrome, didn't function in Opera. I lost my changes, which I don't like! I'm going to keep using it for a couple of weeks (not for blog editing) and re-evaluate again.

Tuesday, July 5, 2011

Playing GOLF

Qframe recently held a bootcamp where all employees were invited to follow sessions on all kinds of things. One of those was a code retreat in which we tried to implement as much of the Game Of Life as possible in 45 minutes time, while giving ourselves a couple of restrictions (implement this without using if statements, implement this test first, ...). We redid this exercise a couple of times and during the last go, I and some colleagues gave ourselves the restriction of using a completely different language than the one we are used to. So we tried implementing this in F# (hence the name GOLF: Game Of Life in F#). I must say, we didn't get very far, but ever since I have been playing with the idea of finishing this exercise. In this post you will find my experience in trying this.

First of all, I must admit, I do have some experience in functional programming. This doesn't mean however I am a bright and shining light in functional programming (all but). But I have used Scheme for a year at university and I still know what a car and cdr are, what a REPL loop is, and so on. On the other hand, I am pretty sure that in the GOLF exercise I made some very big errors in functional programming and I hope you, as a reader, are a bit forgiving for those. One thing that's new to me is the fact that I can mix a functional style with objects. So, feel free to comment on the code, since I do want to learn from my mistakes!

To get started I needed an F# project. I choose to use an F# Library project, since I wanted to start with all the logic of the game first, a fancy user interface can be added later. This type of project gives you two files, a Module1.fs file, in which to place your code and a Script.fsx file, in which you can write code to informally test your F# program. Since I am going to use a unit testing framework to test the F# code, I removed the .fsx file.

Another thing you need to be aware of when writing F# code, is the order in which you place your files. They are processed in order by the F# compiler, so make sure a type (or function, or whatever) is known by the compiler before you use it. This sort of looks like the behaviour you have with a C++ compiler, where you need the correct include statements to let types know each other. A C# programmer doesn't need to worry about this, since all types within the same project know each other.

After the basic project setup, I wanted to write this application test first. So after some Google research I found a couple of unit test libraries you can use with F#. In fact you can use the NUnit framework if you want to, but I choose to use FsUnit, which adds a more natural style of writing tests for F# (and uses NUnit to annotate its tests). Since the FSUnit project is hosted on nuget, installing it, was quite easy (install-package fsunit and you're done). The nuget package also adds a .fs file that gives you some example test cases to get started. I didn't go into the effort at first to place my test code in a second F# library project. I can still do this later on. I did place the test code in a second .fs file (after the Module1.fs file).

Ok, so on to writing my first test. I started simple in saying that when I create a new Cell in the Game Of Life, it shouldn't have any neighbours. F# has the notion of namespaces, you can add those at the top of your file. If you want to use functionality from other libraries (like NUnit, FsUnit and the module1 file I am writing tests for), you need to add an open statement for each. This is actually similar to writing using statements for namespaces you want to use. After this you can place your first test class. in my case this class is called ''Given a new cell''. This naming style is handy when looking at your tests in a test runner. F# (or FsUnit, I actually don't know which) permits spaces in the class name, as long as you surround it with quotes. Beware though, these are two single quotes that start at the top left corner and end at the bottom right corner (they do NOT go straight down, look for them on your keyboard!). Since this is a test class, you need to decorate it with the TestFixture attribute.

 namespace GolF.Tests 
  
 open NUnit.Framework 
 open FsUnit 
 open Module1 
  
 [<TestFixture>]  
 type ``Given a new cell`` ()= 
   let cell = new Cell() 
  
   [<Test>] member test. 
    ``when I ask how many neighbours it has, should answer 0.`` ()= 
       cell.numberOfNeighbours |> should equal 0  

The actual test creates a new Cell class, which I still need to implement, I am working test first. And after that you can find my first test. Again, I use the fact that you can place an entire sentence between those funky quotes. The test is annotated with the Test attribute and I also indicate this test method as being a member of the test class. Beware though that F# does a lot of its parsing based on indentation, so indenting in the correct way is really important. After I wrote my first test, the F# compiler was actually complaining about the ``when I ask how many neighbours it has, should answer 0.`` sentence, which I found strange. The FsUnit example file, with the same sort of syntax, compiled just fine. After some really hard looking at the two files, I found out that before the sentence there is not only a tab, but also a white space, which is very easy to miss.

With this test written, it was time to get it compiling, meaning I had to provide a Cell type with a numberOfNeighbours member.

 module Module1 
  
 type Cell =  
   val numberOfNeighbours : int 
   new() = { numberOfNeighbours = 0 } 

This immediately made my test green, which actually isn't good practice, but I'll ignore that for now.

Time to add some more tests. I will finish this little application during the next weeks and will post some more about my findings during that time, until we get a finished Game Of Life example. I hope this short post will be enough to get you started in F# projects for now.

Sunday, June 12, 2011

NDC 2011

Last week some colleagues and I went to the NDC conference in Norway.



Apart from the weather, which was crappy, it was an awesome conference. I've seen some great talks and am looking forward to watching some of the talks I missed (because I was in another session) online. I also went home with some new great ideas for books I want to read:

  • Introducing HTML 5, by Bruce Lawson and Remy Sharp. They gave the HTML 5 talks during the second day of the conference in a small and very crowded room. They convinced me even more of the amazing things you can do for web pages with the new upcoming standard. It was a relieve as well to hear someone from the Opera browser team talking about HTML 5 instead of the standard Microsoft talks I heard thus far. 
  • Test-Driven JavaScript Development, by Christian Johansen. Too bad his talk was given simultaneously with Rob Ashton's (Document databases with ASP.NET MVC), Kevlin Henney and Anders NorĂ¥s's (Introducing The FLUID Principles) and Hadi Hariri's (Dynamic in a Static World). I went to this last session, which was very good. It gave me some ideas and examples of more things I can start doing with dynamic. I would really like to try to get a DSL written with it (I would probably start off by copying a Ruby example, since it is not easy stuff). The talk about the FLUID principles was very good as well, my colleagues went to that one and it is one of the talks to catch on rerun, once they put the videos up. I did follow the talk about the SOLID principles, which was nice to refresh again. I went to the RavenDB by Example talk on day  3 of the conference. It was a good thing the speaker also mentioned some of the problems he had with a document database, having to rethink the design of your data as opposed to relational databases.
  • The Joy of Closure, by Michael Fogus and Chris Houser. I didn't get to catch any of the Closure and F# talks and it would be nice to get up to speed with this. Also something to watch on rerun and see what we can do with it
  • 97 Things Every Programmer Should Know, by Kevlin Henney and 97 Things Every Software Architect Should Know, by Richard Monson-Haefel. I only went to Kevlin's talk about the 101 things he learned in architecture school, which was light, but enlighting. His other two talks apparently were very good as well, as my colleague went to those.
  • Specification By Example, by Gojko Adzic. His talk wasn't so good, but I think a lot can be learned from this book. One thing I will really remember from the conference is the multiple question marks that speakers had with BDD, DDD and agile. While they are all good techniques, they have their flaws and the software community really needs to figure out how we can do these things even better. Gojko's post on his blog about one of these talks really explains the problem a bit as well. He also mentioned our Cronos colleagues from iLean in his talk, which I think was pretty cool. And he is also one of the creators of cuke4ninja, a port of cucumber for .Net.


Apart from those books and talks I already mentioned, I also followed some of the talks on mobile development. The ones about multi platform development were really informative. The MonoTouch and MonoDroid projects have moved from Novell to Xamarin and are planning on a next release in the coming months. Biggest take-away there was: use the latest MonoTouch and MonoDroid builds for now and switch to the Xamarin builds once they are published. Jonas Follesoe's talk on this topic was great, if you're doing mobile, catch it on rerun! 

I also really liked the AOP talks given by the PostSharp people. They have a great framework for doing AOP, which is really powerfull and which gives you a lot of cool features for keeping your code nice and, well, sharp. They also mentioned some other AOP frameworks, which I think is a nice gesture, since they are not the only ones out there.

The CQRS talk by Fredrik Kalseth was inspiring as well, although he only mentioned one part of CQRS. It was explained really well and can be used as a basis on future projects. I also learned in his talk that JetBrains have a Ruby IDE which I didn't know about. As I look at their site now, I see they're also working on an Objective-C IDE. 



So, all in all, a very good conference, which I hope to catch again next year, and hopefully without the rain. I learned a lot and have now a whole lot of stuff to read and learn even more about. Too bad there's only 24 hours in a day (of which I really need 9 to sleep, since I'm a sleepy head).

Thanks as well to my colleague, Guy, for providing some very nice pictures. You can find the entire collection here.

Monday, June 6, 2011

More on DynamicObject: TryInvokeMember

I just came along another old example of DynamicObject, I would like to share with the world.

What I didn't mention in my last post is that DynamicObject has more methods you can override besides TryGetMember and TrySetMember. These two are very useful when working with properties you want to add on the fly. For methods the TryInvokeMember is a better choice to override. This method will get called on your DynamicObject when it can't resolve a method call.

Let's for instance write a very simple dynamic tracer class. First of all I will inherit again from DynamicObject. This time the class I am creating, DynamicTracer, will not hold an XML tree, but it will wrap another object.

Every time a method is called on this object we will print out (hence the name DynamicTracer) the operation that is being called.

 class DynamicTracer : DynamicObject 
 { 
   object theObject; 
   public DynamicTracer(object theObject) 
   { 
     this.theObject = theObject; 
   } 
   public override bool TryInvokeMember(InvokeMemberBinder binder, 
      object[] args, out object result) 
   { 
     try 
     { 
       Console.WriteLine("Invoking {0} on {1}", binder.Name, 
            theObject.ToString()); 
       Type objectType = theObject.GetType(); 
       result = objectType.InvokeMember(binder.Name, 
            System.Reflection.BindingFlags.InvokeMethod, null, 
            theObject, args); 
       return true; 
     } 
     catch 
     { 
       Console.WriteLine("Oops, cannot resolve {0} to {1}", 
            binder.Name, theObject.ToString()); 
       result = null; 
       return false; 
     } 
     return true;
   } 
 }  

The usage is quite similar to using TryGetMember and TrySetMember, only now are we getting a InvokeMemberBinder as parameter, together with the argument list that is being used and an out parameter for returning the result. I use reflection to invoke the method on the actual object.

To use this tracer, the only thing you need to do is wrap an object with it:

 FileInfo fi = new FileInfo("c:\\temp\\test.txt"); 
 dynamic tracedFI = new DynamicTracer(fi); 
 tracedFI.Create();  

When Create is called, there will be no matching method found in the DynamicTracer class, which will instead trigger the TryInvokeMember method. Although this seems pretty cool and useful, beware you loose all auto completion on any object you wrap this way, which is, for all things dynamic, a downside.

Doing the dynamic thing (Part V)

This will be the fifth and last part in this series. I will try and post some additional stuff concerning dynamic programming, but they will be standalone posts and will not be part of this series (the numbering is getting a bit out of hand).

In last post, you saw how to use the ExpandoObject. We will extend this now with the DynamicObject class. The difference between the ExpandoObject and the DynamicObject is that the first one gives you the ability to create dynamic types on the fly, with custom added properties, methods, ... for each object you create. The DynamicObject class however gives you the opportunity to extend the basic behaviour(s) you want your dynamic objects to have. You can also add some logic for adding dynamic behaviour.

You create your own dynamic objects by inheriting from DynamicObject. You can add extra methods to this class and you can override existing methods of the base class. it is by overriding the existing methods that you actually give your objects dynamic behaviour.

I will give you a practical example of this. A while back a colleague of mine was writing a Silverlight dashboard application on top of a TFS server, using the TFS APIs. This implied writing a WCF service the Silverlight application could use for quering the TFS server. Now, while the TFS APIs are quite extensive, they don't implement the ISerializable interface for all data type objects.

Facing this problem, my colleague started writing DTO classes for all of these types that weren't serializable. But I started thinking if it wasn't possible to just leverage the intrinsic capabilities of dynamic objects. After all, the only thing needed for these TFS objects to be send from and to the service were methods to serialize them to and from XML. And why not make these objects dynamic on the client side, hence excluding the need for referencing or redefining all these TFS objects on the server and client side.

First thing I needed for this, was a way to get any object on the server side serialized to XML. For this I will use the DynamicObject class. I want to be able to use my DynamicObject the same way I used the ExpandoObject class, by adding properties as needed. The DynamicObject for this has two important methods an inheriting class can override. These methods are TryGetMember and TrySetMember. The TryGetMember method gets called whenever you are accessing a property or method of your DynamicObject. The TrySetMember method gets called whenever you want to assign a value to a property or method of your DynamicObject.

I will explain this in more detail for you in a bit. I will start by getting information from our TFS server. I use a simple query and a couple of foreach loops to get information about all workitems in a certain project.

 TeamFoundationServer tfsServer = 
     new TeamFoundationServer("http://serverurl"); 
 WorkItemStore store = 
     (WorkItemStore) tfsServer.GetService(typeof (WorkItemStore)); 
 foreach (Project project in store.Projects) 
 { 
   foreach (WorkItemType wit in project.WorkItemTypes) 
   { 
     WorkItem theItem = new WorkItem(wit); 
     //dynamic code coming up 
   } 
 }  
Once I have a WorkItem from TFS, I want to be able to build a new DynamicObject, using it the same way as an ExpandoObject, adding properties as I go along.

 dynamic dyn = new DynamicElement(theItem.ToString()); 
 dyn.ChangedDate = theItem.ChangedDate.ToString(); 
 dyn.ChangedBy = theItem.ChangedBy; 
 dyn.Description = theItem.Description;  

The DynamicElement class is the class I have inherit from DynamicObject. It is this class that contains the TryGetMember and TrySetMember overrides. Every time I dynamically add a property to my DynamicElement object (like I do for ChangedDate, ChangedBy and Desciption in the example above), the TrySetMember override gets called. In this override I create a sort of dictionary of all the property names and property values the user of DynamicElement has thus far added. This is actually quite similar to what an ExpandoObject does out of the box. The difference is that I can now choose how I store these dynamically added properties and instead of using a dictionary, I use an XElement. I know I have to be able to serialize the entire object to XML, so better make my life simple.
Here you see part of the DynamicElement class that inherits from DynamicObject.
 public class DynamicElement : DynamicObject 
 { 
   public XElement actualElement; 
   public DynamicElement() 
   { } 
   public DynamicElement(XName name) 
   { 
     this.actualElement = new XElement(name); 
   } 
   public override bool TrySetMember(SetMemberBinder binder, object value) 
   { 
     string name = binder.Name; 
     if (actualElement == null) 
     { 
       actualElement = new XElement(binder.Name); 
       return true; 
     } 
     actualElement.Add(new XElement(name, 
       value)); 
     return true; 
   } 
   public override string ToString() 
   { 
     return actualElement.ToString(); //actualElement.Value; 
   } 
 }  
You can see I use an XElement datamember, which I use to build the XML to return from a WCF service call (I didn't make the datamember private, to keep the example short, I need access to it, later on in the example, you should never do this in real life). I also have a constructor overload I can use to set the root name of the XElement. The TrySetMember does nothing more than building the XML. The SetMemberBinder parameter can be used to see which property (or method) names the user of your DynamicElement used (in this example ChangedDate, ChangedBy and Desciption). Once the XML is build, the ToString method can be used to serialize the entire object to XML.
In using this DynamicElement for my WorkItems, I also want to add project info to them:

 dynamic dyn = new DynamicElement(theItem.ToString()); 
 dyn.ChangedDate = theItem.ChangedDate.ToString(); 
 dyn.ChangedBy = theItem.ChangedBy; 
 dyn.Description = theItem.Description; 
 dynamic dynProj = new DynamicElement("Project"); 
 dynProj.Name = theItem.Project.Name; 
 dynProj.Id = theItem.Project.Id; 
 dyn.Project = dynProj.actualElement.Descendants(); 
 return dyn.ToString();  

For the project I use a second DynamicElement. Once the project element is build, I add the entire XML tree to a new Project property of the dynamic workitem object. Eventually I call the ToString method which serializes the object to XML. This way of working makes my service methods quite simple.

 [ServiceContract] 
 public interface IService1 
 { 
   [OperationContract] 
   string GetWorkItem(); 
 }  

So far for the server side of things. We still need a client that can parse the generated XML. For this, again, I will use a DynaimcElement (actually the same one as above, but with extra code added). First of all the incoming XML needs to be understood. A simple solution for this is adding an extra constructor to our DynamicElement class that takes a XElement as a parameter (being the entire XML tree).

 public DynamicElement(XElement actualElement) 
 { 
   this.actualElement = actualElement; 
 }  

Every time now the code wants the value of one of the properties, the TryGetMember override of DynamicObject gets called, so lets add this.

 public override bool TryGetMember(GetMemberBinder binder, 
   out object result) 
 { 
   string name = binder.Name; 
   var elements = actualElement.Elements(name); 
   int numElements = elements.Count(); 
   if (numElements == 0) 
     return base.TryGetMember(binder, out result); 
   if (numElements == 1) 
   { 
     result = new DynamicElement(elements.First()); 
     return true; 
   } 
   
   return false; 
 }  

The code again uses the Name property of the GetMemberBinder, which gives us the name of the property we are trying to get the value of. Next we look for an element with this name in the XML tree. If we can't find this element, maybe the base class can find it (which it probably won't). If we find 1 element with this name, we return it as a DynamicElement. This way we can use the ToString method on it, which will return the Value of this element, and we can also dot further into subproperties of the object (eg. for the Project property of a workitem). We can now write source code like this:
 TFSService.Service1Client client = new TFSService.Service1Client(); 
 string result = client.GetWorkItem(); 
 dynamic workitem = new DynamicElement(XElement.Parse(result)); 
 Console.WriteLine(workitem.ChangedDate); 
 Console.WriteLine(workitem.ChangedBy); 
 Console.WriteLine(workitem.Description); 
 dynamic project = workitem.Project; 
 Console.WriteLine(project.Name);  
I can also add code to the service to return some random XML. I added another service method for this.

 public string GetSomeXml() 
 { 
   return "<test><child1>firstchild</child1>
    <child2>secondchild</child2><child3>
    <sub1>firstsub</sub1><sub2>decondsub</sub2>
    </child3></test>";  
 }  
The client can also print out the values of this XML:

 result = client.GetSomeXml(); 
 dynamic someXml = new DynamicElement(XElement.Parse(result)); 
 Console.WriteLine(someXml.child1); 
 Console.WriteLine(someXml.child2); 
 Console.WriteLine(someXml.child3); 
 Console.WriteLine(someXml.child3.sub1); 
 Console.WriteLine(someXml.child3.sub2);  
This way it is quite easy to build objects on both client and server without the need to provide classes for each one of them. You just take the 'one time effort' to write up a DynamicObject class and you are done.

What I still want to test with this code, is whether it is possible to get this code working together with a tool like AutoMapper (on the server side). It is just a bit cumbersome to copy over all the values of your dynamic objects.

At least I hope this gives you an idea of a practical use of dynamic objects in .Net. It is not the most obvious example and I expect most uses of dynamic lie in working together with COM and JavaScript for SilverLight applications. Other than that I haven't seen many practical examples popping up on the Internet (except for this one, of course).