# Saturday, May 02, 2009

Cliff Simpkins has just posted a blog entry detailing some of the changes between the PDC preview of WF 4.0 and what is coming in beta 1, due shortly.

Important information here not just about beta 1 but also about things you can expect and also things that won’t make it into RTM

.NET | WCF | WF
Saturday, May 02, 2009 12:27:00 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |   | 
# Sunday, April 05, 2009

I’ve been doing some work with the WCF REST Starter Kit for our website http://rocksolidknowledge.com. Preview 2 of the start kit has a bunch of client side plumbing (the original release concentrated on the service side)

The client side code looks something like this:

HttpClient client = new HttpClient("http://twitter.com");

HttpResponseMessage response = client.Get("statuses/user_timeline/richardblewett.xml");

Console.WriteLine(response.Content.ReadAsString());

As compact as this is I was a bit disappointed to see that I only had a few options for processing the content: ReadAsString, ReadAsStream and ReadAsByteArray. Now seeing as they had a free hand to give you all sorts of processing options I was surprised there weren’t more. However, one of the assemblies with the start kit is called Microsoft.Http.Extensions. So I opened it up in Reflector and lo and behold there are a whole bunch of extension methods in there – so why wasn’t I seeing them?

Extension methods become available to your code when their namespace is in scope (e.g. when you have a using statement for the namespace in your code). It turns out that the team put the extension methods in the namespaces appropriate to the technology they were exposing. So for example the ReadAsXElement extension method is in the System.Xml.Linq namespace and the ReadAsXmlSerializable<T> method is in the System.Xml.Serialization namespace.

Although I really like the functionality of the WCF Starter Kit, this particular practice, to me, seems bizarre. Firstly, it makes the API counter intuitive – you use the HttpClient class and then there is no hint in the library that there are a bunch of hidden extensions. Secondly, injecting your extensions into someone else’s namespace increases the likelihood of extension method collision (where two libraries define the same extension method in the same namespace). The same named extension method in difference namespaces can be disambiguated, the same named extension in the same namespace gives you no chance.

I think if you want to define extension methods then you should keep them in your own namespace – it makes everyone’s life simpler in the long run.

.NET | REST | WCF
Sunday, April 05, 2009 4:58:48 PM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |   | 
# Saturday, March 28, 2009

Thanks all who attended my post conference day on a day of connected systems with .NET 4.0, Dublin and Oslo. You can get the demos here.

Dublin | Oslo | WCF | WF
Saturday, March 28, 2009 8:39:03 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Thursday, March 26, 2009

Thanks to all who attended my Devweek session: A Beginners Guide to Windows Workflow. The slides and demos can be downloaded here

.NET | WF
Thursday, March 26, 2009 6:51:37 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Monday, March 23, 2009

If you look in the System.Threading namespace you will notice something that looks slightly odd: there are a pair of classes ReaderWriterLock and ReaderWriterLockSlim. What are these for and why are there two of them?

