+44 (0)1179 113711

Rock Solid Knowledge Blogs

An aggregation of all the Rock Solid Knowledge Blogs

Subscribe  Subscribe

Problem When Upgrading From Rails 2.2.2 to 2.3.2

I've just installed the latest Active* gems to move my Rails install to 2.3.2. When I ran a console I got the following error

Loading development environment (Rails 2.3.2)
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:443:in `load_missing_constant':NameError: uninitialized constant ApplicationController 

I googled this and found a couple of posts on the issue but nothing obvious that I was doing. After generating a 2.3.3 app and comparing files the solution was obvious and easy. I 2.2.2 the ApplicationController class is in a file called Application.rb, in 2.3.2 this has changed to application_controller.rb. Changing the file name has fixed my problem.

Posted 16/04/2009

Extension Methods and Good Practice – or OI! Get Out of my Namespace!

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.

Posted 05/04/2009 Richard Blewett

DevWeek 2009 Demos

Are now available on the Rock Solid Knowledge site. I've upload the 'So you think you now JavaScript', 'Design for Testing' and Day of 'Ruby and Rails' talks. Andy's already put up the 'Day of Patterns' and 'Patterns Dartboard' talks
Posted 02/04/2009

Ruby idioms in ASP.Net MVC

In Rails there is a mechanism by which you can mimic variadic methods (Ruby also supports true variadic methods) by treating the last parameter as a hash. I can write a function definition like this

def pass_a_hash(s, h) 
  puts s
  h.each { |key, value| puts "#{key} => #{value}"} if h.class == Hash  
end

and call it either like

pass_a_hash "kevin", {:a => "b", :c => "d"}
or
pass_a_hash "kevin", :a => "b", :c => "d"
either way this prints
kevin
a => b
c => d

The second style is much neater, it hides the use of the hash and instead makes it seem like we are using named parameters. This is used all over Rails, especially on web pages where you need to specify things such as controllers and actions. You will often see code like:

<%= link_to "Add", :action => :add, :controller => :students %>

Here we are calling the 'link_to' method passing a string and a hash of options, just like above

Microsoft (bless 'em) have tried to mimic this in ASP.Net MVC by letting you can write code similar to the 'link_to' Rails method. On an ASP.Net view you can do something like:

<%= Html.RouteLink("Add", new {action = "add", controller = "students"}) %>

And this adds a link to the page with the text "Add" and a url something like http://server.com/students/add. This is similar to ActionLink and they both eventually call into a method called GenerateRouteLink. In the ASP.Net case the second parameter is not a hash (oh for first class hashes in C#) but an instance of an anonymous class. Using Reflector we can see what this method does.

Internally RouteLink creates a RoutedDictionary passing the anonymous instance as a parameter to its constructor

    return htmlHelper.RouteLink(linkText, new RouteValueDictionary(routeValues));

The RouteValueDictionary constructor looks like this

public RouteValueDictionary(object values)
{
    this._dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    this.AddValues(values);
}

and AddValues does this:

private void AddValues(object values)
{
    if (values != null)
    {
        foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
        {
            object obj2 = descriptor.GetValue(values);
            this.Add(descriptor.Name, obj2);
        }
    }
}

public void Add(string key, object value)
{
    this._dictionary.Add(key, value);
}

So AddValues uses reflection to build a dictionary of name/value pairs

Just like in Rails, when the element is rendered this dictionary is interrogated and the values used to build the URL.

Neat, but still more ceremony than in Ruby!

Posted 01/04/2009

Ruby Essence vs Ceremony

Last week at DevWeek Tim Ewald and I tried to show some of the elegance of Ruby and I'd like to try and repeat that example here.

We started with a Lion class in honour of the news story that week about "Christian the Lion" (hey, look it up yourselves!). The class is very simple

class Lion

  attr_accessor :message, :name

  def speak
    @message
  end

  def to_s
    "#{self.name} says #{self.message}"
  end

  @@lions = {}

  def self.create message, name
    if @@lions[name] == nil
      @@lions[name] = Lion.new(message, name)
    end
    return @@Lions[name]
  end

  def initialize(message, name)
    @message = message
    @name = name
  end

end

The bit we care about is the self.create method. The idea here is that we provide a function to only allow the creation of one lion with any given name (this was a demo so it didn't need to make sense). To do this there is a class level dictionary (a static) in which to store new lions. We only add lions to this dictionary if they are unique, otherwise we return an existing lion. The code as it is written is not very Ruby-ish, it reads more like C++, C# or Java code than Ruby and that's what I'd like to change.

The first step is to remove the 'return' keyword. In Ruby the last statement in a method is the return value so we can change the code to look like this:

def self.create message, name
  if @@lions[name] == nil
    @@lions[name] = Lion.new(message, name)
  end
  @@Lions[name]
end

The 'if' statement isn't very idiomatic either and in Ruby this can be reduced to

def self.create message, name
  @@lions[name] = Lion.new(message, name) if @@lions[name] == nil 
  @@lions[name]
end

We're still not quite there though. Ruby (like C#) has a 'null co-alescing' operator, which lets me say "if 'x' is not null, use it, else do 'y'", and I can rewrite the above 'if' using this operator (|| in Ruby). It also means I can do away with the final return statement

def self.create message, name
  @@lions[name] || @@lions[name] = Lion.new(message, name)
end

Which says, if @@lions[name] is not null return the value, else assign Lion.new to @@lions[name] and return that value

One line to do what it would take four lines to do in other languages and no keywords. As my friend Stu Halloway would put it, essence over ceremony!

Posted 01/04/2009

Dev Week 2009

Just finished DevWeek 2009

It's been another great week. Spent time with people I haven't seen for a while. I've enjoyed giving the talks and hope you have enjoyed listening to them. I always love spending time hanging out the speakers, there are so many really smart people there. Just spent a day with Tim Ewald - it always blows me away how good a presenter Tim is and how much he knows, this time on Ruby and Rails.

Hopefully I'll be back for Software Architect in Sept/Oct and at DevWeek next year.

Posted 27/03/2009

Slides and demos from my Windows Workflow Session at Devweek

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

Posted 26/03/2009 Richard Blewett

A Tale of Two Reader/Writer Locks

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.

Posted 23/03/2009 Richard Blewett

Keeping things safe wth AsyncCallback

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

>>
Posted 18/03/2009 Richard Blewett

VSTS Load/Web Testing and Browser Definitions

When you add a VSTS load test or when you configure a web test you can specify the browser(s) to use for the test. The data for each type of browser is held in files with a .browser extension in the C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Templates\LoadTest\Browsers directory.

You can add your own browsers to this list by copying and renaming one of these files and changing the details within the file. The files are XML so this is easy to do, they look something like this

<Browser Name="Netscape 6.0">
  <Headers>
    <Header Name="User-Agent" Value="Mozilla/5.0 (Windows; U; Windows NT 5.0; en; rv:1.0) Netscape/6.0" />
    <Header Name="Accept" Value="image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*" />
    <Header Name="Accept-Language" Value="{{$IEAcceptLanguage}}" />
    <Header Name="Accept-Encoding" Value="GZIP" />
  </Headers>
</Browser>


Remember to change the Name attribute on the Browser element otherwise you'll see the same browser listed twice inside visual studio.

After making the changes you will need to re-start Visual Studio to see your new browser listed.

Posted 16/03/2009

WF4: Why do I have to pass the context to get data from an argument?

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.

>
Posted 03/03/2009 Richard Blewett