Whenever you have multiple threads there is a need to protect state shared between them from corruption. The simplest tool in the .NET Framework is the Monitor class (encapsulated by the lock statement in C#) that provides mutual exclusion. In other words, only one thread at a time can acquire it and anyone else trying to acquire it blocks until the first thread releases it. It situations of high update this provides a reasonable approach. However, if we had no writers we could allow everyone to access a resource without acquiring a lock. So if we had many readers and only an occasional writer, ideally we’d like all the readers to be able to access a resource at the same time and only be blocked if someone needed to write. Unfortunately a Monitor would only allow one reader in at a time so this is the role of a Reader/Writer lock – to allow many concurrent readers but only a single writer, blocking all readers.

So we come to the next question: why are there two of them? ReaderWriterLock was introduced in version 2.0 of .NET and provided the above functionality. However, there was a problem. Imagine this scenario: we have 10 readers currently reading when a writer wants access. Obviously the writer has to let the readers finish and so waits patiently for the readers to release their read locks. However, as the readers drop to one, suddenly a brand new reader arrives – there i still a read lock being held but thats ok as it can also acquire a read lock in that situation. Now the writer is blocked on a new reader and more can continue to arrive so that the writer never gets in – this is called writer starvation. ReaderWriterLock suffers from the possibility of writer starvation.

For version 3.5 SP1 the .NET framework team decided to address this. They introduced a new class called ReaderWriterLockSlim that provides the reader/writer lock functionality but does not suffer from writer starvation (new readers are blocked when there is a writer waiting). However, why didn’t the team just fix the original one? They say that some people depend on the feature that new readers can get a lock if a reader is already there. They didn’t want to break existing code.

Monday, March 23, 2009 2:13:25 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Wednesday, March 18, 2009

The .NET Async pattern is a very neat way of running functionality asynchronously. The async pattern is where for a synchronous method DoWork be have a pair of methods BeginDoWork and EndDoWork to handle running the DoWork functionality on the threadpool. Now it is well documented that if I call the Begin method I must also call the End method to allow the async infrastructure to clean up resources it may have acquired. However, where do I call the End version?

Consider async delegate invocation. Quite often I’d like to just fire off the async method and forget about it but I have to call EndInvoke. Fortunately lambdas make this really easy

Action a = DoWork;
a.BeginInvoke( ar => a.EndInvoke(ar) );

Now there is a nasty problem. What happens if DoWork throws an exception? The async delegate infrastructure will conveniently cache the exception and re-throw it when I call EndInvoke. However, the issue is that this is happening in an AsyncCallback delegate on a threadpool thread and so I cannot catch it easily in this construct. Why is that a problem? well since .NET 2.0 an unhandled exception on a background thread will terminate the process. This means to reliably call EndInvoke in an AsyncCallback we must put it in a try … catch. This is annoying code to reliably put in place and is easily forgotten. So I have written an extension method to wrap this functionality for you

public static class Extensions
{
 
public static AsyncCallback Try(this AsyncCallback cb, Action<Exception> exceptionAction)
 
{
   
AsyncCallback wrapper = delegate(IAsyncResult iar)
    {
     
try
     
{
       
cb(iar);
     
}
     
catch (Exception e)
     
{
       
exceptionAction(e);
     
}
   
};
   
return wrapper;
  }
}

So this code extends AsyncCallback and takes a delegate to call if an exception takes place it then wraps its own AsyncCallback around the one passed in this time putting it in a try … catch block. The usage looks like this:

Action a = DoStuff;
AsyncCallback cb = ia => a.EndInvoke(ia);
a.BeginInvoke(cb.Try(e => Console.WriteLine(e)), null);

The only awkward thing here is having to take the lambda out of the call to BeginInvoke because the C# compiler won’t allow the dot operator on a lambda (without casting it to an AsyncCallback) but at least this wraps up some of the issues

Wednesday, March 18, 2009 5:37:08 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Saturday, March 14, 2009

I’ll be speaking at DevWeek in a couple of weeks. Doing a normal session and a post conference day

Tuesday 24th March: Introduction to the Windows Workflow Foundation
There are many challenges to writing software. Not least of these are lack of transparency of code and creating software that can execute correctly in the face of process or machine restart. Windows Workflow Foundation (WF) introduces a new way of writing software that solves these problems and more. This session explains what WF brings to your applications, and how it works. Along the way we will see the major features of WF that make it a very powerful tool in your toolkit, removing the need for you to write a lot of complex plumbing.

Friday 27th March: A Day of Connected Systems with .NET 4.0 and Oslo
The next version of .NET comes with major improvements to the workflow world in terms of performance, usability and new execution models. It also has a feature-rich infrastructure for integrating with WCF to create workflow-based services. At the same time Oslo introduces a modelling platform that can be used to model these workflow services and the application around them using a repository, modelling tool and modelling language.
This one-day seminar walks you through the latest offerings from Microsoft’s Connected Systems Division, and discusses not only how they affect the software you write tomorrow, but also what it all means for the software you write today.

Hope to see you there

Saturday, March 14, 2009 11:48:25 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Tuesday, March 03, 2009

I talked about the new WF4 Runtime model a while back. One of the things I discussed was the new data flow model of arguments and variables. However, if you are used to WF 3.5 something looks a bit odd here. Lets look at a simple activity example:

public class WriteLineActivity : WorkflowElement
{
    public InArgument<string> Text { get; set; }
    protected override void Execute(ActivityExecutionContext context)
    {
        Console.WriteLine(Text.Get(context));
    }
}

Why do I need to pass the ActivityExecutionContext when I want to get the data from the argument? This highlights a subtlety to the change in the runtime model. The activity is really just a template. A class called ActivityInstance is the thing that is actually executed, it just has a reference to the actual activity to be able to hand off to the activty’s methods (e.g. Execute). The actual argument state is stored in a construct called the LocalEnvironment. The ActivityExecutionContext gives access to  the current ActivityInstance and that in turn holds a reference to the current LocalEnvironment. Therefore, to get from  an activity’s Execute method to its state we have to go via the ActivityExecutionContext.

.NET | WF
Tuesday, March 03, 2009 9:41:42 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Wednesday, February 25, 2009

I’ve finally got round to pushing the code for BlobExplorer to CodePlex. You can find the CodePlex site here. If you want to contribute to the project, let me know at richard at nospam dotnetconsult dot co dot uk and I’ll add you to the contributors list. The releases will continue being pushed to blob storage http://dotnetconsult.blob.core.windows.net/tools/BlobExplorer.zip

Wednesday, February 25, 2009 2:59:12 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   | 
# Friday, February 20, 2009

A while back I did this post talking about how WCF contract definitions should model the messages being passed and not use business  objects. This inevitably  means that you have to translate from the Data Transfer Object (DTO) in the contract to business object and back again. This can feel like a lot of overhead but it really does protect you from a lot of heartache further down the line.

However Dom just pointed out the AutoMapper to me. This is in its early stages but looks like the kind of library that will really take away a lot of the grunt work associated with using DTOs – kudos!

.NET | WCF
Friday, February 20, 2009 6:55:55 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |   |