tag:blogger.com,1999:blog-35189456784698522732024-03-02T10:30:30.740+00:00Jahya Code .NET::: A blog on constructing web applications in C# .NET :::Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.comBlogger18125tag:blogger.com,1999:blog-3518945678469852273.post-82332260893498392662012-03-27T14:57:00.000+01:002012-03-27T14:57:44.212+01:00Introduction to Covariance and Contravariance in C#<p>Covariance and contravariance have <a href="http://en.wikipedia.org/wiki/C_Sharp_4.0#Covariant_and_contravariant_generic_type_parameters">had a tweak</a> in C# 4.0. But before we can start using the benefits in our code, we need to know exactly what they are! The subject can be a little bit tricky when you first encounter it, so in this post I'm going to introduce it in a way that I hope is easy to follow.</p>
<p>Almost all of the information in this post comes from Eric Lippert's <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx">excellent series of posts</a>, and I recommend you go and take a look at his blog right now (links to the whole series are at the bottom of this post.)</p>
<table class="tr-caption-container" style="float: right; margin-left: 1em; text-align: right;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSn37VQPfhMmFLCkjsEEEk2nBR4xtCvM6-vZJskiUXic3XzHLjpoP3kK3BNVEUFw5rN9WkcS-7V-xHPTUjOrBYloplitqbtLTnM9oSeswvcegDRx6oYANbXlsWMo5SctyX-oSk9VDxFf8y/s1600/2360443334_3cd52b5de1.jpg" style="clear: right; margin-bottom: 1em; margin-left: auto; margin-right: auto;"><img alt="Tigers and a giraffe" height="213" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSn37VQPfhMmFLCkjsEEEk2nBR4xtCvM6-vZJskiUXic3XzHLjpoP3kK3BNVEUFw5rN9WkcS-7V-xHPTUjOrBYloplitqbtLTnM9oSeswvcegDRx6oYANbXlsWMo5SctyX-oSk9VDxFf8y/s320/2360443334_3cd52b5de1.jpg" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Tigers and a giraffe (credit: <a href="http://www.flickr.com/photos/andrewmalone/">andrewmalone</a>)</td></tr>
</tbody></table>
<p>If you 'get it' straight away, great - stick with that, he's the expert. If you'd like a slightly gentler introduction, avoiding (I hope!) common 'gotchas' for learning the subject, read my post (this post) first.</p>
<p>What I have done is to explain the same concepts using the same examples, but in an order and with an emphasis which I think make it much easier to understand the basics. This is particularly good for you if you are a programmer coming at it from the cold, i.e. you haven't encountered covariance and contravariance before, or you have but you don't understand them yet.</p>
<p>When you're done here I'd suggest you go back and read Eric's posts in order - they should be much easier for you to read by then. Eric's posts will flesh out all the interesting details, and continue on to discuss more advanced topics.</p>
<p><strong>Inheritance and assignability</strong><br />
We're not going to begin talking about covariance and contravariance straight away. First, we're going to make a distinction between inheritance and assignability.</p>
<p>As Eric points out, for any two types <code>T</code> and <code>U</code>, exactly one of the following statements is true:</p>
<ul>
<li><code>T</code> is bigger than <code>U</code></li>
<li><code>T</code> is smaller than <code>U</code></li>
<li><code>T</code> is equal to <code>U</code></li>
<li><code>T</code> is not related to <code>U</code></li>
</ul>
<p>Now, one of the things that seems to have caused some confusion on Eric's blog (see the <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx">comments</a>) is usage of the phrase "is smaller than". It is used frequently, and is key, so I want to make it's definition crystal clear now before we move on. Eric says:</p>
<blockquote>"Suppose you have a variable, that is, a storage location. Storage locations in C# all have a type associated with them. At runtime you can store an object which is an instance of an <span style="font-style:italic">equal or smaller type</span> in that storage location."</blockquote>
<p>In simple scenarios, this is something so familiar to programmers that it's barely worth mentioning. We all know that, looking at the list above, only in the middle two scenarios is <code>T</code> assignable to <code>U</code>. The <span style="font-style:italic">smaller than</span> relation:</p>
<pre class="brush:csharp">
class U{}
class T : U{}
U myInstance = new T();
</pre>
<p>This is the first thing that comes to mind, right? An inheritance hierarchy.</p>
<p>But Eric didn't mention inheritance hierarchies. Sure, an inheritance hierarchy is <span style="font-style:italic">one way</span> to make a <code>T</code> which is assignable to a <code>U</code>, but what about this one:
<pre class="brush:csharp">
U[] myArray = new T[10];
</pre>
<p>... or, the same statement using classes from the <a href="http://www.codeproject.com/Articles/42863/Covariance-and-Contravariance-in-C">animals hierarchy</a>:</p>
<pre class="brush:csharp">
Animal[] animals = new Giraffe[10];
</pre>
<p>The type <code>Animal</code> inherits from <code>Giraffe</code>, but the type <code>Animal[]</code> doesn't inherit from <code>Giraffe[]</code>. They are assignable, but not linked by inheritance, and this tells us something about what 'is smaller than' means:</p>
<ul>
<li><code>T</code> is smaller than <code>U</code></li>
</ul>
<p>can be read as</p>
<ul>
<li><code>T</code> is assignable to <code>U</code></li>
</ul>
<p>You can visualise it this way:</p>
<pre class="brush:csharp">
T is smaller than U
T < U
--> //Direction of assignability
</pre>
<p>As we have seen, in some cases this direction of assignability may be because of an inheritance relationship, but in others it is simply because the CLR and languages (C#, Java etc.) happen to support that particular assignment operation.</p>
<p>There is still an inheritance hierarchy <span style="font-style:italic">involved</span>, i.e. this wouldn't work:</p>
<pre class="brush:csharp">
Tiger[] tigers = new Giraffe[10]; //illegal
</pre>
<p>But the key thing is that there is a <span style="font-style:italic">difference</span> between inheritance and assignability: they are not the same thing.</p>
<p>I'll say it one more time (for good luck!): The phrase "is smaller than" refers to assignability, not inheritance. The direction of assignability always flows from the smaller type to the larger type. We'll come back to this in a moment.</p>
<p><strong>Covariance and Contravariance</strong><br />
Eric's <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx">second post</a> discusses the array assignment operation (the one I used in the <code>Animal</code>/<code>Giraffe</code> example above), and the problems with it. It's definitely worth reading, but park it for now, because things really come alive in <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/19/covariance-and-contravariance-in-c-part-three-member-group-conversion-variance.aspx">post number three</a>.
<p>Eric's example uses <a href="http://jahyacode.blogspot.com/2011/07/introduction-to-delegates-in-c.html">delegate methods</a>, and I'll use a simplified version of it here, just to get us started.</p>
<p>It is clear why this is a legal operation:</p>
<pre class="brush:csharp">
static Giraffe MakeGiraffe()
{
return new Giraffe();
}
//Inside some method:
Func<Animal> func = MakeGiraffe;
// <-- Direction of assignment
</pre>
<p>Notice that in the assignment operation, <code>Animal</code> is on the left and <code>Giraffe</code> is on the right. That is, the declared type is based on <code>Animal</code> and the assigned type is based on <code>Giraffe</code>.
<p>Now let's look at another example:</p>
<pre class="brush:csharp">
static void AcceptAnimal(Animal animal)
{
//operate on animal
}
//Inside some method:
Action<Giraffe> action = AcceptAnimal;
// <-- Direction of assignment
</pre>
<p>Notice that <code>Giraffe</code> is on the left and <code>Animal</code> is on the right. That is, the declared type is based on <code>Giraffe</code> and the assigned type is based on <code>Animal</code>.
<p>The <code>Func<out T></code> assignment operation supports <span style="font-style:italic">covariance</span>. The <code>Action<in T></code> assignment operation supports <span style="font-style:italic">contravariance</span>.</p>
<p><strong>What does that mean?</strong><br />Have a quick look at this summary:
<br /><span style="font-style:italic">(remember to read < as 'is smaller than' <span style="font-weight:bold">and</span> 'is assignable to')</span></p>
<pre class="brush:csharp">
//Direction of assignability -->
Giraffe < Animal
Giraffe MakeGiraffe() < Func<Animal> //covariance
AcceptAnimal(Animal animal) < Action<Giraffe> //contravar..
</pre>
<p>Now read Eric's definition of covariance and contravariance, from the <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx">first post</a> in his series:<br /><span style="font-style:italic">(the "operation" which manipulate types being the two assignment operations)</span></p>
<blockquote>Consider an "operation" which manipulates types. If the results of the operation applied to any T and U always results in two types T' and U' with the <span style="font-style:italic">same</span> relationship as T and U, then the operation is said to be "covariant". If the operation <span style="font-style:italic">reverses bigness and smallness</span> on its results but <span style="font-style:italic">keeps equality and unrelatedness the same</span> then the operation is said to be "contravariant".</blockquote>
<p>Hopefully it should start to become clear. In line 4 above, the direction of assignability with respect to the original types, was <span style="font-style:italic">preserved</span>, while in line 5 it was <span style="font-style:italic">reversed!</span></p>
<p>Line 4 represents a <span style="font-style:italic">covariant</span> operation, and line 5 represents a <span style="font-style:italic">contravariant</span> operation.</p>
<p><strong>The main heuristic</strong><br />
Let's put it back to C# code so that we can see it with the right-to-left assignability we are used to (now the smaller types are on the right):</p>
<pre class="brush:csharp">
Animal animal = new Giraffe(); //basic type assignment
Func<Animal> func = MakeGiraffe; //covariant
Action<Giraffe> action = AcceptAnimal; //contravariant
// <-- Direction of assignability
</pre>
<p>Notice how in the <span style="font-style:italic">covariant</span> operation, <code>Animal</code> and <code>Giraffe</code> are on the same sides as in the basic type assignment operation. And notice how in the <span style="font-style:italic">contravariant</span> operation, they are on opposite sides - the operation "reverses bigness and smallness".</p>
<p>In both cases, the opposites are illegal. As Eric puts it in <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/24/covariance-and-contravariance-in-c-part-five-higher-order-functions-hurt-my-brain.aspx">post number five</a>:</p>
<blockquote style="font-weight:bold">"Stuff going 'in' may be contravariant,<br />stuff going 'out' may be covariant"</blockquote>
</p>... but not vice-versa:</p>
<pre class="brush:csharp">
Func<Giraffe> func = MakeAnimal; //contravariant (illegal)
Action<Animal> action = AcceptGiraffe; //covariant (illegal)
// <-- Direction of assignability
</pre>
<p>And by the way, if there's one heuristic you remember as a result of reading this post, it's probably best to make it the one above!</p>
<p>I'll repeat it later in this article.</p>
<p><strong>Hang on, methods aren't types!</strong><br />
A quick aside - at this stage you might be asking why I'm referring to methods as though they were types. The straight answer is, I'm copying Eric. His caveat:</p>
<blockquote>"A note to nitpickers out there: yes, I said earlier that variance was a property of operations on types, and here I have an operation on method groups, which are typeless expressions in C#. I’m writing a blog, not a dissertation; deal with it!"</blockquote>
<p>Can't argue with that.</p>
<p><strong>What's new in C# 4.0?</strong><br />
Well, 'new' is the wrong word since the <a href="http://en.wikipedia.org/wiki/C_Sharp_4.0">stable release</a> of C# 4.0 was two years ago! But all of the types of variance we've looked at so far in this post have been supported since C#2 or before.</p>
<p>We as developers didn't really have to think about those types of variance to use them, because it wasn't exposed syntactically. In other words, we didn't have to write anything different to make it happen, it's just what is and what isn't supported by C# compilers and the CLR.</p>
<p>In post numbers <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/22/covariance-and-contravariance-in-c-part-four-real-delegate-variance.aspx">four</a> and <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx">six</a>, Eric discusses types of variance which went on to become part of the specification for C# 4.0, and it's those types of variance that I'll discuss now.</p>
<p><strong>Real delegate variance</strong><br />
The first one is easy, and it's discussed in <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/22/covariance-and-contravariance-in-c-part-four-real-delegate-variance.aspx">post number four</a>. It's simply about taking the operations which were already legal in terms of method groups and making the same operations legal in terms of typed expressions.</p>
<p>Take our covariant example from earlier:</p>
<pre class="brush:csharp">
static Giraffe MakeGiraffe()
{
return new Giraffe();
}
//Inside some method:
Func<Animal> func = MakeGiraffe;
// <-- Direction of assignment
</pre>
<p>Well, in C#3 this <span style="font-style:italic">essentially equivalent</span> operation was illegal, whereas in C#4 it is legal:</p>
<pre class="brush:csharp">
Func<Animal> func = new Func<Giraffe>(() => new Giraffe());
// <-- Direction of assignment
</pre>
<p>In fact because of <a href="http://jahyacode.blogspot.co.uk/2011/07/lambda-expressions-in-c.html">lambda syntax</a> and inferred typing, it can be shortened to:</p>
<pre class="brush:csharp">
Func<Animal> func = () => new Giraffe();
// <-- Direction of assignment
</pre>
<p>You can now do with typed expressions what you could already do with method groups. Simple.</p>
<p>But here's where it makes sense to quickly explain something I breezed over earlier. </p>
<p><strong>Covariance <span style="font-style:italic">and</span> Contravariance, at once</strong><br />
Take a look again at the heuristic:</p>
<blockquote>"Stuff going 'in' may be contravariant,<br />stuff going 'out' may be covariant"</blockquote>
<p>So what happens when you are dealing with a type which has both an 'in' and an 'out'?</p>
<p>The short answer is: it can be covariant, contravariant, both, or neither. But it's <span style="font-style:italic">easier than that makes it sound!</span></p>
<p>Take a look at this example. It's a <code>Func</code> that accepts a <code>Mammal</code> and returns a <code>Mammal</code>:
<pre class="brush:csharp">
Func<Mammal, Mammal> func;
</pre>
<p>Now here are some assignment operations:</p>
<p><ul><li>This is a <strong>covariant</strong> operation:</li></ul></p>
<pre class="brush:csharp">
Func<Mammal, Giraffe> toAssign = //somehow initialise;
Func<Mammal, Mammal> func = toAssign;
</pre>
<p><ul><li>This is a <strong>contravariant</strong> operation:</li></ul></p>
<pre class="brush:csharp">
Func<Animal, Mammal> toAssign = //somehow initialise;
Func<Mammal, Mammal> func = toAssign;
</pre>
<p><ul><li>This is <strong>both</strong>:</li></ul></p>
<pre class="brush:csharp">
Func<Animal, Giraffe> toAssign = //somehow initialise;
Func<Mammal, Mammal> func = toAssign;
</pre>
<p>... and, well, I'm sure I don't need to spell out the <strong>neither</strong>!</p>
<p><strong>Interface variance</strong><br />
The other new feature, as discussed in <a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx">post number six</a>, is the extension of variance to interfaces. There's not much to add here - it's just the same thing, but using interfaces. Eric gives a really nice example of the practical benefit here, and I'm going to repeat it almost verbatim.</p>
<p>Take a look at this code block. This is another example of something which is illegal in C#3, and legal in C#4:
<pre class="brush:csharp">
void FeedAnimals(IEnumerable<Animal> animals) {
foreach(Animal animal in animals)
if (animal.Hungry)
Feed(animal);
}
//...
IEnumerable<Giraffe> adultGiraffes =
from g in giraffes where g.Age > 5 select g;
FeedAnimals(adultGiraffes);
</pre>
<p>Just as earlier on, when we call <code>FeedAnimals(IEnumerable<Animal> animals)</code> we are assigning a 'smaller' type to a 'larger' type:</p>
<pre class="brush:csharp">
//Direction of assignability -->
Giraffe < Animal
Giraffe MakeGiraffe() < Func<Animal> //covariance
IEnumerable<Giraffe> < IEnumerable<Animal> //covariance
</pre>
<p>Of course, anywhere else that you reference that assigned-to variable (<code>IEnumerable<Animal></code>), what comes out will be typed as <code>Animal</code>. All pretty uncontroversial.</p>
<p><strong>In and out</strong><br />But finally, let's look at the <code>in</code> and <code>out</code> keywords, and how they fit in when designing your own interfaces (or using the upgraded C#4 ones.) Recall one more time the heuristic:</p>
<blockquote>"Stuff going 'in' may be contravariant,<br />stuff going 'out' may be covariant"</blockquote>
<p>In C# 4.0, <code>IEnumerable<T></code> <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx">has become</a> <code>IEnumerable<out T></code>. The <code>out</code> marks the <code>IEnumerable</code> as supporting covariance on the <code>T</code>. This means that, as in the example above, you can assign based on something smaller than <code>T</code>.</p>
<p>But it also means that the interface <span style="font-style:italic">cannot accept the type <code>T</code> as an input!</span> It will only allow the interface to send <code>T</code> out, in whatever fashion you like - but it will never accept a <code>T</code> in. If you try it, the compiler won't allow it. Hence, the name: <code>out</code>.</p>
<p>Reading through this code block should make it clear why:</p>
<pre class="brush:csharp">
//the compiler won't allow this, but go with it to see why:
interface ICustom<out T>
{
T GetFirst(); //ok
void Insert(T t); //compiler complains
}
//..
ICustom<Giraffe> giraffes = //somehow init;
ICustom<Animal> animals = giraffes;
Animal animal = animals.GetFirst(); //ok
animals.Insert(new Tiger()); //problem -
//backing store is Giraffe
</pre>
<p>Think of it this way - an <code>IEnumerable<Animal></code> variable can have an <code>IEnumerable<Giraffe></code> assigned to it and it will churn out <code>Giraffe</code>s typed as <code>Animal</code>s all day long. Because of how it's declared, users of the <code>IEnumerable<Animal></code> variable expect to be dealing with <code>Animal</code>s.</p>
<p>But a <code>Tiger</code> is also an animal. What would happen if there were a method on the interface that allowed a user to put an <code>Animal</code> in?</p>
<p>The user could put a <code>Tiger</code> in instead, and the backing store - <code>IEnumerable<Giraffe></code> - wouldn't be able to cope.</p>
<p><strong>The same in reverse</strong><br />Now here's a similarly invalid code block, this time using the <code>in</code> keyword:</p>
<pre class="brush:csharp">
//the compiler won't allow this, but go with it to see why:
interface ICustom<in T>
{
T GetFirst(); //compiler complains
void Insert(T t); //ok
}
//..
ICustom<Animal> animals = //somehow init;
ICustom<Giraffe> giraffes = animals;
giraffes.Insert(new Giraffe()); //ok
Giraffe giraffe = giraffes.GetFirst(); //problem
//backing store is Animal
</pre>
<p>So when a type is marked as <code>out</code>, it's <code>out</code> only. And when a type is marked as <code>in</code>, it's <code>in</code> only too! A type can't be both <code>in</code> and <code>out</code>.</p>
<p><strong>How to read it</strong><br />
So when you read an <code>out</code> type in an interface, read it this way:</p>
<pre class="brush:csharp">
interface ICustom<out T>
{
//You can initialise me using <=T
//And I will use it as a backing store
//But I will only send T's out-wards
//Because T's coming in could be too wide
// for my <=T backing store
}
</pre>
<p>And for an <code>in</code> type in an interface:</p>
<pre class="brush:csharp">
interface ICustom<in T>
{
//You can initialise me using >=T
//And I will use it as a backing store
//But I will only accept T's in-wards
//Because my >=T backing store is too wide
// to produce T's to send out
}
</pre>
<p>If it helps, try reading those again - but this time, with the <code>out T</code> interfaces read <code>T</code> as <code>Animal</code> and <code><=T</code> as <code>Giraffe</code>.</p>
<p>And with the <code>in T</code> interfaces read <code>T</code> as <code>Giraffe</code> and <code>>=T</code> as <code>Animal</code>.</p>
<p><strong>Or, more concisely</strong><br />
Here's <code>out</code> again more concisely:</p>
<pre class="brush:csharp">
interface ICustom<out T>
{
//covariant
//assign a smaller T, i'll only send it out
}
</pre>
<p>And for <code>in</code>:</p>
<pre class="brush:csharp">
interface ICustom<in T>
{
//contravariant
//assign a larger T, i'll only take it in
}
</pre>
<p>I hope that helps!</p>
<p><strong>The payoff</strong><br />
As Eric points out, the only way to make the above example of <code>FeedAnimals</code> work in C#3 is to use a "silly and expensive casting operation":</p>
<pre class="brush:csharp">
FeedAnimals(adultGiraffes.Cast<Animal>());
//or
FeedAnimals(from g in adultGiraffes select (Animal)g);
</pre>
<p>He goes on:</p>
<blockquote>"This explicit typing should not be necessary. Unlike arrays (which are read-write) it is perfectly typesafe to treat a read-only list of giraffes as a list of animals"</blockquote>
<p>And the example which Eric suggests hypothetically in that post, Matt Hidinger later <a href="http://www.matthidinger.com/archive/2010/04/07/introduction-to-c-4-covariance-with-the-is-keyword.aspx">demonstrates for us</a> using C#4!</p>
<p><strong>The full series</strong><br />
That's about as much as I want to write on the subject!</p>
<p>Below are links to the full series. Bear in mind that these explanatory posts were written prior to the release of C# 4.0. But they are still an excellent programmer's introduction, with much more info than I have covered in this post:</p>
<ul>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx">1. Introduction</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx">2. Array Covariance</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/19/covariance-and-contravariance-in-c-part-three-member-group-conversion-variance.aspx">3. Method Group Conversion Variance</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/22/covariance-and-contravariance-in-c-part-four-real-delegate-variance.aspx">4. Real Delegate Variance</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/24/covariance-and-contravariance-in-c-part-five-higher-order-functions-hurt-my-brain.aspx">5. Higher Order Functions Hurt My Brain</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx">6. Interface Variance</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/29/covariance-and-contravariance-in-c-part-seven-why-do-we-need-a-syntax-at-all.aspx">7. Why Do We Need A Syntax At All?</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/10/31/covariance-and-contravariance-in-c-part-eight-syntax-options.aspx">8. Syntax Options</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/11/02/covariance-and-contravariance-in-c-part-nine-breaking-changes.aspx">9. Breaking Changes</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2007/11/09/covariance-and-contravariance-in-c-part-ten-dealing-with-ambiguity.aspx">10. Dealing With Ambiguity</a></li>
<li><a href="http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx">11. To infinity, but not beyond</a></li>
</ul>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com5tag:blogger.com,1999:blog-3518945678469852273.post-77738084276021370992012-03-19T14:33:00.000+00:002012-03-20T08:23:48.317+00:00A TDD Example: The Mars Rover Problem<p>I learned TDD the hard way - while doing feature development on an existing, poorly tested enterprise application. I wanted to see TDD in action on a small greenfield project, so I decided to write a solution to the <a href="http://veerasundar.com/blog/2010/06/mars-rover-in-java/">Mars Rover problem</a>.</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9xainxZ6876qH06SE7YEnREmOXPYkUNyQmHEEvDxmWKe7buDllgX5wysTWNY19cV0bwtK5J8YxNtqDdEKJwz-HOP4s3X7gosHTFmSF8DXgK9EOsJal9OQ_4Uc-W5LHMFIiehTSMkzdj2D/s1600/600px-Mars_Rover_Stuck.jpg" style="clear:right; float:right; margin-left:1em; margin-bottom:1em"><img alt="A Mars Rover stuck in a sand dune" height="320" width="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9xainxZ6876qH06SE7YEnREmOXPYkUNyQmHEEvDxmWKe7buDllgX5wysTWNY19cV0bwtK5J8YxNtqDdEKJwz-HOP4s3X7gosHTFmSF8DXgK9EOsJal9OQ_4Uc-W5LHMFIiehTSMkzdj2D/s320/600px-Mars_Rover_Stuck.jpg" /></a></div>
<p>The Mars Rover is a problem that I have been set by more than one prospective employer in the past. Previously I had solved it 'test-after', this time I wanted to solve it test-first.</p>
<p>As a result I came up with a completely different architecture. The main reason for this is that TDD encourages continuous refactoring, and high test coverage gives you confidence to improve system design as you go, without worrying about regressions.</p>
<p>In this post I want to briefly describe how I used TDD to grow the project, particularly as a reference and talking point for other newcomers to TDD. I'll describe how and why I used TDD, in Mars-Rover-problem context, and at the end you will be able to go and explore the codebase to see how it ended up. (Or ofcourse you can just skip the garb and go <a href="http://github.com/microcosm/MarsRover">check out the project</a>.)</p>
<p>I'm really interested in feedback, so if you have any thoughts as you read, please do leave comments or drop me an email.</p>
<p><strong>The Mars Rover problem</strong><br />A quick disclaimer: The Mars Rover problem is simple and there are many solutions floating around on the web (some have slightly different problem specs, <a href="https://github.com/microcosm/MarsRover#readme">click here</a> to see the one I implemented). The first thing you'll notice when looking at my solution is that <strong>it is 100% overkill!</strong></p>
<p>For a problem with such defined boundaries, and more importantly a problem you know will never change or grow, you could code up a very simple solution. You may not even have to use OOP at all.</p>
<p>However, I work every day on enterprise systems and I wanted my solution to be relevant to some of those challenges - to be extendable, testable, expressive and understandable. I wanted to explore a small, limited problem with a few basic stories, so that I could share the results and move on from it.</p>
<p>Importantly then, the Mars Rover problem doesn't require any particular presentation or persistence technologies. These are very important subjects, but I have descoped them and they can be the <a href="http://www.arrangeactassert.com/how-to-unit-test-asp-net-mvc-controllers/">subject of other posts</a>.</p>
<p><strong>Let's get started already!</strong><br />You can download the project here:</p>
<ul><li><a href="http://github.com/microcosm/MarsRover">http://github.com/microcosm/MarsRover</a></li></ul>
<p>You can also just browse the source code via the github website, but if you are a C# developer you might want to launch it in VS so you can run the tests and explore using ReSharper.</p>
<p><strong>A good story</strong><br />Before writing any code, I went through a short analysis phase (see the <a href="https://github.com/microcosm/MarsRover/tree/master/Analysis">Analysis directory</a>), and one of the artifacts of that phase was the generation of a short list of acceptance criteria: </p>
<ol>
<li>Interprets GridSizeCommand, initializes Grid and sets size</li>
<li>Interprets RoverDeployCommand, deploys Rovers, Rovers report their position without moving</li>
<li>Interprets RoverExploreCommand, Rovers move and turn before reporting</li>
</ol>
<p>Each of the items on the list represent a small chunk of demonstrable progress, or in other words a story. These aren't necessarily stories which make immediate sense to a system user (what's the point of being able to deploy a rover without moving it?)</p>
<p>Nonetheless they are good stories, because they represent incremental progress toward a stated aim. If a story is too large it becomes a 'black hole' into which development time and resources are spent without any realistic measure of progress.</p>
<p>(My approach to creating acceptance criteria, and to much else in this post, was inspired by Steve Freeman and Nat Pryce's <a href="http://www.growing-object-oriented-software.com">Growing Object-Oriented Software, Guided by Tests</a>, as suggested by my colleague <a href="http://tech-journals.com">JonoW</a>.)</p>
<p>I later added a fourth acceptance criterion:</p>
<ol start="4">
<li>Given input string defined in problem statement, produces output string defined in problem statement</li>
</ol>
<p>After all, that is the <span style="font-style:italic">only</span> acceptance criterion expressed in the problem spec, so it would be crazy to miss it out!</p>
<p><strong>Criteria become acceptance tests</strong><br />The acceptance criteria can then translate (almost) literally into the names of the acceptance tests:</p>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhD5NrNyUMllauSyURELYnNnc2OUhMyaiUE-fpyXDFLFlhRMBUTqYIK2iicQgLOY7w9Buvn8JjiDiPmnreZ9P8ggEO4rIS7BoBuQQa6tsmpDqARNzQeVev93y0nf2BtnE_gFDqr9kRBqFxj/s1600/1acceptancetests_full.png"><img alt="Acceptance tests" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgIxo1ZSrHVGu6yxSxJ8e3HuGAu75c8dcbY7yaaouGPsukpDoQOB2gu9uTAF5CIn8r_D_v52s3lRD5yAVUBDIv787e2C_fcCgz6sFtPQs4INsa_myzxwNXd8XXTx6Le5jQpxvnxZKAd_uH6/s1600/1acceptancetests.png" /></a>
<p>(You'll notice that some of the names are different, for example at some point I changed the word <code>Grid</code> to become <code>LandingSurface</code>, which is more expressive of this particular problem domain.)</p>
<p>What this all means is that if you just want to get a quick overview of what a TDD application actually <span style="font-style:italic">does</span>, the first place to look is the acceptance tests. One of the major benefits of TDD is the fact that the tests themselves become documentation (<span style="font-style:italic">of</span> what the system actually does, as well as <span style="font-style:italic">proof</span> that it does it.)</p>
<p>This is taken to the next level with BDD, which provides a framework in which behavioural criteria, as expressed by non-technical stakeholders, <a href="http://dannorth.net/introducing-bdd/">become executable</a>.</p>
<p><strong>Starting work on a story</strong><br />Before you start writing any actual code for your story, or even any unit tests, you write a failing acceptance test. When this test goes green, you have finished the story - so in other words, the acceptance test needs to capture the entire essence of the story. This will usually be in a format similar to: 'Given this certain input/context, whatever happens internally, I expect this certain output.'</p>
<p>To begin work on MarsRover, I started with the first acceptance criterion:</p>
<ol>
<li>Interprets GridSizeCommand, initializes Grid and sets size</li>
</ol>
<p>Which I translated into this acceptance test:</p>
<pre class="brush:csharp">
[TestCase("5 5", 5, 5)]
[TestCase("2 3", 2, 3)]
public void Given_a_commandString_with_one_LandingSurface
SizeCommand_creates_LandingSurface_and_sets_size(
string landingSurfaceSizeCommandString,
int expectedWidth, int expectedHeight)
{
var expectedSize = new Size(expectedWidth, expectedHeight);
var commandCenter = container.Resolve<ICommandCenter>();
commandCenter.Execute(landingSurfaceSizeCommandString);
var landingSurface = commandCenter.GetLandingSurface();
var actualSize = landingSurface.GetSize();
Assert.AreEqual(expectedSize, actualSize);
}
</pre>
<p>The name is long, but it reads as English, and you'll recognise it from the documentation earlier in this post.</p>
<p><strong>A quick aside</strong><br />
You'll notice that I exposed a <code>LandingSurface</code> as a getter from <code>ICommandCenter</code>:</p>
<pre class="brush:csharp">
var landingSurface = commandCenter.GetLandingSurface();
</pre>
<p>This is a compromise - the spec doesn't say anything about reporting back the plateau's size, but I need some way to get access to it to ensure the size has been set! Debates could be had here, but i'll move on.</p>
<p><strong>Moving on</strong><br />
At the moment, this test doesn't even compile, so I then 'stub out' the two interfaces <code>ICommandCenter</code> and <code>ILandingSurface</code>. If you use ReSharper, you can do this with a few <a href="http://www.jetbrains.com/resharper/webhelp/Reference__Keyboard_Shortcuts.html">shortcuts</a>, and you can even save your interfaces to the correct assemblies / directories, all without coming out of ReSharper.</p>
<p>Now the test compiles but it doesn't pass. As you eventually progress from story to story, your bank of green acceptance tests represent stories already completed. The single red acceptance test represents the story you are currently working on.</p>
<p>As you can see in the code example above, the acceptance test sees your codebase from the 'outside in', the same way your stakeholders see it. In writing an acceptance test, you highlight two important things - the trigger (what kicks the functionality into action - a button, a scheduled task etc.), and the expected response (a screen-based confirmation message, a sound, some kind of acknowledgement.)</p>
<p>You will need to keep these things in mind when you start writing your first unit test, as your first unit test will be written for the 'trigger' (i.e. <code>commandCenter.Execute()</code> above.)</p>
<p><strong>Writing the first unit test</strong><br />
In the MarsRover spec, as an input we are given a complete, newline-delimited string to parse. The implication is that this system is receiving remote communications in a serial format, so from the context of our application it is not expected that the string will be literally typed in by a human.</p>
<p>For this reason, and because dealing with communications technologies is outside the scope of this project, I embedded the string as a constant in the application. So the entry point for this story is a command to execute a predefined string, i.e.</p>
<pre class="brush:csharp">
commandCenter.Execute(landingSurfaceSizeCommandString);
</pre>
<p>The 'grid size' command string will contain two integers separated by a space, as in our <code>TestCase</code> attributes above:</p>
<pre class="brush:csharp">
[TestCase("5 5", 5, 5)]
[TestCase("2 3", 2, 3)]
</pre>
<p>I came up with the class name <code>CommandCenter</code> to handle the execution, and it's responsibility is to talk to a <code>CommandParser</code> to turn the string into a list of <code>Command</code>s, and to hand the list to a <code>CommandInvoker</code>. The <code>CommandInvoker</code>'s responsibility is to invoke each <code>Command</code> on domain objects such as <code>LandingSurface</code> and <code>Rover</code>.</p>
<p>(I avoided the name <code>CommandController</code> for example, because of the association with MVC.)</p>
<p>The first thing the <code>CommandCenter</code> should do when asked to execute a string command, is to figure out what kind of command it is dealing with. For this, first I wrote a test:</p>
<pre class="brush:csharp">
public class CommandCenterTests
{
[TestFixture]
public class CommandCenter_Execute
{
[Test]
public void Given_valid_command_string_invokes_Parser()
{
const string expectedCommand = "2 5";
var mockCommandParser = new Mock<ICommandParser>();
var commandCenter = new CommandCenter();
commandCenter.Execute(expectedCommand);
mockCommandParser.Verify(x =>
x.Parse(expectedCommand), Times.Once());
}
}
}
</pre>
<p>As you can see, focusing on the first unit of behaviour expected of this class has suggested a dependency - <code>ICommandParser</code>. At the moment this is just an interface, not a class, so it can be mocked and used for the purposes of this test without having to start worrying about it's implementation or having two failing unit tests at once.</p>
<p>As an extension of this 'single test subject' concept, the only class to be directly instantiated (newed up) is the Subject Under Test (SUT):</p>
<pre class="brush:csharp">
var commandCenter = new CommandCenter();
</pre>
<p>All interactions with other objects are verified only by mocking, so that a test only ever verifies the behaviour of the SUT, no more no less.</p>
<p><strong>Testing too much</strong><br />
The responsibilities of those associated objects, like <code>ICommandParser</code> above, will have their own tests to verify their behaviour when they are implemented. As in the example above, it is enough to ensure that the <code>CommandCenter</code> invokes the services of it's collaborator, <code>ICommandParser</code>, and that is all. Testing the actual command parsing functionality will take place in the <code>CommandParserTests</code>.</p>
<p>This is one of the first pitfalls for newcomers to TDD - testing too much. But once you get the hang of it you start thinking of classes in terms of their specific responsibilities. You also start to see objects from the outside-in, in terms of class responsibilities being defined by an API (hence the use of interfaces).</p>
<p>Once you have a green light on your first test, you can start work on the first dependency you have highlighted (test-first ofcourse), and so on until your acceptance test goes green. If you have no dependencies left unimplemented and your acceptance test is still red, look back to your 'trigger', and add another test for the missing functionality.</p>
<p>This is what happened with the example above - it's not enough just to parse the string into commands, you also have to execute them. You could write a new test for that functionality, or you could extend the existing one (<a href="http://github.com/microcosm/MarsRover/blob/master/Nasa.MarsRover.Tests/CommandCenterTests.cs">as I did</a>). So long as you have a failing test before you start, and so long as you keep the test small and focused. One or two Assert's is OK, more than that and you may be testing too much.</p>
<p><strong>Arrange, Act, Assert</strong><br />Note at this stage that the test is written in the <a href="http://www.arrangeactassert.com/why-and-what-is-arrange-act-assert/">Arrange Act Assert</a> format. Below you can see exactly the same test but with a few comments to show you the different sections:</p>
<pre class="brush:csharp">
public class CommandCenterTests
{
[TestFixture]
public class CommandCenter_Execute
{
[Test]
public void Given_valid_command_string_invokes_Parser()
{
//Arrange
const string expectedCommand = "2 5";
var mockCommandParser = new Mock<ICommandParser>();
//Act
var commandCenter = new CommandCenter();
commandCenter.Execute(expectedCommand);
//Assert
mockCommandParser.Verify(x =>
x.Parse(expectedCommand), Times.Once());
}
}
}
</pre>
<p>When you are beginning it can be helpful to annotate it as above, however once you've been doing it a while you get used to expecting a certain convention in the code, and no longer need the reminders.</p>
<p><strong>Refactoring... is this the best possible design?</strong><br />
This is probably a good time to take a look at the <a href="http://www.agiledata.org/essays/tdd.html">TDD cycle</a>. One of the fundamental things, and core benefits of TDD is improving your design. After you have written your implementation, you have the opportunity to improve it, perhaps to make it more efficient, and as long as it still satisfies your test cases, you are good to go.</p>
<p>But more broadly than that, <span style="font-style:italic">before</span> you start writing a test, you have the opportunity to improve the existing system design in light of the functionality you are about to implement.</p>
<ul>
<li>Will some responsibilities need to shift to ensure the resulting system makes sense? First, shift the tests, then shift their implementations.</li>
<li>Does another method need to be renamed, for the sake of differentiation, now that a class has to handle a slightly different load? Use ReSharper to do it automatically.</li>
<li>Is the code you're writing starting to look a bit like a popular <a href="http://www.dofactory.com/Patterns/Patterns.aspx">design pattern</a>? Consider whether implementing the pattern more closely will improve the code. (This is how I got to the <a href="http://www.dofactory.com/Patterns/PatternCommand.aspx">Command pattern</a>, which I explain later in this post.)</li>
</ul>
<p><strong>Semantic naming</strong><br />Finally, take a look at the test's internal class structure and naming. This (like many things I am describing in this post!), is a matter of convention and style, but the inner class tells you what class and method are under test (the SUT). The test method name tells you the expected behaviour you are ensuring, i.e.</p>
<pre class="brush:csharp">
public class ClassNameTests
{
[TestFixture]
public class ClassName_MethodName
{
[Test]
public void Behaviour_under_test()
{
//Arrange, Act, Assert
}
}
}
</pre>
<p>The reason I've used these conventions is that as well as being explicit, it reads as documentation, like before:</p>
<div style="width:100%; text-align:center;">
<img alt="Rover Tests reading as class documentation" height="214" width="520" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg51Pn7WYrHeBHPtaKPyD_TXwmeSEveAbRk6du1YzQNXqtxRccLYiw-eaOe8UTCXdAjc-qb-3Cvml4eL9_u1nXzS0PaCIay-2oG7rNmznIXlnyysao5FgeHzMFSf8Yv4m63WeTSVsRaxS4p/s1600/3classdocumentation.png" /></div>
<p>Only this time we have class-level documentation rather than story/acceptance-level. Each method of the <code>Rover</code> class in the example above is described in terms of it's externally expected behaviour, along with proof that it is living up to those expectations.</p>
<p><strong>Speed</strong><br />
I'll briefly describe the architecture of the system in a minute, but I want to quickly talk about speed.</p>
<p>If you are new to TDD, one of the things you might be thinking right now is, how long is all this going to take!? In this time we could have already implemented twice as many features.</p>
<p>This is a very good point. You could, and TDD is slower - at least at the start. The most convincing answer to this that I know of, is that it depends on the expected complexity and lifespan of your application. A small application which will be shelved in six months <span style="font-style:italic">may</span> not be a good candidate for TDD. But an enterprise application, which is expected to constantly change and grow as the business changes and grows, is probably a good candidate.</p>
<p>With TDD, the very start certainly takes longer, but once you get going features can be added at a consistent pace. This is in contrast to non-TDD projects, where as the system grows and becomes more complex, it also becomes more 'brittle' and harder to change. People are afraid to redesign to adapt to new challenges, people are afraid to update to the latest versions or techniques of external libraries for fear of regressions, and deployments to production become more of a risk.</p>
<p>And ofcourse the real clincher: the time it takes to implement new features on existing functionality <span style="font-style:italic">grows exponentially</span>.</p>
<p>With regard the time it takes to implement a single feature with TDD, once I got used to the process I found it to be only marginally longer. This is because in effect, you are doing the same core tasks you were doing without TDD, only in a different order - and with a little bit of extra typing for the tests:</p>
<ul>
<li>analysing a problem,</li>
<li>contextualising it within an existing codebase,</li>
<li>following through on implementation,</li>
<li>and testing</li>
</ul>
<p>But as well as the extra typing, there is the fact that you are working incrementally, i.e. you are improving your design and refactoring as you go.</p>
<p>Now that <span style="font-style:italic">does</span> take extra time - but it takes the time upfront.</p>
<p>Without TDD you hit those problems later on, often close to your release date. You are more likely to have longer bug lists, unexpected regressions, and poorer system design at the end of it. This means the next developers who have to come and work on the codebase, and the next after that, will encounter the same problems again, and those problems will continue to grow as the complexity grows.</p>
<p>Ofcourse, this is all quite philosophical! There's no hard evidence, but as we know, TDD has become a mainstream practice. As you can tell, I'm convinced of it's usefulness in non-trivial applications!</p>
<p><strong>Separating end-to-end from unit tests</strong><br />Acceptance tests are naturally end-to-end. Their purpose is to test the system, as far as is possible, from the perspective of it's actual usage. That means that the tests must use the same object graph, provided by the same <a href="http://jahyacode.blogspot.com/2011/07/ioc-containers-and-dependency-injection.html">DI</a> container and an equivalent <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">composition root</a> (notice the <code>container.Resolve<Icommandcenter></code> in the acceptance test example above). This is so that the objects exercised by the tests all relate to each other in exactly the same way as they do in production.</p>
<p>Unit tests, on the other hand, must test just one behaviour of one component at a time, and so to distinguish the two types of test, I placed each in their own assembly:</p>
<div style="width:100%; text-align:center;">
<img alt="Project layout showing AcceptanceTests assembly" style="margin-left:auto; margin-right:auto;" height="208" width="276" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7SW0MpubaS8NDa3Gd-E5fWAXEZ4FMgk3aai00eLz1E8rQVnAqJ13HpuA-frKdW3R62N0pzjaT1T1RAe2agGWqCw7kRpWp_FGn2SvaFb-sYbtyFMuIjJn1YO1UagB3coLd6-wGuvyK7tUz/s1600/2solutionexplorer_acceptancetests.png" />
</div>
<p>As the system grows, there would remain only one Acceptance Test assembly (for each distinct presentation layer anyway), but a new Unit Test assembly would be added for each and every production code assembly, mirroring the directory structure of the production code.</p>
<p>Ofcourse, there are other types of test - in particular Integration Tests, for testing your (hopefully thin) integration points with external resources. However there is no requirement for integration in this spec, and so it is descoped for another article.</p>
<p><strong>Exploring the MarsRover project</strong><br />
You should have enough information to start exploring the solution now, so before I wrap up I'll just say a few things about architecture.
<p>I have used the <a href="http://www.dofactory.com/Patterns/PatternCommand.aspx">Command pattern</a>, in which a <span style="font-style:italic">command invoker</span> invokes <span style="font-style:italic">commands</span> on command <span style="font-style:italic">receivers</span>. To make it easy for other developers to detect the use of the pattern, I have used appropriate naming conventions:</p>
<ul>
<li><code>ICommand</code></li>
<li><code>ILandingSurfaceSizeCommand</code> (implements <code>ICommand</code>)</li>
<li><code>IRoverDeployCommand</code> (implements <code>ICommand</code>)</li>
<li><code>IRoverExploreCommand</code> (implements <code>ICommand</code>)</li>
<li><code>ICommandInvoker</code> (invokes each of the concrete commands at the appropriate moments via their shared interface, <code>ICommand</code>)</li>
</ul>
<p>The command <span style="font-style:italic">receivers</span> are the domain objects being operated on, i.e.</p>
<ul>
<li><code>IRover</code> (implementation <code>Rover</code>), and</li>
<li><code>ILandingSurface</code> (implementation <code>Plateau</code>)</li>
</ul>
<p>When the <code>CommandInvoker</code> is instructed to <code>InvokeAll()</code>, it simply iterates through each <code>ICommand</code>, assigns the receivers to it, and invokes it. You can see it happen <a href="http://github.com/microcosm/MarsRover/blob/master/Nasa.MarsRover/Command/CommandInvoker.cs">here</a>.</p>
<p>(Note: The <a href="http://www.markhneedham.com/blog/2010/05/30/c-using-a-dictionary-instead-of-if-statements/">method dictionary</a> is just a way to pass each <code>ICommand</code> to a tailored method for assigning the correct receivers.)</p>
<p><strong>Resolving dependencies</strong><br />
The other thing you'll notice is how I handled dependency injection, and in particular <span style="font-style:italic">dynamic instantiation</span>. This is all stuff I've blogged about before, so please check out the relevant posts:</p>
<ul>
<li>I used constructor injection to inject dependencies (described <a href="http://jahyacode.blogspot.co.uk/2011/07/ioc-containers-and-dependency-injection.html">here</a>),</li>
<li>and Autofac's delegate factories for <span style="font-style:italic">dynamic instantiation</span> (described <a href="http://jahyacode.blogspot.co.uk/2012/03/using-autofacs-auto-factories-to-avoid.html">here</a>)</li>
</ul>
<p>I hope you find this project useful, and if you have any comments or questions, please write!</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-75643489048039491922012-03-14T22:21:00.000+00:002012-03-19T12:17:57.138+00:00Using Autofac's Auto-Factories to Avoid Service Locator<table class="tr-caption-container" style="float: right; margin-left: 1em; text-align: right;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHUJx4u7voPk_TEyN2WWRvrneh_6XwMCoq2SHR5eLe9X8ogr6ceruT_yVPuxC3ZtQbOdCDDOAC3MGEuIAtDXJ0CXWSlhOUs5s3h0ckw_FZDf5T7JG4qTMVywqcB3BxKkmLep2A_4sAO4Xr/s1600/3959355664_22383aeaf8_o.jpg" style="clear: right; margin-bottom: 1em; margin-left: auto; margin-right: auto;"><img alt="An autofac-style factory delegate" height="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHUJx4u7voPk_TEyN2WWRvrneh_6XwMCoq2SHR5eLe9X8ogr6ceruT_yVPuxC3ZtQbOdCDDOAC3MGEuIAtDXJ0CXWSlhOUs5s3h0ckw_FZDf5T7JG4qTMVywqcB3BxKkmLep2A_4sAO4Xr/s200/3959355664_22383aeaf8_o.jpg" width="200" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">An autofac-style factory delegate<br />(credit: <a href="http://www.flickr.com/photos/pasukaru76/3959355664/in/photostream">pasukaru76</a>)</td></tr>
</tbody></table>
<p>I recently switched a project's <a href="http://jahyacode.blogspot.com/2011/07/ioc-containers-and-dependency-injection.html">DI</a> solution from <a href="http://structuremap.net/structuremap">StructureMap</a> to <a href="http://code.google.com/p/autofac">Autofac</a>.</p>
<p>The reason was because the only way I could get StructureMap to handle <a href="http://nblumhardt.com/2010/01/the-relationship-zoo/">dynamic instantiation</a> was to use a variant of <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service Locator</a>, which couples your code to your container, making unit tests impossible and reducing <a href="http://en.wikipedia.org/wiki/Code_coverage">code coverage</a>.</p>
<p>In this article I'll explain the problem with StructureMap, and how Autofac solved it elegantly.</p>
<p>I'll explain the problem using a <span style="font-family: 'Courier New'">Something</span> class, i.e. any class you might want to dynamically instantiate somewhere in your code. Here it is in all it's glory:</p>
<pre class="brush:csharp">
public class Something : ISomething
{
public Something(int anArgument)
{
//an implementation
}
}
</pre>
<p><strong>How it works in StructureMap</strong><br />One of the biggest problems with using StructureMap (as mentioned in <a href="http://jahyacode.blogspot.com/2011/07/ioc-containers-and-dependency-injection.html">this post</a> and <a href="http://jahyacode.blogspot.com/2011/07/injecting-controller-dependencies-in.html">this post</a>), is that your entry-point to the container is via the static class <span style="font-family: 'Courier New'">ObjectFactory</span>, which always resolves to a singleton container.</p>
<p>Commonly you'll see a Bootstrapper class like this one below, where all the dependencies are registered (explained <a href="http://structuremap.net/structuremap/ConfiguringStructureMap.htm">here</a>):</p>
<pre class="brush:csharp; highlight: 3">
public static void Bootstrap()
{
ObjectFactory.Initialize(x =>
{
x.For<ISomething>().Use<Something>();
x.For<IAnotherThing>().Use<AnotherThing>();
}
}
</pre>
<p>The main benefit of the static reference is that when you need to dynamically instantiate an instance later in your code, you can use the static class again to refer to the same container (rather than 'newing up' an instance of the container, which wouldn't have all of your existing bootstrapped mappings):
<pre class="brush:csharp; highlight: [5,6,7]">
public class SomethingClient
{
public void SomeDynamicScenario(int anArgument)
{
var something = ObjectFactory
.With("anArgument").EqualTo(anArgument)
.GetInstance<ISomething>();
//operate on new object
}
}
</pre>
<p>The downside of this benefit is that it's a Service Locator. The method can't be unit tested, because when the test runner gets to the <span style="font-family: 'Courier New'">ObjectFactory</span>, it doesn't know what an <span style="font-family: 'Courier New'">IService</span> is. You could tell it by running the Bootstrapper in your test, but then ofcourse then you aren't <a href="http://en.wikipedia.org/wiki/Unit_testing">unit-testing</a> any more.</p>
<p>In other words, your code is <a href="http://en.wikipedia.org/wiki/Coupling_(computer_programming)">coupled</a> to the StructureMap container.</p>
<p><strong>The standard approach</strong><br />The standard approach to making this testable is to <a href="http://stackoverflow.com/questions/2531612/structuremap-resolve-dependency-through-injection-instead-of-service-location">extract your instantiation logic</a> into an <span style="font-family: 'Courier New'">ISomethingFactory</span>. That way, you can inject the factory and mock it in your tests.</p>
<pre class="brush:csharp">
public class SomethingClient
{
private readonly ISomethingFactory somethingFactory;
public SomethingClient(ISomethingFactory aSomethingFactory)
{
somethingFactory = aSomethingfactory;
}
public void SomeDynamicScenario(int anArgument)
{
var something = somethingFactory.Create(anArgument);
//operate on new object
}
}
public class SomethingFactory : ISomethingFactory
{
public ISomething Create(int anArgument)
{
return ObjectFactory
.With("anArgument").EqualTo(anArgument)
.GetInstance<ISomething>();
}
}
</pre>
<p>But then ofcourse, all you are doing is <span style="font-style:italic">moving</span> the problem somewhere else. How would you unit test <span style="font-family: 'Courier New'">SomethingFactory</span>? You can't.</p>
<p>The problem is that wherever you have 'peppered' container references around your code (i.e. <span style="font-family: 'Courier New'">ObjectFactory</span> references), you won't be able to test and your implementation will be coupled.</p>
<p>At that stage you could just say, well, that's the boundary of our unit tests - we will adopt a policy where we just don't unit test factories. And there's merit in that, because you are defining a unit test boundary and everything on one side of it will be unit tested. You could still test the factory as a module, or not test it at all. But then again...</p>
<p><strong>Step in Autofac</strong><br />
The good thing about Autofac is, not only does it provide a solution which gives you 100% code coverage, it's also actually much <span style="font-style:italic">easier</span> to implement.</p>
<p>You can just declare your factory as a delegate method (which returns an <span style="font-family: 'Courier New'">ISomething</span>), include it as a constructor argument and that's it! Autofac will work out from your <span style="font-family: 'Courier New'">ISomething</span> mappings to build and inject a factory for you, saving you the bother of having to even define one in the first place.</p>
<p>Here's the <span style="font-family: 'Courier New'">SomethingClient</span> example again:</p>
<pre class="brush:csharp">
public class SomethingClient
{
private readonly Func<int, ISomething> somethingFactory;
public SomethingClient(
Func<int, ISomething> aSomethingFactory)
{
somethingFactory = aSomethingfactory;
}
public void SomeDynamicScenario(int anArgument)
{
var something = somethingFactory(anArgument);
//operate on new object
}
}
//No need for a factory class
</pre>
<p>When the container instantiates <span style="font-family: 'Courier New'">SomethingClient</span> it discovers the <span style="font-family: 'Courier New'">Func</span> <a href="http://jahyacode.blogspot.com/2011/07/lambda-expressions-in-c.html">delegate</a>. The delegate has a return type that Autofac is registered to handle, and a parameter list Autofac recognises as <span style="font-family: 'Courier New'">ISomething</span> constructor parameters, and so Autofac injects a delegate that acts as a factory for us.</p>
<p>The <span style="font-family: 'Courier New'">Func</span> delegate in this example takes one <span style="font-family: 'Courier New'">int</span> argument, but ofcourse you can plug in <a href="http://msdn.microsoft.com/en-us/library/dd402862.aspx">any useful combination of input parameters</a>.</p>
<p><strong>Mixed constructor argument parameters</strong><br />Now, this all works fine when we have a simple parameter with just a single <span style="font-family: 'Courier New'">int</span>, but what happens when we update <span style="font-family: 'Courier New'">ISomething</span> to accept a mixture of dependencies and value-type arguments?</p>
<pre class="brush:csharp">
public class Something : ISomething
{
public Something(int anArgument,
Point aPoint, IDependency aDependency)
{
//an implementation
}
}
</pre>
<p>In this example let's assume that the <span style="font-family: 'Courier New'">Point</span> above is a type you have defined in your codebase to represent a value type, and therefore you want to specify this value dynamically on construction rather than by registering it with the container:</p>
<pre class="brush:csharp">
public struct Point
{
public int X;
public int Y;
public Point(int anX, int aY)
{
X = anX;
Y = aY;
}
}
</pre>
<p>On the other hand ofcourse, <span style="font-family: 'Courier New'">IDependency</span> is a dependency and you want that injected for you, by the container. How do we declare our factory?</p>
<p>We <span style="font-style:italic">only</span> include the value types and we <span style="font-style:italic">omit</span> the dependency:</p>
<pre class="brush:csharp; highlight:4">
public class SomethingClient
{
private readonly
Func<int, Point, ISomething> somethingFactory;
public SomethingClient(
Func<int, Point, ISomething> aSomethingFactory)
{
somethingFactory = aSomethingfactory;
}
public void SomeDynamicScenario(
int anArgument, Point aPoint)
{
var something = somethingFactory(anArgument, aPoint);
//operate on new object
}
}
//No need for a factory class
</pre>
<p>No <span style="font-family: 'Courier New'">IDependency</span> mentioned anywhere! Autofac is smart enough to allow you to add dependencies to the underlying class constructor's signature, without changing the factory, and it will <span style="font-style:italic">still inject the dependencies for you!</span></p>
<p>Which is exactly what you want - as your solution grows and you find yourself adding dependencies, your factories do not change. They are created for you and extra dependencies are included on instantiation transparently.</p>
<p>This type of joined-up thinking makes Autofac a very nice container to work with. Lots of things happen for you, right out of the box, based on convention - you just have to know which and when.</p>
<p><strong>The composition root</strong><br />As <a href="http://stackoverflow.com/questions/4570750/dependency-injection-turtles-all-the-way-down">this post</a> eloquently explains, there should be only one place in an application where your container is referenced - the <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx">composition root</a>. In this location you should do everything necessary to resolve the entire object graph - i.e. <a href="http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasePattern.aspx">Register, Resolve, Release</a>.</p>
<p>By using a static reference to a singleton container, StructureMap encourages these rules to be broken. Autofac, on the other hand, provides a container that implements <span style="font-family: 'Courier New'">IDisposable</span>, which means you can use a <span style="font-family: 'Courier New'">using</span> block to enforce the RRR pattern:</p>
<pre class="brush:csharp; highlight: [23, 22, 10, 11]">
public class Program
{
public static void Main()
{
var containerBuilder = registerAssemblyTypes();
using (var container = containerBuilder.Build())
{
//single entry point
var entryPoint =
container.Resolve<ICodebaseEntryPoint>();
//start using entryPoint
}
}
private static ContainerBuilder registerAssemblyTypes()
{
var programAssembly = Assembly.GetExecutingAssembly();
var builder = new ContainerBuilder();
//perform auto-wiring
builder.RegisterAssemblyTypes(programAssembly)
.AsImplementedInterfaces();
return builder;
}
}
</pre>
<p><strong>Component discovery</strong><br />While we're here, take a look at the call to <span style="font-family: 'Courier New'">ContainerBuilder.RegisterAssemblyTypes (Assembly)</span>. This little call uses <a href="http://msdn.microsoft.com/en-us/library/ms173183(v=vs.100).aspx">reflection</a> to look at your concrete classes and your interfaces, and work out which go with which. It uses a convention over configuration approach, and <a href="http://code.google.com/p/autofac/wiki/Scanning">you can include clauses and overrides</a> to filter and specify particular instantiations.</p>
<p>StructureMap also provides a similar <a href="http://structuremap.net/structuremap/ScanningAssemblies.htm">component discovery</a> model.</p>
<p>In fact, I'm sure StructureMap can do most of the things Autofac can do one way or another (see this article on <a href="http://structuremap.net/structuremap/UsingTheContainerOutsideOfObjectFactory.htm">avoiding static references</a>), and I've used StructureMap successfully many times. It's just that Autofac does things nicely by default.</p>
<p><strong>Broadening the discussion about relationships</strong><br />One final point - <a href="http://nblumhardt.com/2010/04/introducing-autofac-2-1-rtw/">Nicholas Blumhardt</a>, the creator of Autofac, has included a very nice chart on his blog describing different object relationship types (of which dynamic instantiation via factories is one):</p>
<style type="text/css">
table#relationshiptypes
{
border: 1px solid black;
margin: 0px;
padding: 0px;
border-width: 0 0 1px 1px;
border-style: solid;
border-spacing: 0;
border-collapse: collapse;
}
table#relationshiptypes th, table#relationshiptypes tr, table#relationshiptypes td
{
border: 1px solid black;
margin: 0px;
padding: 0.3em;
border-width: 1px 1px 0 0;
border-style: solid;
}
</style>
<table id="relationshiptypes">
<tr>
<th>Relationship</th>
<th>Adapter Type</th>
<th>Meaning</th>
</th>
<tr>
<td><em>A</em> needs a <em>B</em></td>
<td><em>None</em></td>
<td>Dependency</td>
</tr>
<tr>
<td><em>A</em> needs a <em>B</em> at some point in the future</td>
<td><code class="codecolorer text default"><span class="text">Lazy<B></span></code></td>
<td>Delayed instantiation</td>
</tr>
<tr>
<td><em>A</em> needs a <em>B</em> until some point in the future</td>
<td><code class="codecolorer text default"><span class="text">Owned<B></span></code></td>
<td>Controlled lifetime</td>
</tr>
<tr>
<td><em>A</em> needs to create instances of <em>B</em></td>
<td><code class="codecolorer text default"><span class="text">Func<B></span></code></td>
<td>Dynamic instantiation</td>
</tr>
<tr>
<td><em>A</em> provides parameters of types <em>X</em> and <em>Y</em> to <em>B</em></td>
<td><code class="codecolorer text default"><span class="text">Func<X,Y,B></span></code></td>
<td>Parameterisation</td>
</tr>
<tr>
<td><em>A</em> needs all the kinds of <em>B</em></td>
<td><code class="codecolorer text default"><span class="text">IEnumerable<B></span></code></td>
<td>Enumeration</td>
</tr>
<tr>
<td><em>A</em> needs to know <em>X</em> about <em>B</em> before using it</td>
<td><code class="codecolorer text default"><span class="text">Meta<T></span></code> and <code class="codecolorer text default"><span class="text">Meta<B,X></span></code></td>
<td>Metadata interrogation</td>
</tr>
</table>
<p>It's nice to consider contextually where the problem we've just dealt with sits. For more discussion on these types, check out Nicholas' <a href="http://nblumhardt.com/2010/01/the-relationship-zoo/">introductory article</a>.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com1tag:blogger.com,1999:blog-3518945678469852273.post-52571718830955585422012-02-24T11:05:00.000+00:002012-02-24T11:05:13.770+00:00Using NuGet to Install Packages Across a Solution<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSiyKi6eHqCpNtbVIWhIbj8RrrZOIqdpHGk5dG6h9b3x9i0rkrFxteitwWOAY1y-61L1a4nOohVmC6LQFRj0NOTOj2q__5FmL71bwJ2OsEvAnWqtRH_NCd4_kcI3D0r3ukYDVBLIJ1Qas0/s1600/ramly-nuget-ayam-1kg.jpg" style="clear:right; float:right; margin-left:1em; margin-bottom:1em"><img alt="NuGet" height="300" width="300" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSiyKi6eHqCpNtbVIWhIbj8RrrZOIqdpHGk5dG6h9b3x9i0rkrFxteitwWOAY1y-61L1a4nOohVmC6LQFRj0NOTOj2q__5FmL71bwJ2OsEvAnWqtRH_NCd4_kcI3D0r3ukYDVBLIJ1Qas0/s320/ramly-nuget-ayam-1kg.jpg" /></a>
<p>Earlier today I created a new Unit Test project in an existing VS solution. I then wanted to install the NUnit package to the project using NuGet - but I want the same <span style="font-style:italic">version</span> of NUnit that is used on all the other Unit Test projects in the solution.</p>
<p>A new version of NUnit just came out, and all the existing projects use the old version. And the NuGet GUI would only let me install the latest package, not previous versions.</p>
<p>So what to do?</p>
<p>Ofcourse at some point in a codebase you'll want the latest version, but until you are ready to upgrade a package across every project in your solution, you'll want to install older package versions, to keep all your solution packages in sync.</p>
<p>The short answer is <strong>download the latest version of NuGet!</strong> Version 1.6 is out now, and since 1.5 has had the new feature: </p>
<pre>Tools ><br /> Library Package Manager ><br /> Manage NuGet Packages for Solution...</pre>
<p>You can see which version of NuGet you currently have <a href="http://docs.nuget.org/docs/start-here/nuget-faq#How_do_I_check_the_exact_version_of_NuGet_installed%3f">by checking the help dialog</a>, or by using the <a href="http://msdn.microsoft.com/en-us/library/dd293638.aspx">Visual Studio Extension Manager</a>. From the latter you can also uninstall your old NuGet and download and install the new one.</p>
<p><strong>The Longer Answer</strong><br />The longer answer, which highlights a little more about how NuGet manages your packages behind the scenes, is this:</p>
<ol>
<li>First, check which version of your package you have in your existing project references by looking at it's property sheet:</li>
</ol>
<div style="width:100%;text-align:center">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRzhM9OIVFcphlZTB4cZI2HcGOIkyLSqAIVriEjb_nwID-0WWqOPpoMhPnhOcamG7Uv0jcyXmbGT6nESnEygCA_xVROK996VkeFdagR_YRqUZs3foXIwY1WbnOZ2gfuCVdZtfBoZKw-AcX/s1600/version-number.png" style="clear:right; margin-left:auto; margin-right:auto;"><img alt="Property sheet" height="288" width="310" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRzhM9OIVFcphlZTB4cZI2HcGOIkyLSqAIVriEjb_nwID-0WWqOPpoMhPnhOcamG7Uv0jcyXmbGT6nESnEygCA_xVROK996VkeFdagR_YRqUZs3foXIwY1WbnOZ2gfuCVdZtfBoZKw-AcX/s320/version-number.png" /></a>
</div>
<ol start="2">
<li>Then launch the Package Manager Console and type in:</li>
</ol><pre class="brush:text">Install-Package <Package-Name> -Version <Version-Number></pre>
<p> i.e.</p>
<pre class="brush:text">Install-Package NUnit -Version 2.5.10.11092</pre>
<ol start="3">
<li>
NuGet should discover that your package is already installed elsewhere in your solution, and simply reference the existing package (as shown by the output below).
</li>
</ol>
<pre class="brush:text">
PM> Install-Package NUnit -Version 2.5.10.11092
'NUnit 2.5.10.11092' already installed.
Successfully added 'NUnit 2.5.10.11092' to My.Project.Tests.</pre>
<p><strong>The 'packages' Folder</strong><br />For more clarity, it's a good idea to browse to the 'packages' filesystem folder at the root of your solution. It contains a subfolder for each package you have installed in any project in your solution. The NuGet Package Manager ensures that when you use the same package across different projects, they share a single reference to the appropriate subdirectory. This keeps things neat and tidy in a way that we used to have to do by hand.</p>
<p>And ofcourse you can upgrade NuGet, do it the easy way, and let the Package Manager do it for you!</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-31258525695389321342011-12-20T10:55:00.000+00:002012-02-14T16:01:30.569+00:00ASP.NET Web Pages and QUnit<a style="float:right; margin: 0.5em 1em 0em 1.4em;" href="http://boingboing.net/2005/12/04/qunit-queen-and-50ce.html"><img alt="QUnit" height="242" width="244" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCJWBkZgZxPEfP1KHV6RUu85U0bbGvT7L-EBjMVVEZAfAlfnoWMC9E0TjoJoKheKHtwdVM_eh4gq03R0T4NOON9AUmF5iB2A35h3yU_zbU1L0xXhUIkhzMjNA6CgvMEjS4sb7iRnquPsY7/s320/qunit.jpg" /></a>
<p>Phil Haack has mentioned <a href="http://www.asp.net/web-pages">Web Pages</a> a few times recently, so I thought it was worth posting here. It's essentially designed to take advantage of Razor's more concise (and generally more fun to use) syntax, and make it easy and appealing for people who want to make quick and easy web pages with a bit of server-side scripting thrown in. But who don't want to have to build a full MVC app.</p>
<p>In other words, to give ASP.NET the sort of quick and easy flexible feel of PHP. You can write full-blown OO PHP apps, but most people start at least with the quick and dirty option.</p>
<p>At first glance on that basis it's hard to see where Web Pages would fit in for me, after all, I <span style="font-style: italic;">am</span> building full-blown MVC applications, and you generally wouldn't want to mix and match Web Pages and Controller routing within a single solution - it would make routing ambiguous.</p>
<p>On the other hand, Haack <a href="http://haacked.com/archive/2011/12/10/using-qunit-with-razor-layouts.aspx">points out a very nice usage here</a>, for testing using <a href="http://freshbrewedcode.com/jonathancreamer/2011/12/08/qunit-layout-for-javascript-testing-in-asp-net-mvc3/">QUnit</a>. The point is, controller actions are a bit redundant in the frontend script testing scenario, so why use them just for routing's sake?</p>
<p>He points out how annoyingly generic the name 'Web Pages' is too. He's right.</p>
<ul>
<li><a href="http://www.asp.net/web-pages">ASP.NET Web Pages</a></li>
<li><a href="http://docs.jquery.com/QUnit">QUnit</a></li>
</ul>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-23063759173372191012011-11-30T15:41:00.005+00:002012-02-15T16:28:11.262+00:00Bundling and Minification in .NET 4.5<div style="float: right; text-align: center; margin: 0.4em 1em 1em 1.2em">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSYM2s7iCR8bMt20bE-B84MkyMPGw-7F3zZK4_DdJUnKK1rlZHBTk6KwSIRq_BtW3nGZbUr_kWwcc85bYF9XlT3_NTdc9oSjmgxBYT338P2v4TiArqvArqm7ODz5CzZ2uLMVxClRXi4fWk/s1600/475823_87254229.jpg" style="margin-left: auto; margin-right: auto;"><img alt="A minified being" height="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSYM2s7iCR8bMt20bE-B84MkyMPGw-7F3zZK4_DdJUnKK1rlZHBTk6KwSIRq_BtW3nGZbUr_kWwcc85bYF9XlT3_NTdc9oSjmgxBYT338P2v4TiArqvArqm7ODz5CzZ2uLMVxClRXi4fWk/s200/475823_87254229.jpg" width="173" /></a>
<br />
A minified being
</div>
<p>.NET 4.5 (WebForms and MVC) will come with a cool new feature to help improve page load times from your web applications. CSS and JS files will be able to be bundled and minified at the folder level.</p>
<p>See <a href="http://weblogs.asp.net/scottgu/archive/2011/11/27/new-bundling-and-minification-support-asp-net-4-5-series.aspx">ScottGu's post here</a>, and a quick (1 min) video runthrough below (<a href="http://www.asp.net/vnext/videos/aspnet-vnext-videos-bundling-and-minification">source</a>).</p>
<p>This will leave your working files unaltered, and in their separate logical locations. But it will remove whitespace, use minify rules, and combine like files in response to browser requests.</p>
<p>One thing that isn't mentioned is cacheing, i.e. presumably the server caches the bundled files rather than perform the bundle operation every time a page is assembled. Will have to see how that works when 4.5 is released.</p>
<p>By default the bundled files within a folder are ordered alphabetically, but this can be overridden by customising Bundle objects. You also have the option of specifying CSS or JS syntax to convert to, including specifying custom rules. Pretty cool.</p>
<object id="SilverlightMediaPlayer" style="width:572px;height:490px;" autoupdate="true" data="data:application/x-silverlight-2," type="application/x-silverlight-2"><param name="MinRuntimeVersion" value="2.0.31005.0" /><param name="source" value="http://www.asp.net/ClientBin/mediaplayer/MSCommunities.MediaPlayer.xap?cdn_id=2012-02-07-001" /><param name="InitParams" value="extendedfeatures=false,videoid=27455,videowidth=572,videoheight=490" /><video controls="" width="572" height="490" src="http://download.microsoft.com/download/7/0/7/70737AB5-9634-4B70-9DAA-53BE53FA4E58/HDI_ITPro_MSDN_mp4audio_Visual_Studio_vNext_Videos_Bundling_and_Minification.m4v"><a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration:none"><img src="http://i1.asp.net/common/static-asp/asp.net/videos/silverlight.mediaplayer/slplayer_disabled.png?cdn_id=2012-02-07-001" alt="Please install Silverlight or click download to watch video locally." /></a></video></object>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-50286760076909696512011-10-21T11:23:00.001+01:002012-02-15T17:27:37.841+00:00AJAX and Unobtrusive Javascript in MVC3<p>AJAX is a fundamental aspect of many web applications, and unobtrusive Javascript, supporting the Separation of Concerns (SOC) principle, has really come into it's own with the introduction of the HTML5 specification. In this post I want to introduce the built-in Microsoft MVC3 support for these features, just enough to get you off the ground.</p>
<p>I have embedded Pluralsight training videos into the post as I go along. The free Pluralsight training videos are often a great quick-and-easy primer to .NET framework features, which show you idealised scenarios from which you can jump off to more tailored solutions.</p>
<p>For each video I provide a short summary of it's contents for easy-access later.</p>
<p>This is the <a href="http://www.pluralsight-training.net/microsoft/courses/tableofcontents?courseName=aspdotnet-mvc3-intro">table of contents for the entire 'Introduction to MVC3' series</a>. The videos embedded below are from the section 'AJAX and JavaScript with ASP.NET MVC 3'.</p>
<p><span style="font-weight: bold;">Video 1. CDNs, scripts at the bottom, and RenderSection</span><br />The first video is all about ways of laying out your scripts:</p>
<a href="#" id="Ajax2" style="height:405px;width:575px;background:black;display:block;text-align:center;">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGWy_pWS8_4w6VMF-hKujvOM73WX_AXmueqloUIixY3DIozc6R9Jl4cB4uvVR2Vxg_Kv4dott4NgP0GG7muUs4srIAWV2_LClXc_wQZbDxKXy2nY2xsJURG0LN-XwQzel2COY0ZQRTuvmr/s320/play.png" alt="Play video" style="position:relative;top:166px;" />
</a>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#Ajax2").click(function(){
$(this).html('<iframe style="height:405px;width:575px" src="http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=2&course=aspdotnet-mvc3-intro" frameBorder="0" scrolling="no" ></iframe>');
return false;
});
});
</script>
<br />
<ul>
<li>First it talks about the performance benefits of using CDN-hosted resources and placing <span style="font-family:'Courier New'"><script></span> tags etc. at the bottom of your page (as opposed to in the <span style="font-family:'Courier New'"><head></span>). In particular, unobtrusive javascript <span style="font-style:italic">allows</span> us to put our <span style="font-family:'Courier New'"><script></span> tags at the bottom, because we are unhindered by inline javascript dependencies on <span style="font-family:'Courier New'"><head></span>-loaded .js files.</li>
<li>Next, the 'magic' App_Code folder is demonstrated. Razor @helpers (concise versions of HtmlHelpers) can be dropped into this folder and will be precompiled into static methods, accessible from any view.</li>
<li>Finally, the RenderSection method is introduced. Like it's MVC2 equivalent, this method allows the master page to control page layout by defining sections. While the pages themselves can optionally define content to populate each section.</li>
</ul>
<pre class="brush: xml">
<!-- Master-page scripts, included on all pages -->
@Content.Script("jquery-1.4.4.min.js", Url)
@Content.Script("jquery.unobtrusive-ajax.min.js", Url)
<!-- Page-specific scripts -->
@RenderSection("Scripts", false)
<!-- (false means not required) -->
</body>
</html>
</pre>
<br />
<p><span style="font-weight: bold;">Video 2. Using Ajax.ActionLink to return a PartialViewResult to a specified page element</span><br />
The second video is a very straight-forward example of an asynchronous request:</p>
<a href="#" id="Ajax3" style="height:405px;width:575px;background:black;display:block;text-align:center;">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGWy_pWS8_4w6VMF-hKujvOM73WX_AXmueqloUIixY3DIozc6R9Jl4cB4uvVR2Vxg_Kv4dott4NgP0GG7muUs4srIAWV2_LClXc_wQZbDxKXy2nY2xsJURG0LN-XwQzel2COY0ZQRTuvmr/s320/play.png" alt="Play video" style="position:relative;top:166px;" />
</a>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#Ajax3").click(function(){
$(this).html('<iframe style="height:405px;width:575px" src="http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=3&course=aspdotnet-mvc3-intro" frameBorder="0" scrolling="no" ></iframe>');
return false;
});
});
</script>
<ul>
<li>An <span style="font-family:'Courier New'">Ajax.ActionLink</span> is embedded into a Razor view</li>
<li>... and configured so that when the link is clicked, a particular controller action is called.</li>
<li>The controller action returns a <span style="font-family:'Courier New'">PartialViewResult</span></li>
<li>...and another parameter of the <span style="font-family:'Courier New'">ActionLink</span> directs the <span style="font-family:'Courier New'">PartialViewResult</span> into a page element (by specifying it's ID)</li>
</ul>
<p>Note that we haven't written any Javascript or frontend code - we will discuss that shortly.</p>
<p>The view:</p>
<pre class="brush:csharp">
<h2>Reviews</h2>
@Ajax.ActionLink("Click here to see the latest review",
"LatestReview", //The controller action to call
new AjaxOptions
{
UpdateTargetId = "latestReview", //The page id to
InsertionMode.InsertAfter, //fill with the
HttpMetho = "GET" //PartialViewResult
})
<div id="latestReview">
<!-- The PartialViewResult will be inserted here -->
</div>
</pre>
The controller:
<pre class="brush:csharp">
public class HomeController : Controller
{
public PartialViewResult LatestReview()
{
var review = reviewRepository.FindLatest(1).Single();
return PartialView("Review", review);
}
}
</pre>
<p>The only other things discussed are using different <span style="font-family:'Courier New'">InsertionMode</span>'s (<span style="font-family:'Courier New'">InsertAfter</span>, <span style="font-family:'Courier New'">Replace</span> etc.) This specifies how to handle content insertion to the specified <span style="font-family:'Courier New'"><div></span>.</p>
<p>And adding an extra argument to specify an element to display while the content loads - i.e. a progress / status indicator image.</p>
<p><span style="font-weight: bold">Video 3: Unobtrusive Javascript</span><br />
The next video is where things get interesting. We get to see what exactly it is that our <span style="font-family:'Courier New'">Ajax.ActionLink</span> call spits out to the page...</p>
<a href="#" id="Ajax4" style="height:405px;width:575px;background:black;display:block;text-align:center;">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGWy_pWS8_4w6VMF-hKujvOM73WX_AXmueqloUIixY3DIozc6R9Jl4cB4uvVR2Vxg_Kv4dott4NgP0GG7muUs4srIAWV2_LClXc_wQZbDxKXy2nY2xsJURG0LN-XwQzel2COY0ZQRTuvmr/s320/play.png" alt="Play video" style="position:relative;top:166px;" />
</a>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#Ajax4").click(function(){
$(this).html('<iframe style="height:405px;width:575px" src="http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=4&course=aspdotnet-mvc3-intro" frameBorder="0" scrolling="no" ></iframe>');
return false;
});
});
</script>
<p>...which is this:</p>
<pre class="brush: xml">
<div id="latestReview">
<a data-ajax="true"
data-ajax-loading="#progress"
data-ajax-method="GET"
data-ajax-mode="replace"
data-ajax-update="#latestReview"
href="/Home/LatestReview">
Click here to see the latest review
</a>
</div>
</pre>
<p>All those 'data-dash' attributes (<span style="font-family:'Courier New'">data-ajax</span>, <span style="font-family:'Courier New'">data-ajax-loading</span> etc.) are a part of the HTML5 specification. Or rather, they are not. Anything prefixed by <span style="font-family:'Courier New'">data-</span> is considered by the specification to be a valid attribute, but is known to be there only to support dynamic features of the page. The attributes therefore are ignored by browser rendering engines and HTML markup validation services.</p>
<p>With these attributes carrying all of the custom data for this link's behaviour, all we need is a generic javascript file whose job it is to go looking for elements with <span style="font-family:'Courier New'">data-ajax-*</span> attributes, and to manipulate them to achieve the desired behaviour. This file is <span style="font-family:'Courier New'">jquery.unobtrusive-ajax.js</span>, provided by Microsoft, which must ofcourse be included after the main jQuery library.</p>
<p><span style="font-weight:bold;">3b. Unobtrusive jQuery validation</span><br />
The video then jumps on to a related topic. Microsoft also happen to include an extension to the <a href="http://docs.jquery.com/Plugins/Validation">jQuery validation</a> library: <span style="font-family:'Courier New'">jquery.validate.unobtrusive.js</span>. This makes validation message-handling also unobtrusive.</p>
<p>The video goes on to show how data annotations on model classes can be easily piped through onto unobtrusive Views.</p>
<p>The model:</p>
<pre class="brush: csharp; highlight: 5">
public class Review : IValidatableObject
{
public virtual int Id { get; set; }
[Range(1, 10)]
public virtual int Rating { get; set; }
//etc
}
</pre>
<p>The view:</p>
<pre class="brush: xml; highlight: [11];">
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rating)
@Html.ValidationMessageFor(model => model.Rating)
</div>
<!-- etc -->
</pre>
<p>Basically then the HtmlHelpers do all the javascript work for you.</p>
<p>I'll explain how in a minute, but as a brief aside - The data annotations are from the <span style="font-family:'Courier New'">System.ComponentModel.DataAnnotations</span> namespace introduced in .NET 3.5 (notice the the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject.aspx">IValidatableObject</a> interface). For those of us using the Enterprise Library's <a href="http://msdn.microsoft.com/en-us/library/ff650484.aspx">Validation Application Block</a>, it seems that Enterprise Library 5.0 introduces interoperability between the two annotation frameworks, although I haven't tried this myself yet. For a quick intro to the features of the two systems, check out <a href="http://stackoverflow.com/questions/3565097/dataannotations-or-application-validation-block">this Stack Overflow post</a>.</p>
<p>Anyway, moving on - The way the HtmlHelpers render your javascript depends on your appSettings:</p>
<pre class="brush: xml">
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
</appSettings>
</pre>
<p>Obviously the first needs to be true to render any javascript validation at all. But the second determines the method. When it is false, standard XHTML tags are rendered with a bunch of inline, on-the-page javascript. When it is true, the HTML5 <span style="font-family:'Courier New'">data-</span> tags are rendered and <span style="font-family:'Courier New'">jquery.validate.unobtrusive.js</span> (and <span style="font-family:'Courier New'">jquery.unobtrusive-ajax.js</span>) do all the work.</p>
<p><span style="font-weight: bold;">Video 4. Using Ajax.BeginForm</span><br />
The fourth video shows how to use <span style="font-family:'Courier New'">Ajax.BeginForm</span> to create small, Ajax-only forms, such as a search query:</p>
<a href="#" id="Ajax5" style="height:405px;width:575px;background:black;display:block;text-align:center;">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGWy_pWS8_4w6VMF-hKujvOM73WX_AXmueqloUIixY3DIozc6R9Jl4cB4uvVR2Vxg_Kv4dott4NgP0GG7muUs4srIAWV2_LClXc_wQZbDxKXy2nY2xsJURG0LN-XwQzel2COY0ZQRTuvmr/s320/play.png" alt="Play video" style="position:relative;top:166px;" />
</a>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#Ajax5").click(function(){
$(this).html('<iframe style="height:405px;width:575px" src="http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=5&course=aspdotnet-mvc3-intro" frameBorder="0" scrolling="no" ></iframe>');
return false;
});
});
</script>
<p>As you can see, it starts to get a bit obvious at this point. Here's the View...</p>
<pre class="brush: csharp">
@using(Ajax.BeginForm("Search", "Home",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "searchResults"
}))
{
<input type="text" name="q" />
<input type="submit" value="Search" />
}
<table id="searchResults">
<!-- The PartialViewResult will be inserted here -->
</table>
</pre>
<p>...and you can imagine what the Controller method looks like - pretty much the same as the Controller method from video 2!</p>
<p>The rest of the videos go on to discuss:</p>
<ul>
<li><a href="http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=6&course=aspdotnet-mvc3-intro">Autocompletion with jQuery UI</a> (filling in search results as the user types)</li>
<li><a href="http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=7&course=aspdotnet-mvc3-intro">jQuery UI datepicker</a></li>
<li><a href="http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=8&course=aspdotnet-mvc3-intro">jQuery UI templates</a></li>
</ul>
<p>So it's a bit off-topic for this article, but useful how-to's. I hope you found this article useful, and be sure to check out <a href="http://www.pluralsight-training.net/microsoft/courses/tableofcontents?courseName=aspdotnet-mvc3-intro">the rest of the Pluralsight MVC3 training videos</a>.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-8808702138139275442011-10-03T17:20:00.011+01:002012-02-15T17:27:12.522+00:00Selected Items with HtmlHelpers<p>I came across an odd 'feature' of MVC Html Helpers today: Even if you explicitly provide a selected value when you call an option-based Helper, there's no guarantee that selected value will be used.</p>
<p>Suppose you are creating a view - an edit page for a Book. You declare something like this in your view. Note that we are passing in a new Author object as our currently selected item - so it shouldn't match anything and no items should be selected:</p>
<pre class="brush: csharp;"><% var selectList =
new SelectList(Model.Authors, "Id", "Name", new Author()); %>
<%=Html.DropDownList("book.Author.Id", selectList,
"Please select")%>
</pre>
<p>The fourth argument to your SelectList constructor is a new <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Author</span> object. As such when you view your edit page you would expect the drop-down to default to "Please select".</p>
<p>In reality though, the drop-down defaults to the author associated in your model..? This may be the behaviour you normally want from an edit page, but when your business rules suggest that the field not be pre-populated, you can't live up to it without a mild hack.</p>
<p>What's happening is the Html Helper is looking at your View Model object, for an item that looks like the first argument: <span style="font-family: 'Courier New'">"book.Author.Id"</span></p>
<p>When it finds it, the Helper is favouring that Id value over your suggestion. Not exactly putting you in the driving seat is it?</p>
<p>One workaround? It's not the nicest-looking, but set the View Model value to what you want just before calling the Helper:</p>
<pre class="brush: csharp; highlight: 1">Model.Book.Author = new Author();
<% var selectList =
new SelectList(Model.Authors, "Id", "Name", new Author()); %>
<%=Html.DropDownList("book.Author.Id", selectList,
"Please select")%>
</pre>
<p>It may not be pretty, but it works.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-13954031098841829212011-07-22T14:33:00.015+01:002012-02-15T17:52:02.947+00:00Lambda Expressions in C#<p>In a previous article I <a href="http://jahyacode.blogspot.com/2011/07/introduction-to-delegates-in-c.html">introduced delegates and anonymous delegates</a>. In this article I intend to explain the fundamentals of Lambda expressions by building on our knowledge of delegates. It's useful to get a proper handle on delegates before delving into Lambdas, because Lambdas are just anonymous delegates in different clothing.</p>
<p><span style="font-weight:bold;text-decoration:underline;">A Quick Example</span><br />
At the end of my post on delegates, I introduced a common scenario where you might want to use an anonymous delegate to find an item from a list:</p>
<pre class="brush: csharp; highlight: [11,12]">class AdHocSearch
{
static void Main()
{
List<Book> bookDb = new List<Book>();
bookDb.Add(new Book(){ title = "Romancing the Stone" });
bookDb.Add(new Book(){ title = "Wuthering Heights" });
Book foundBook = bookDb.Find(delegate(Book candidate)
{
return candidate.title.Equals(
"Wuthering Heights");
});
Console.WriteLine(foundBook.title);
}
}
</pre>
<p>However the same code can easily be refactored to use a Lambda expression (if you use ReSharper just hit Alt+Enter and it will refactor for you):</p>
<pre class="brush: csharp; highlight: [10,11]">class AdHocSearch
{
static void Main()
{
List<Book> bookDb = new List<Book>();
bookDb.Add(new Book(){ title = "Romancing the Stone" });
bookDb.Add(new Book(){ title = "Wuthering Heights" });
Book foundBook = bookDb.Find(
candidate => candidate.title.Equals(
"Wuthering Heights"));
Console.WriteLine(foundBook.title);
}
}
</pre>
<p>The portion highlighted is the Lambda expression, and it does the same job as the delegate in the first code-block. However it does it in a way which is slightly different - it is more concise, and it's declaration is less explicit.</p>
<p>Let's start from the top - the Lambda operator.</p>
<p><span style="font-weight:bold;text-decoration:underline;">The Lambda Operator</span><br />
You can tell you are looking at a lambda expression when you see the lambda operator <span class="Apple-style-span" style="font-family: inherit;">(</span><span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">=></span><span class="Apple-style-span" style="font-family: inherit;">)</span>. This operator can be read as "goes to":</p>
<pre class="brush: csharp;">x => x * x
</pre>
<p>So this expression (above) is read as "x goes to x times x".</p>
<p><span style="font-weight:bold;text-decoration:underline;">How do we Get from Delegate to Lambda?</span><br />
Let's explain the above expression by showing how it would look in familiar, delegate form. Then we can alter it step by step until it becomes a lamba expression again. Here's the fully written-out delegate equivalent of the above statement (below). I have written this in a way which should be familiar from <a href="http://jahyacode.blogspot.com/2011/07/introduction-to-delegates-in-c.html">my previous post on delegates</a>:</p>
<pre class="brush: csharp">public delegate int Square(int i);
void Main()
{
Square square = delegate(int i)
{
return i*i;
};
}
</pre>
<p>In the code-block above, the first thing to notice is that we have a named <span style="font-style:italic;font-weight:bold;">delegate type</span> - it's name is <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Square</span>. This is the first line in the code-block, the declaration that essentially says (in English) "There is a delegate type named <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Square</span>, it has a single <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int</span> input parameter, and an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int</span> return type."</p>
<p>Inside the body of the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Main</span> method, we have then instantiated an instance of <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Square</span>, (named lower-case <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">square</span>), and assigned an anonymous delegate to it.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Step 1: Anonymise the Delegate Type</span><br />
Well now, we are going to anonymise the <span style="font-style:italic;font-weight:bold;">delegate type</span> aswell as the delegate. Anonymising means declaring the same behaviour, but without specifying a name. So in English: "There is a delegate type <strike>named <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Square</span></strike>, it has a single <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int</span> input parameter, and an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int</span> return type".</p>
<p>Since we are no longer giving it a name, we must declare it at the same time as assigning a value to it, and therefore now the whole thing is enclosed within one statement. Remember, we are still naming the variable (lower-case <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">square</span>), but we are no longer naming the type (was init-capped <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Square</span>):</p>
<pre class="brush: csharp; highlight: [1,5,15]">public delegate int Square(int i);
void Main()
{
Square square = delegate(int i)
{
return i*i;
};
}
//becomes
void Main()
{
Func<int, int> square = delegate(int i)
{
return i*i;
};
}
</pre>
<p>To do this we used a type named <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Func<T, TResult></span> (see the <a href="http://msdn.microsoft.com/en-us/library/bb549151.aspx">definition here</a>), which was introduced in C# 3.5. This class allows us to encapsulate a method as a <a href="http://jahyacode.blogspot.com/2011/07/heap-and-stack.html">reference-type</a>, and pass in a couple of generic type parameters describing the argument and return type respectively: <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"><int, int></span>.</p>
<p>You'll notice that there are several variations on <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Func</span>, each with a different number of generic type parameters. You can encapsulate a method with up to <a href="http://msdn.microsoft.com/en-us/library/dd402862.aspx">16 arguments</a>, and there is a similar family of classes to deal with <a href="http://msdn.microsoft.com/en-us/library/018hxwa8.aspx">methods with no return type</a>. Any method you assign to an instance of one of these types has to have matching input parameters and return type, and you can see in the code-block above this is the case.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Step 2: Switch to Lambda Syntax</span><br />
Now let's convert the delegate on the right side of that assignment operation into a lamda expression:</p>
<pre class="brush: csharp">Func<int, int> square = delegate(int i)
{
return i*i;
};
//becomes
Func<int, int> square = i => i * i;
</pre>
<p>And there we have the same statement we started with. It uses the same variables to do the same thing and return the same value - but with different syntax.</p>
<p>The first thing you notice is how concise it is, even though it does exactly the same job. On the left side of the operator, we always have the input parameters.</p>
<ul class="compact" style="text-align: left;"><li>left-of-the-operator - input parameters,</li>
<li>right-of-the-operator - expression or statement block</li>
</ul>
<p>Remember, the operator is read as "goes to". So a lambda is always read as "input (goes to) expression", or "input (goes to) statement block".</p>
<p><span style="font-weight:bold;text-decoration:underline;">Inferred Typing</span><br />
With the delegate version we had to specify the <i>type </i>of the input parameter, when we said: <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">delegate(int i)</span>. However with lambdas the compiler infers the type of <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">i</span> from it's usage. The compiler sees that we are assigning the expression to a strongly-typed <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Func</span> object with generic type parameteres <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"><int, int></span>. So it knows and doesn't need to be retold that the input parameter <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">i</span> in the expression is an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int</span>.</p>
<p>Don't make the mistake of thinking this is loosely-typed. Loose-typing is not possible in the .NET Framework. This is <span style="font-style:italic">inferred</span> typing, which is still very much strongly-typed. Type usage is inferred by the compiler on initialisation and cannot change. It is part of the suite of implicit-typing functionality introduced in C# 3.0, including:</p>
<ul class="compact" style="text-align: left;"><li><a href="http://msdn.microsoft.com/en-us/library/bb384061.aspx">Implicitly-typed local variables</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb384090.aspx">Implicitly-typed arrays</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx">Anonymous reference-types</a></li>
</ul>
<p>In fact, one of the main benefits of lambda's, is they are a simple way to make many previously un-type-safe operations type-safe. Take a quick look at <a href="http://bugsquash.blogspot.com/2008/03/strongly-typed-nhibernate-criteria-with.html">Mauricio Scheffer's blog here</a>, where he has used lambda's to replace string literals. You see this type of usage a lot in .NET frameworks and packages nowadays.</p>
<p>In the first example in the first code-block of this post, without Lambdas or delegates the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Find</span> method would only be possible by passing in string literals representing the desired candidate properties. And you can also see, for example, from <a href="http://jahyacode.blogspot.com/2011/07/ioc-containers-and-dependency-injection.html">my post on StructureMap IoC</a>, that statement lambdas are now the preferred initialisation approach (though the previous approach was also typesafe).</p>
<p><span style="font-weight:bold;text-decoration:underline;">Specifying Input Parameters</span><br />
If you want to override the compiler's inferred usage, you can use brackets on the left-side of the lambda operator to specify input parameters:</p>
<pre class="brush: csharp">Func<int, int> square = (int i) => i * i;
</pre>Or, if you have no parameters to pass in, just use empty brackets:<br />
<pre class="brush: csharp">Func<int> noParams = () => 5 * 5;
</pre>
<p>I have to admit i'm not sure yet where or when this would be useful.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Expression Lambdas vs. Statement Lambdas</span><br />
So far we've only been using Expression Lambdas, which means that on the right-side of the lambda operator there is one, single expression. This is generally useful when you are trying to apply a function, such as <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Square</span> above, or trying to apply a predicate, such as the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">List.Find</span> example at the top of this article.</p>
<p>However you can construct multi-line, procedural lambdas if you wish, by using curly braces:</p>
<pre class="brush: csharp">Action<string> speakToWorld = n =>
{
string s = n + " " + "World";
Console.WriteLine(s);
};
speakToWorld("Hello");
</pre>
<p><span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Action</span> is ofcourse the cousin of <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Func</span>, but never returns a value (see <a href="http://msdn.microsoft.com/en-us/library/018hxwa8.aspx">the reference page here</a>).</p>
<p><span style="font-weight:bold;text-decoration:underline;">Expression Trees</span><br />
One final thing to note here is the broader context within which both lambda's and delegates exist. We have moved into an arena where functionality now has the same status as value. What I mean is that we are used to assigning and manipulating values (and objects encapsulating values) within variables. Now it is just as easy to build and manipulate functionality. Expression trees are an example of that.</p>
<p>Earlier we used <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Func</span> and <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Action</span> to store our method pointers. These allow truly anonymous references to executable code. But these classes can be assembled and re-assembled in their own right, as components of an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Expression</span> object.</p>
<p>Have a quick look at <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx">the MSDN on Expression Trees</a>:</p>
<p>"Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y."<br />"You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries."</p>
<p>A quick example from <a href="http://www.codeproject.com/KB/cs/explore_lamda_exp.aspx">the-code-project</a>:</p>
<pre class="brush: csharp">ParameterExpression parameter1 =
Expression.Parameter(typeof(int), "x");
BinaryExpression multiply =
Expression.Multiply(parameter1, parameter1);
Expression<Func<int, int>> square =
Expression.Lambda<Func<int, int>>(multiply, parameter1);
Func<int, int> lambda = square.Compile();
Console.WriteLine(lambda(5));
</pre>
<p>In the code-block above, we have done the same thing our simple lambda expression from earlier does - square a number. It is much more verbose, yes, but look at the types on the last two lines before <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Console.WriteLine</span>. We created a dynamic <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Expression</span> object, which can be altered and assembled ad-hoc however you like at runtime - and then <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Compile()'</span>d into executable code, and run - again, all at runtime.</p>
<p>In other words, you can have your code assemble more code as it runs. Or in other words again, you can have your code treat itself in the same, flexible way it used to only be able to treat data and values.</p>
<p>Aside from generating dynamic queries, what does this allow us to do? As <a href="http://stackoverflow.com/questions/1532600/whats-a-good-use-case-for-net-4-0-expression-trees">this stack-overflow page</a> points out, we can hand the power of code customisation over to users. Ever made a 'form builder', allowing users to customise post-driven dynamic webpages? I can't imagine how we did that in the past but they've just got a whole lot easier, and semantically correct. Or what about user-customised workflows? Ditto.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Further Reading</span></p>
<ul>
<li><a href="http://www.codeproject.com/KB/cs/explore_lamda_exp.aspx">Lambdas and Expression trees on the-code-project</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx">Expression Trees on MSDN</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx">Lambda Expressions on MSDN</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx">Anonymous Methods on MSDN</a></li>
</ul>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-81593669086122421672011-07-21T17:44:00.005+01:002012-02-15T18:18:44.359+00:00Introduction to Delegates in C#<p>What is a delegate? Most articles dive straight into the technical stuff, but I think it makes it easier to learn when you start by looking at the metaphor - I will dive right into the practical example straight afterwards.</p>
<p>So first of all, what makes the word 'delegate' such an apt keyword?</p>
<p><span style="font-weight:bold;text-decoration:underline;">The Metaphor</span><br />
According to Wikipedia, a <a href="http://en.wikipedia.org/wiki/Delegate">delegate</a> is a person who is similar to a representative, but "delegates differ from representatives because they receive and carry out instructions from the group that sends them, and, unlike representatives, are not expected to act independently."</p>
<p>Imagine a government department is employing two private companies to carry out litter collection across two districts. The government are responsible for preparing the contracts, and intend to use a standard template contract for both private companies. But the two private companies have different operating practices, and each want to tailor their respective contracts to suit their own particular needs.</p>
<p>They each send a <span style="font-style:italic;font-weight:bold;">delegate</span> to meet the government and make amendments to their respective contracts. Each delegate is briefed by their respective companies before they leave, so that they know exactly what their instructions are. Each delegate arrives intending to do the same thing - amend a contract. But their instructions and boundaries on how they can do that are different - and are defined clearly by the respective senders.</p>
<p>I'll end the metaphor here, because I don't want to lock into one example. But having that sense of what a delegate <span style="font-style:italic">is</span> should make the rest of this article easier to read.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Declaring a Delegate Type</span><br />
First, let's declare a publicly accessible <span style="font-weight:bold;font-style:italic;">delegate type</span>:</p>
<pre class="brush: csharp">//Declare a delegate type
public delegate void BookProcessingDelegate(Book b);
</pre>
<p>It is important at this stage to understand that what we have defined is not a delegate but a <span style="font-weight:bold;font-style:italic;">delegate type</span>. Each instance we later instantiate of this type will be an actual delegate.</p>
<p>Delegates are usually declared not as class members, but as peers of classes or structs, i.e. at the same level. This is because declared delegate types are types in their own right. They can ofcourse, also be declared nested inside a class (just like a class can be declared nested inside a class).</p>
<p>In other words, a delegate is an example of a reference-type, and is stored on the heap and accessed via a pointer (see my <a href="http://jahyacode.blogspot.com/2011/07/heap-and-stack.html">article on types, the stack and the heap</a>).</p>
<p><span style="font-weight:bold;text-decoration:underline;">Instantiating and Assigning a Delegate Method</span><br />Having declared our delegate type, there are three things we need to do to make use of it:</p>
<ol class="compact" style="text-align: left;"><li>Define a method (write some instructions)</li>
<li>Instantiate a delegate and assign the method to it (brief the delegate of our instructions)</li>
<li>Send the delegate off to do business on our behalf</li>
</ol>
<p>I'm going to use a variation of the 'classic' delegate example, and note that I've commented numerically the implementation of the bullet points above:</p>
<pre class="brush: csharp;">//Declare a delegate type
public delegate void BookProcessingDelegate(Book b);
public class Book
{
public string title { get; set; }
}
public class BookDB
{
private IList<Book> books;
public void ProcessBooks(BookProcessingDelegate del)
{
foreach(Book b in books)
{
// Call the delegate method
del(b);
}
}
}
class Program
{
//1. Define a method
private static void PrintBookTitle(Book b)
{
Console.WriteLine(b.title);
}
static void Main()
{
BookDB bookDb = new BookDB();
//2. Instantiate a delegate, and assign the method
BookProcessingDelegate printTitles = PrintBookTitle;
//3. Send the delegate off to do work on our behalf
bookDb.ProcessBooks(printTitles);
}
}
</pre>
<p>When we assign the method to the delegate (item 2 above), we are actually assigning to the delegate a pointer to the method. Then, when the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BookDB.ProcessBooks</span> method uses (invokes) the delegate, it follows the pointer and actually invokes the referenced method.</p>
<p>Logically, it is exactly the same as if the body of the referenced method had been declared inside of BookDB. But ofcourse it wasn't, and that's the key to the usefulness of delegates - i'll discuss this in more detail shortly.</p>
<p>But first of all let's explore two more ideas - anonymous delegates, and multicast delegates.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Anonymous Delegates</span><br />
In the above example, we assigned a <i>named</i> method which was a private class member (namely <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">PrintBookTitle</span>). If that method is only going to be used for this one specific purpose, it can be much more convenient to declare an anonymous method.</p>
<p>What follows is exactly the same code block as above, but now the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">PrintBookTitle</span> method has been anonymised, causing steps 1 and 2 to become one statement:</p>
<pre class="brush: csharp">class Program
{
static void Main()
{
BookDB bookDb = new BookDB();
//1. Define a method AND
//2. Instantiate a delegate, and assign a method
BookProcessingDelegate printTitles = delegate(Book b) {
Console.WriteLine(b.title);
};
//3. Send the delegate off to do work on our behalf
bookDb.ProcessBooks(printTitles);
}
}
</pre>
<p>Anonymous delegates are more concise, and they are the foundation of lambda expressions, which I <a href="http://jahyacode.blogspot.com/2011/07/lambda-expressions-in-c.html">discuss in another article</a>.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Multicast Delegates</span><br />
It's another odd word, but <a href="http://en.wikipedia.org/wiki/Multicast">multicast is based on another metaphor</a>. Check out the link to get a quick sense of that, but it's simple enough anyway. You can assign more than one method to a delegate. The delegate will respond when invoked, by executing each method in order:</p>
<pre class="brush: csharp">class Program
{
private static void PrintLower(Book b) {
Console.WriteLine(b.title.ToLower());
}
private static void PrintUpper(Book b) {
Console.WriteLine(b.title.ToUpper());
}
static void Main()
{
//Instantiate a delegate, and assign TWO methods
BookProcessingDelegate printTitles = PrintUpper;
printTitles += PrintLower;
//You can also use the -= operator to remove methods
//from the 'invocation list'
printTitles -= PrintLower;
}
}
</pre>
<p>You can add and remove methods to your heart's content. The resulting list of methods which must be called on invocation of the delegate is referred to as the delegate's <span style="font-weight:bold;font-style:italic;">invocation list</span>.</p>
<p>If the delegate has a return value, only the value returned by the last method in the invocation list will be returned. Similarly, if the delegate has an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">out</span> or <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ref</span> parameter, the parameter will end up being equal to the value assigned in the last method in the invocation list (see also my article on <a href="http://jahyacode.blogspot.com/2011/07/pass-by-reference-in-c.html">parameter passing in C#</a>).</p>
<p><span style="font-weight:bold;text-decoration:underline;">What Are Delegates Useful For?</span><br />
As we have seen, delegates give us the ability to assign <i>functionality</i> at runtime. This adds to our toolbox of assignment operations - we all know how easy it is to assign values, or references to objects. Now we can assign functionality too.</p>
<p>Look back to the first, main code-block of this article. It should be clear that any class, anywhere in your application that chooses to call <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BookDB.ProcessBooks</span> can do so and provide it's own specific, tailored functionality. The <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Program</span> class happens to have sent one particular type of functionality (printing to the console), but any delegate can point to any method implementation.</p>
<p>Without delegates, the creators of the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BookDB</span> class would have to have thought up in advance <span style="font-style:italic">every possible thing</span> that callers might want to do with the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Book</span> list - and provide lots of methods to cover all those bases. In doing so, the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BookDB</span> class would be taking on responsibilities that are not within it's problem domain.</p>
<p>The other way to achieve the same functionality without delegates would be for the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BookDB</span> to expose it's internal list as a property, or via an access method. The <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Program</span> class could then iterate over the collection itself. But this approach would mean that the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Program</span> class was shouldering responsibilities that are not within it's domain - iterating over a collection.</p>
<p>Delegates therefore provide an elegant solution which helps achieve the <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">Seperation of Concerns</a> principle within your application architecture.</p>
<p><span style="font-weight:bold;text-decoration:underline;">A Common Usage - Ad-Hoc Searching</span><br />
There are lots of places in the .NET Framework where you can use delegates, and their newer equivalent, <a href="http://jahyacode.blogspot.com/2011/07/lambda-expressions-in-c.html">lambda expressions</a>. We'll take a look at one example, by altering our <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BookDB</span> code a little. Let's say you want to find a book with a particular title, from a list of <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Book</span> items:</p>
<pre class="brush: csharp">class AdHocSearch
{
static void Main()
{
List<Book> bookDb = new List<Book>();
bookDb.Add(new Book() { title="Romancing the Stone" });
bookDb.Add(new Book() { title="Wuthering Heights" });
Book foundBook = bookDb.Find(delegate(Book candidate)
{
return candidate.title.Equals("Wuthering Heights");
});
Console.WriteLine(foundBook.title);
}
}
</pre>
<p>If you couldn't use a delegate, you would have to manually iterate over the list. But fortunately for us, the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">List<T>.Find()</span><span class="Apple-style-span" style="font-family: inherit;"> method </span>will accept a delegate function which describes how to apply a condition which determines a match for us. This leaves the job of iterating the collection, with it's associated efficiency concerns, in the correct problem domain - the domain of the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">List</span>.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Quick Runthrough</span><br />
For a nice, quick, concise primer on the subjects I've discussed above, check out this Youtube video:</p>
<iframe allowfullscreen="" frameborder="0" height="349" src="http://www.youtube.com/embed/FgctfDmagx0" width="425"></iframe>
<p>I don't think it stands up as a learning resource in it's own right, but as a primer it's quite well organised.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Further Reading</span><br />
This is quite a nice <a href="http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx">delegates tutorial on MSDN</a>.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-78538014882596335462011-07-20T21:28:00.001+01:002012-02-15T18:39:34.796+00:00Pass by Value and Pass by Reference in C#<p>This article is a quick explanation of C#'s handling of pass-by-val and pass-by-ref. If you haven't already done so, it's a worth getting to grips with <a href="http://jahyacode.blogspot.com/2011/07/heap-and-stack.html">the heap and the stack</a> - that article will also explain the relationship between value types, reference types and pointers, which will be really useful.</p>
<p><span style="font-weight: bold;text-decoration:underline;">Value-Types</span><br />By default, <span style="font-weight:bold;font-style:italic">value types</span> are 'passed-by-value' into C# methods. This means that inside the body of the called method, the value instance can be changed or re-assigned without affecting the instance of the value in the caller.</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
int i = 1;
Console.WriteLine(i); // prints 1
MyMethod(i);
Console.WriteLine(i); // prints 1
}
static void MyMethod(int i)
{
i = 2;
}
</pre>
<p>If you want to override this behaviour, you can use the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ref</span> keyword or <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">out</span> keyword:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
int i = 1;
Console.WriteLine(i); // prints 1
MyMethod(ref i);
Console.WriteLine(i); // prints 2
}
static void MyMethod(ref int i)
{
i = 2;
}
</pre>
<p>You can use the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ref</span> or the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">out</span> keyword, the only difference it makes is that <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ref</span> needs the value to have been initialised before it is passed.</p>
<p>The compiler will issue an error if you try to send an unassigned variable with the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ref</span> keyword, but it will let you send happily using <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">out</span>. Ofcourse, if you don't have logic to handle the unassigned <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">out</span> variable in the target method you will get a runtime exception anyway.</p>
<p><span style="font-weight: bold;text-decoration:underline;">Reference-Types</span><br />
There really is <span style="font-style:italic">no way</span> to pass reference-types <span style="font-style:italic">other than</span> by reference. So although you can use the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">out</span> and <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ref</span> keywords with an object, there really isn't much point:</p>
<pre class="brush: csharp">static void Main(string[] args)
{
MyClass myObj = new MyClass();
MyMethod(ref myObj); //not much point
}
</pre>
<p>If you want to pass a reference-type variable by-<i>value</i>, you need to start thinking about cloning the object, which is a whole new subject matter in itself. If you simply want to prevent the passing object from being altered you might want to consider making the class immutable, but in any case that's outside the scope of this article.</p>
<p><span style="font-weight: bold;text-decoration:underline;">More examples</span></p>
<ul><li><a href="http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx">The MSDN on 'out'</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/14akc2c7.aspx">The MSDN on 'ref'</a></li></ul>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-75670382476956978052011-07-18T12:58:00.001+01:002012-02-15T21:25:25.627+00:00Boxing and Unboxing in C#<p>C#, like all .NET languages, uses a unified type system (called <a href="http://en.wikipedia.org/wiki/C_Sharp_(programming_language)#Common_Type_System_.28CTS.29">Common Type System</a>). The idea is that all types that can ever be declared within the framework, always ultimately derive from <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">System.Object</span>. <a href="http://www.codeproject.com/KB/dotnet/6importentStepsDotNet.aspx#So which data types are ref type and value type">This diagram</a> gives you some idea how that works at the top-level.</p>
<p>However if primitive datatypes such as <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int</span> and <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">bool</span> were to be stored always as objects it would be a huge performance hit. So in reality, at any given moment these primitive types are capable of being represented in one of two ways:</p>
<ul class="compact"><li>As a <span style="font-weight:bold;font-style:italic;">value type</span> - stored on the stack or the heap</li>
<li>As a <span style="font-weight:bold;font-style:italic;">reference type</span> - stored on the heap</li>
</ul>
<p>(Check out my <a href="http://jahyacode.blogspot.com/2011/07/heap-and-stack.html">article on value types, reference types, the stack and the heap</a>.)</p>
<p><span style="font-weight:bold;text-decoration:underline">Boxing</span><br />
Boxing is the name given to the process of converting a value-type representation to a reference-type representation. The process is implicit - just use an assignment operator and the compiler will infer from the types involved that boxing is necessary:</p>
<pre class="brush: csharp">public static void BoxUsingObjectType()
{
const int i = 0;
object intObject = i; //Boxing occurs here
}
</pre>
<p>In the above example the integer <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">i</span> is boxed into a generic object. This is the type of usage that you will generally see - usually the point of boxing is so that you can treat the value-type in a generic way (alongside reference-type objects). More on that later.</p>
<p>It's also useful to note that you can box directly to the correct type:</p>
<pre class="brush: csharp">public static void BoxUsingCorrectTypes()
{
const short s = 0; //equivalent to System.Int16
System.Int16 shortObject = s;
const int i = 0; //equivalent to System.Int32
System.Int32 intObject = i;
const long l = 0; //equivalent to System.Int64
System.Int64 longObject = l;
}
</pre>
<p>In fact all that happens when you box an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int</span> to an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">object</span> is that it is first boxed and then <a href="http://en.wikipedia.org/wiki/Downcasting">downcasted</a>.</p>
<p>The example below shows that you cannot box a larger value-type into a smaller reference-type, for the obvious reason that data will be lost. However, the reverse is possible, you can box a smaller value-type into a larger reference-type:</p>
<pre class="brush: csharp">public static void BoxToDifferentSizedTypes()
{
const int intVal = 0; //equivalent to System.Int32
const long longVal = 0; //equivalent to System.Int64
/* This is fine */
System.Int64 longObject = intVal;
/* This causes a compiler error */
System.Int32 intObject = longVal;
}
</pre>
<p>The second assignment operation above causes a compiler error.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Unboxing</span><br />
The process of unboxing is explicit, and uses the same syntax as casting. Ofcourse, casting can only occur between two reference-type variables, so when the compiler encounters the syntax below with a value-type on the left and a reference-type on the right, it infers that unboxing is necessary:</p>
<pre class="brush: csharp">public static void UnBox(System.Int32 intObject)
{
int i = (int) intObject; //Unboxing occurs here
}
//or
public static void UnBox(object intObject)
{
int i = (int) intObject; //Unboxing occurs here
}
</pre>
<p><span style="font-weight:bold;text-decoration:underline">Why Would you Use Boxing?</span><br />
You generally wouldn't - and one good reason to know about it is to help avoid it. Like casting, it's an expensive operation. Here's a common scenario where you might inadvertently box:</p>
<pre class="brush: csharp">int i = 10;
string s = string.Format("The value of i is {0}", i);
</pre>
<p>But the most common usage of boxing is in collections. In the .NET 1.1 days you might have used an <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ArrayList</span> something like this:</p>
<pre class="brush: csharp">ArrayList list = new ArrayList();
list.Add(10); // Boxing
int i = (int) list[0]; // Unboxing
</pre>
<p>Because <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ArrayList</span> boxes and downcasts to <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">object</span>, this is an expensive operation.</p>
<p>Now in the era of <a href="http://msdn.microsoft.com/en-us/library/512aeb7t(v=VS.100).aspx">generics</a> this is less of a problem, because when you use a primitive type as a generic parameter, such as the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"><int></span> below, it is <span style="font-style:italic;">not</span> boxed, and it <span style="font-style:italic;">is</span> typesafe. This is a very good reason to use a generic collections.</p>
<pre class="brush: csharp">List<int> list = new List<int>();
list.Add(10); // No Boxing
int i = list[0]; // No Unboxing
</pre>
<p><span style="font-weight:bold;text-decoration: underline;">Generically-Typed Collections</span><br />
The problem comes when you want to use a mixed list. First, how it looks in .NET 1.1:</p>
<pre class="brush: csharp">ArrayList list = new ArrayList();
list.Add(10); // Boxing
list.Add(new SomeClass()); // Downcasting
int y = (int) list[0]; // Unboxing
SomeClass o = (SomeClass) list[1]; // Casting
</pre>
<p>Even with a generic list, we have to use object, or some common ancestor type, to ensure that our list will accept all values:</p>
<pre class="brush: csharp">List<object> list = new List<object>();
list.Add(10); // Boxing
list.Add(new SomeClass()); // Downcasting
int y = (int) list[0]; // Unboxing
SomeClass o = (SomeClass) list[1]; // Casting
</pre>
<p>This is very similar to using <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ArrayList</span>. But although there are no efficiency gains, with generics we explicitly have control as to what level casting operations occur.</p>
<p>There are some discussions <a href="http://stackoverflow.com/questions/1028520/use-cases-for-boxing-a-value-type-in-c">here</a> and <a href="http://stackoverflow.com/questions/1949122/boxing-and-unboxing-when-does-it-come-up">here</a> on stack-overflow about other possible use cases involving boxing and unboxing.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Further Reading</span><br />
This <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx">page on the microsoft website</a> gives you some more ideas including some diagrams demonstrating what's happening on the stack and the heap at runtime.</p>
<p>Also, <a href="http://www.codeproject.com/KB/dotnet/6importentStepsDotNet.aspx">this article on the-code-project</a> has some nice examples and images, and a fuller explanation of value and reference types.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-1999120808695145532011-07-17T12:52:00.000+01:002012-02-15T21:24:43.734+00:00The Heap and the Stack<p>There are two locations in memory where the .NET Framework stores items during runtime - the <span style="font-weight:bold;">Heap</span> and the <span style="font-weight:bold;">Stack</span>. Understanding the difference between the two is one of those nuanced things that will pay dividends in all kinds of programming scenarios.</p>
<p>This article is a concise run-through of the most important concepts. For a broader explanation, check out <a href="http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx">this article on c-sharp corner</a> or <a href="http://www.codeproject.com/KB/dotnet/6importentStepsDotNet.aspx">this one on code-project (with nice diagrams)</a>.</p>
<span style="font-weight:bold;text-decoration:underline;">What are the Heap and the Stack?</span></p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCOkOXBBlwl_RvVmSbw6SogdUW6ja-BMQAsydGg-gH_nWcVfSeIMLIryRMfyaplQMy5crgtx3hCT1LQVCb_adirwPBgL32Cqq5kIdiP7oOl7Isynfp8MvwnJDWLKqztHMajis4OaMsluzH/s1600/998524_tranquility_4.jpg" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img alt="The stack" height="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCOkOXBBlwl_RvVmSbw6SogdUW6ja-BMQAsydGg-gH_nWcVfSeIMLIryRMfyaplQMy5crgtx3hCT1LQVCb_adirwPBgL32Cqq5kIdiP7oOl7Isynfp8MvwnJDWLKqztHMajis4OaMsluzH/s200/998524_tranquility_4.jpg" width="134" /></a></div>
<p><span style="font-weight:bold;font-style:italic">The Stack</span> is <span style="font-weight:bold;font-style:italic;">more or less</span> responsible for what's executing in our code.</p>
<p>There is a stack for every currently executing thread at runtime. Within each thread, each time a method is called, the method is added to the relevant stack for the thread. When the method is finished executing, it is removed from the stack. Therefore the stack is sequential, building upwards in one straight line, and at any given moment the CLR is only really interested in the items at the top of the stack.</p>
<p>Bear in mind that although it's easier to visualise it in terms of 'methods' being added to the stack, in reality the method <span style="font-style:italic;">itself</span> is not added to the stack - the <span style="font-style:italic;">resources</span> associated with the method are. This means arguments, internal method members, and the return value.</p>
<p>The stack is self-cleaning - when the method at the top of the stack finishes executing, the items associated with it have their resources freed.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfBr3_erzL5sa8jcSxeIiVAKJZOt-MgATKAq82NegmUu-mW7YvOdzeyc-duiFCybr4RfArOjmG_eCJ_WhHV6zPIXKJ3vi3YRqXMnFfBl-qdQJSQjCsJA10NdtSXijGsrcrrbLc3MMSYJwa/s1600/1005861_stack_of_baltic_amber_2.jpg" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img alt="The heap" height="133" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfBr3_erzL5sa8jcSxeIiVAKJZOt-MgATKAq82NegmUu-mW7YvOdzeyc-duiFCybr4RfArOjmG_eCJ_WhHV6zPIXKJ3vi3YRqXMnFfBl-qdQJSQjCsJA10NdtSXijGsrcrrbLc3MMSYJwa/s200/1005861_stack_of_baltic_amber_2.jpg" width="200" /></a></div>
<p><span style="font-weight:bold;font-style:italic">The Heap</span> is <span style="font-weight:bold;font-style:italic;">more or less</span> responsible for keeping track of our objects. Anything on the heap can be accessed at any time - it's like a heap of laundry, anything can go anyplace.</p>
<p>Items placed in the Heap can be referenced by pointers to the relevant memory location where they are stored. Unlike the Stack, the Heap has to worry about garbage collection.</p>
<p><span style="font-weight:bold;text-decoration:underline;">What can go on the Heap and the Stack?</span><br />
First we'll talk about the different resources that can be placed on the heap and the stack, and then we'll talk about which go where.</p>
<ol><li>Value Types</li>
<li>Reference Types, and</li>
<li>Pointers</li></ol>
<p>For a <a href="http://www.codeproject.com/KB/dotnet/6importentStepsDotNet.aspx#So which data types are ref type and value type">nice tree diagram go here</a>, or check out the lists:</p>
<p><span style="font-weight:bold;text-decoration:underline;">1. Value Types</span><br />
These are the types which are associated with System.ValueType (when <a href="http://jahyacode.blogspot.com/2011/07/boxing-and-unboxing.html">boxed</a> they derive from it).<br />
<ul class="compact">
<li><span style="font-weight:bold;">bool</span></li>
<li><span style="font-weight:bold;">byte</span></li>
<li><span style="font-weight:bold;">char</span></li>
<li><span style="font-weight:bold;">decimal</span></li>
<li><span style="font-weight:bold;">double</span></li>
<li><span style="font-weight:bold;">enum</span></li>
<li><span style="font-weight:bold;">float</span></li>
<li><span style="font-weight:bold;">int</span></li>
<li><span style="font-weight:bold;">long</span></li>
<li><span style="font-weight:bold;">sbyte</span></li>
<li><span style="font-weight:bold;">short</span></li>
<li><span style="font-weight:bold;">struct</span></li>
<li><span style="font-weight:bold;">uint</span></li>
<li><span style="font-weight:bold;">ulong</span></li>
<li><span style="font-weight:bold;">ushort</span></li>
</ul>
<p><span style="font-weight:bold;text-decoration:underline;">2. Reference Types</span><br />
<span style="font-family: 'Courier New'">System.Object</span>, and anything which derives from it. Think in terms of:</p>
<ul class="compact">
<li><span style="font-weight:bold;">class</span></li>
<li><span style="font-weight:bold;">interface</span></li>
<li><span style="font-weight:bold;">delegate</span></li>
<li><span style="font-weight:bold;">object</span></li>
<li><span style="font-weight:bold;">string</span></li>
</ul>
<p><span style="font-weight:bold;text-decoration:underline;">3. Pointers</span><br />
A Pointer is a chunk of space in memory that points to another space in memory - it's value is either a memory address or null. All Reference Types are accessed through pointers. We don't explicitly use Pointers, they are managed by the CLR, but they exist in memory as items in their own right.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Which Go Where?</span></p>
<ul class="compact">
<li><span style="font-weight:bold;font-style:italic;">Reference Types</span> always go on the <span style="font-weight:bold;font-style:italic;">Heap</span></li>
<li><span style="font-weight:bold;font-style:italic;">Value Types</span> and <span style="font-weight:bold;font-style:italic;">Pointers</span> go <span style="font-weight:bold;font-style:italic;">wherever they are declared</span></li>
</ul>
<p>Look at the example below:</p>
<pre class="brush: csharp;">public class MyClass
{
/* This variable is placed on the HEAP
inline with the containing reference-type,
i.e. the class, when it is instantiated */
public int MyClassMember;
/* These 3 variables are placed on the STACK
when the method is called, and removed
when execution completes */
public int MyMethod(int myArg)
{
int myLocal;
return myArg + myLocal;
}
}
</pre>
<p>Ofcourse, the class <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">MyClass</span> is a Reference Type and is placed on the Heap. The member variable <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">MyClassMember</span><span class="Apple-style-span" style="font-family: inherit;"> is declared <span style="font-weight:bold;font-style:italic;">inline with a reference type</span>, and therefore it is <span style="font-weight:bold;font-style:italic;">stored inline with that reference type</span> on the Heap.</span></p>
<p>The local variables <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">myArg</span>, <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">myLocal</span> and the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">return</span> variable are incidental to the object - they are not class members. They are <span style="font-weight:bold;font-style:italic;">not inline with a reference type</span> and therefore they are <span style="font-weight:bold;font-style:italic;">stored on the Stack</span>.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Reference Types and Pointers</span><br />
When a Reference Type such as an object is instantiated, the actual contents are stored on the Heap. Under the hood, the CLR also creates a Pointer, the contents of which are a reference to the object's memory location on the heap.</p>
<p>In this way, reference types can be easily addressed, and can be addressed by reference from more than one variable. But where is that pointer stored?</p>
<p>It's the same rules as with Value Types - it depends where the object is declared:</p>
<pre class="brush: csharp;">public class MyClass
{
/* This pointer is stored on the HEAP */
MyClass myMember = new MyClass();
public void MyMethod()
{
/* This pointer is stored on the STACK */
MyClass myLocal = new MyClass();
}
}
</pre>
<p>As noted above and discussed in the <a href="http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx">c-sharp-corner article</a>, the same object can be referenced by more than one Pointer. It's important to understand that object assignment operations in .NET actually assign the pointer value - the memory address of the object. They do not copy the object's value, only the pointer value.</p>
<p>Take a look at this example:</p>
<pre class="brush: csharp;">public int ReturnValue()
{
int x = new int();
x = 3;
int y = new int();
y = x;
y = 4;
return x;
}
//This returns 3
</pre>
<p>This is simple enough.</p>
<p>But what happens when we wrap the value types inside a reference type? The key is what happens when you use the <span style="font-style:italic;">assignment</span> operation on a reference type.</p>
<pre class="brush: csharp;">public class MyInt
{
public int Val;
}
public int ReturnValue2()
{
MyInt x = new MyInt();
x.Val = 3;
MyInt y = new MyInt();
y = x; /* y now points to the 'x' memory address */
y.Val = 4;
return x.Val;
}
//This returns 4
</pre>
<p>As you can see, the assignment assigns the <span style="font-weight:bold;">Pointer value</span> - the memory address of the assigned object - <span style="font-style:italic;">not</span> the value of the object or the object's members. As a consequence, the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">new MyInt()</span> that was created and initially assigned to <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">y</span>, is now orphaned.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Dynamic vs. Static Memory</span><br />
So the Stack and the Heap have different structures, behaviours and reasons for being. One is sequential and related to the current method, the other is tree-based, messy (requires GC) and random-access.</p>
<p>But why not just use one memory store - why separate them at all? The answer is to separate static memory from dynamic memory.</p>
<ul><li>The Stack is <span style="font-weight:bold;font-style:italic;">static</span> - once a chunk of memory is allocated for a variable, it's size cannot and will not change. Each unit is <span style="font-weight:bold;font-style:italic;">small</span> and of <span style="font-weight:bold;font-style:italic;">fixed size</span>.</li>
<li>The Heap is <span style="font-weight:bold;font-style:italic;">dynamic</span> - reference types encapsulate value types and other reference types. Each unit is <span style="font-weight:bold;font-style:italic;">larger</span> and of <span style="font-weight:bold;font-style:italic;">variable size</span>.</li>
</ul>
<p>These differences mean that the way space is allocated and consumed is very different. It's outside the scope of this article, but you can do more reading by looking up <a href="http://en.wikipedia.org/wiki/Dynamic_memory_allocation">dynamic memory allocation</a> and <a href="http://en.wikipedia.org/wiki/Static_memory_allocation">static memory allocation</a>.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-82441547210205583012011-07-15T12:36:00.001+01:002012-02-15T19:34:22.936+00:00The 'Finally' in Try / Catch<p>When exactly is the <span style="font-weight:bold;font-style:italic;">finally</span> block called in <span style="font-weight:bold;font-style:italic;">try/catch</span> statements? If you know, you can correctly predict what gets printed here:</p>
<pre class="brush: csharp;">static void Main(string[] args)
{
AssignToInt(null);
AssignToInt(new object());
AssignToInt(1);
}
public static bool AssignToInt(object o)
{
try
{
int i = (int)o;
Console.WriteLine("{0} assigned OK", i);
return true;
}
catch (NullReferenceException)
{
Console.WriteLine("NullReferenceException");
return false;
}
catch (InvalidCastException)
{
Console.WriteLine("InvalidCastException");
return false;
}
finally
{
Console.WriteLine("Finally...");
}
}
</pre>
<p>The <span style="font-weight:bold;font-style:italic;">finally</span> block is always called after any execution within a <span style="font-weight:bold;font-style:italic;">try/catch</span> block - regardless of whether an exception was caught or not. Even when a <span style="font-weight:bold;font-style:italic;">return</span> command is found inside a <span style="font-weight:bold;font-style:italic;">try</span> or <span style="font-weight:bold;font-style:italic;">catch</span> block, the CLR will execute the <span style="font-weight:bold;font-style:italic;">finally</span> block before executing the <span style="font-weight:bold;font-style:italic;">return</span> command.</p>
<p>The best example of why you would use it is to clean up and close any resources you have left open. Lets say you open a <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">FileStream</span> in your <span style="font-weight:bold;font-style:italic;">try</span> block - it will need to be closed whether or not an exception occurs. The <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">FileStream.Close()</span> method call should be made inside the <span style="font-weight:bold;font-style:italic;">finally</span> block.</p>
<p>Therefore the output you get from running the code is:</p>
<pre class="brush: plain;">NullReferenceException
Finally...
InvalidCastException
Finally...
1 assigned OK
Finally...
</pre>
<p>Further reading:</p>
<ul><li><a href="http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=VS.100).aspx">try-finally (C# Reference)</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/0yd65esw(v=VS.100).aspx">try-catch (C# Reference)</a></li></ul>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-19339520821260578712011-07-11T01:24:00.006+01:002012-02-15T21:26:02.830+00:00Injecting Controller Dependencies in .NET MVC with StructureMap<p>When you are creating an MVC application, your Controllers will by default be created without any dependencies. As soon as you try to <a href="http://jahyacode.blogspot.com/2011/07/ioc-containers-and-dependency-injection.html">inject a dependency</a> into your Controller's constructor...</p>
<pre class="brush: csharp;">public EbookController(IEbookRepository ebookRepository)
{
this.ebookRepository = ebookRepository;
}
</pre>
<p>You will get an error message something like this:</p>
<pre class="brush: plain;">No parameterless constructor defined for this object.
</pre>
<p>This is because the MVC framework internally uses a factory to generate Controller objects based on your classes. When the factory tries to instantiate your class, it doesn't have an implementation that handles your dependency.</p>
<p>You can override the default factory with one that uses your preferred Dependency Injection solution (in this example I have used StructureMap), and therefore will take over the controller instantiation and resolve any dependencies on your behalf. You need to do three things:</p>
<ol><li>Bootstrap your dependencies</li>
<li>Override the default Controller factory</li>
<li>Tell your application to use your Bootstrapper and overriden factory</li>
</ol>
<p>I'm going to demonstrate using the example I've already started above: an Ebook controller depending on an EbookRepository.</p>
<p><span style="font-weight:bold;">1. Bootstrap your dependencies</span></p>
<pre class="brush: csharp;">using StructureMap;
public static class Bootstrapper
{
public static void Bootstrap()
{
ObjectFactory.Initialize(
x => x.For<IEbookRepository>()
.Use<EbookRepository>());
}
}
</pre>
<p><span style="font-weight:bold;">2. Create a new class to override the default Controller factory with one that uses StructureMap to instantiate Controllers:</span></p>
<pre class="brush: csharp;">public class StructureMapControllerFactory
: DefaultControllerFactory
{
protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
return base.GetControllerInstance(
requestContext, controllerType);
return ObjectFactory.GetInstance(controllerType)
as Controller;
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(
ObjectFactory.WhatDoIHave());
throw;
}
}
}
</pre>
<p><span style="font-weight:bold;">3. Tell your application to use the Bootstrapper and overriden factory, by editing Global.asax.cs:</span></p>
<pre class="brush: csharp;">protected void Application_Start()
{
//Any other commands
RegisterRoutes(RouteTable.Routes);
Bootstrapper.Bootstrap();
ControllerBuilder.Current.SetControllerFactory(
new StructureMapControllerFactory());
}
</pre>
<p>That's it!</p>
<p>The source of the technique used in this article can be found here on <a href="http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuremap.aspx">Shiju Varghese's blog</a>.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-20897824862474978372011-07-06T11:51:00.002+01:002012-02-15T21:23:55.969+00:00Introduction to IoC Containers and Dependency Injection using StructureMap<p>In a previous article, I discussed the nature of the IoC principle as a separate entity from Dependency Injection. In this article I want to explain IoC <span style="font-weight:bold;font-style:italic;">Containers</span>, and show how these can be used alongside Dependency Injection to create clean, testable, scaleable code, via decoupled architectures.</p>
<p>But before I explain what IoC Containers and DI are, let's talk about <span style="font-weight:bold;font-style:italic;">why</span> you would want them.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Decoupled Architectures</span><br />
In <a href="http://jahyacode.blogspot.com/2011/06/inversion-of-control.html">my IoC post</a>, we looked at an example in which we handed over control to a GUI framework. I'm going to continue with that example here, and have included a cut-down version of the class in the codeblock below.</p>
<p><span style="font-style:italic;">(I've renamed the class <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GuiFramework</span> to <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GraphicUserInterface</span>, because the original naming was only intended to highlight the differences between libraries and frameworks.)</span></p>
<pre class="brush: csharp">public class BusinessLogic {
private GraphicUserInterface gui =
new GraphicUserInterface();
public void Run(){
gui.NamePrompt("Please enter your name");
gui.AddNameChangedHandler(OnNameChanged);
}
}
public class Program() {
public static void Main() {
BusinessLogic busLogic = new BusinessLogic();
busLogic.Run();
}
}
</pre>
<p>One of the main benefits of the IoC approach is that we have a separation of concerns. The <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GraphicUserInterface</span> class handles all of the stuff to do with GUIs. The <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BusinessLogic</span> class handles all of the stuff to do with business logic.</p>
<p>The business logic class manipulates the GUI class in order to implement business logic functionality, but it doesn't know anything about how, when or where the GUI does it's job. It simply uses the GUI's services and that's it.</p>
<p>So our architecture is <span style="font-style:italic;">almost</span> <a href="http://en.wikipedia.org/wiki/Decoupling#Software_Development">decoupled</a>. The only thing that still couples our architecture is that the business logic class <span style="font-style:italic;">directly instantiates</span> an instance of the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GraphicUserInterface</span> class. With this setup we say that the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BusinessLogic</span> class <span style="font-weight:bold;font-style:italic;">depends on</span> the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GraphicUserInterface</span> class, or that the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GraphicUserInterface</span> class is <span style="font-weight:bold;font-style:italic;">a dependency of</span> the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BusinessLogic</span> class.</p>
<p>If we can properly decouple these components, then they become like 'plugins':</p>
<ul><li>entirely independent of each other</li>
<li>entirely interchangeable with other components that provide the same or similar services</li>
<li><span style="font-style:italic;">but still</span> entirely inter-operable with each other - any plugged in component will work without adapting or making config changes to other components in the system - they will just 'plug and play'</li>
</ul>
<p><span style="font-weight:bold;text-decoration:underline;">Why That's Good</span><br />
If you've worked with enterprise-level applications, or any application with more than a trivial number of components, it will be clear why this is positive. Here are a few important reasons:</p>
<ul>
<li><span style="font-weight:bold;">Requirements changes</span> - It is practically inevitable during any project that requirements will change. Decoupled architectures allow you to replace components in an existing system without having to adapt and recompile other components to match.</li>
<li><span style="font-weight:bold;">Unit testing</span> - A decoupled component can be tested in isolation from it's dependencies, by <a href="http://en.wikipedia.org/wiki/Mock_object">mocking</a> the dependencies. In this way unit tests can be run continuously throughout the project - and it becomes easy to have a development process in which your software <span style="font-style:italic;">always</span> in a testable state. This is a huge advantage because it provides certain guarantees and confidence throughout. It also paves the way for TDD, which i'll discuss in another post.</li>
<li><span style="font-weight:bold;">Separation of concerns</span> - it enforces an architecture where responsibilities are meted out to components neatly. This is nicer to work with, but it also has the practical benefit that if you bring a new developer onto the project, they can start work very quickly, and with a minimum of knowledge about the system. For example, if they are working on a data-access abstraction they need not ever have seen the UI - the responsibilities that this developer has will end at the boundary of the data-access abstraction, or whatever other component they are working on.</li>
</ul>
<p>So let's see what that really means, by decoupling the example code, step by step.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Step 1: Use an Interface</span><br />
Instead of referring to the implementation class directly by name, we'll use an <a href="http://www.youtube.com/watch?v=oHKec9XFZdc">interface</a>. I've commented out the old declaration and added a new one.</p>
<pre class="brush: csharp;">public class BusinessLogic {
//private GraphicUserInterface gui = new
// GraphicUserInterface();
private IUserInterface userInterface;
public void Run(){
gui.NamePrompt("Please enter your name");
gui.AddNameChangedHandler(OnNameChanged);
}
}
public class Program() {
public static void Main() {
BusinessLogic busLogic = new BusinessLogic();
busLogic.Run();
}
}
</pre>
<p>First, notice the rename. The interface is called <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">IUserInterface</span> - not <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">IGraphicUserInterface</span>. This is important, because our business logic class doesn't need to know <span style="font-style:italic;">what kind</span> of implementation it is dealing with. All it needs is the services of some kind of user interface, in order to prompt and accept a user's name. Exactly what kind of UI is unimportant - it could be a GUI or a web form or a speech recognition component - the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BusinessLogic</span> class doesn't care.</p>
<p>All the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BusinessLogic</span> class wants to know is that the class is capable of providing the services it requires. Implementation classes can indicate this capability by implementing the relevant interface - in this case <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">IUserInterface</span>.</p>
<p>Second, notice that we are not instantiating our new private <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">userInterface</span> member, only declaring it. Ofcourse if our application is going to work, the member will need to be instantiated - but how?</p>
<p><span style="font-weight:bold;text-decoration:underline;">Step 2: Use Dependency Injection</span><br />
We 'inject' a pre-instantiated object into our class:</p>
<pre class="brush: csharp; highlight: [5,6,7]">public class BusinessLogic {
private IUserInterface userInterface;
public void BusinessLogic(IUserInterface aUserInterface){
this.userInterface = aUserInterface;
}
public void Run(){
gui.NamePrompt("Please enter your name");
gui.AddNameChangedHandler(OnNameChanged);
}
}
public class Program() {
public static void Main() {
BusinessLogic busLogic = new BusinessLogic();
busLogic.Run();
}
}
</pre>
<p>The approach used above is called Constructor Injection. Alternatively you could use Setter Injection, which is where you inject a dependency via a method (a setter method). In either case, the dependency is instantiated outside of the dependent class and injected in.</p>
<p>We'll use Constructor Injection in this example, and you'll see why a little later on.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Step 3: Set up an IoC Container</span><br />
So where is the object instantiated? We need an IoC container.</p>
<p>These 'contain' the mappings required to wire up our dependencies. You'll hear them called DI containers too, but it means the same thing (there's a brief discussion on terminology at the bottom of this article).</p>
<p>I'm going to use <a href="http://structuremap.net/structuremap/">StructureMap</a> as an example because it's easy to use and has an intuitive syntax. First, we create a <a href="http://en.wikipedia.org/wiki/Bootstrapping_(computing)">Bootstrapper</a>. This becomes the single location within our program where concrete types are mapped to interfaces:</p>
<pre class="brush: csharp;">using StructureMap;
public static class Bootstrapper
{
public static void Bootstrap()
{
ObjectFactory.Initialize(x =>
{
x.For<IUserInterface>().Use<GraphicUserInterface>();
x.For<IBusinessLogic>().Use<BusinessLogic>();
});
}
}
</pre>
<p>StructureMap is one of a number of IoC Containers for .NET. Regardless of which container you use, you would expect to see all mappings declared inside a Bootstrapper, and the Bootstrapper to be created during initialisation (Global.asax for web applications, or the main routine for a desktop application).</p>
<p><span style="font-weight:bold;text-decoration:underline;">StructureMap's Object Factory</span><br />
The <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ObjectFactory</span> mentioned in the codeblock above is a static wrapper for the StructureMap container. Whenever you use the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ObjectFactory</span> static class anywhere in your code, you are always referencing the same singleton container (it is possible to use more than one container object but this is not standard).</p>
<p>Once you have bootstrapped your mappings, you can use the static <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ObjectFactory</span> reference anywhere in your code to instantiate an object by describing the service you require (passing in an interface name):</p>
<pre class="brush: csharp">public class Program {
public static void Main()
{
Bootstrapper.Bootstrap();
var userInterface =
ObjectFactory.GetInstance<IUserInterface>();
}
}
</pre>
<p>In the above example, the implicitly-typed var <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">userInterface</span> will now hold an instance of the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GraphicUserInterface</span> class.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Auto-Wiring</span><br />
You might think at this stage, great - now we can just create a <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BusinessLogic</span> object and send the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">userInterface</span> object as an argument. But it's simpler than that, and this is one good reason to use Constructor Injection for your dependencies.</p>
<p>If you decouple all of your components, including (in this case) the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">BusinessLogic</span> class, then StructureMap will figure out your dependencies for you using <a href="http://structuremap.net/structuremap/AutoWiring.htm">Auto-Wiring</a>:</p>
<pre class="brush: csharp;">public class Program {
public static void Main()
{
Bootstrapper.Bootstrap();
//var userInterface =
// ObjectFactory.GetInstance<IUserInterface>();
var businessLogic =
ObjectFactory.GetInstance<IBusinessLogic>();
businessLogic.Run();
}
}
</pre>
<p>Notice that I have commented out the top line. Auto-wiring basically means that <span style="font-style:italic;">unless you tell the bootstrapper differently</span>, any time you instantiate an object with dependencies StructureMap will create an instance of the dependency and inject it for you.</p>
<p><span style="font-weight:bold;text-decoration:underline;">More With StructureMap</span><br />
There's a lot more you can do with StructureMap, or any IoC Container. For example, you can wire up a singleton so that all dependencies resolve to a single instance:</p>
<pre class="brush: csharp">x => x.For<IFoo>().Singleton().Use<Foo>()
</pre>
<p>You can use 'open generics', so that you can decouple your genericised classes. For example you might have a class <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Repository</span> which could handle <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Book</span> objects or <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Magazine</span> objects, i.e. <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Repository<Book></span> or <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Repository<Magazine></span>. Using this syntax, you can declare mappings that are generics-agnostic:</p>
<pre class="brush: csharp">x => x.For(typeof (IRepository<>)).Use(typeof (Repository<>))
</pre>
<p>You can specify an instance to use for particular constructor arguments. For example, if your class <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">Foo</span> is constructed with a string called <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">argName</span>:</p>
<pre class="brush: csharp">x.For<IFoo>().Use<Foo>().Ctor<string>("argName").Is("arg");
//or
x.For<IFoo>().Use<Foo>().Ctor<string>("argName").
.EqualToAppSetting("app-setting-id");
</pre>
<p>This is ofcourse a whirlwind tour. Here are a few recommended links if you want to run off and figure out StructureMap now:</p>
<ul style="text-align: left;"><li><a href="http://www.theabsentmindedcoder.com/2010/05/structure-map-basics-26.html">http://www.theabsentmindedcoder.com/2010/05/structure-map-basics-26.html</a> (check the link on the right for more StructureMap posts)</li>
<li><a href="http://structuremap.net/structuremap/QuickStart.htm">http://structuremap.net/structuremap/QuickStart.htm</a> (Check the left-nav for lots of links)</li>
<li><a href="http://codebetter.com/jeremymiller/2008/12/01/a-gentle-quickstart-for-structuremap-2-5/">http://codebetter.com/jeremymiller/2008/12/01/a-gentle-quickstart-for-structuremap-2-5/</a></li>
</ul>
<p><span style="font-weight:bold;text-decoration:underline;">When To Use Which Approach</span><br />
There will be times when Constructor Injection is not appropriate, and you need fine-grained control of object instantiation during program execution. In these circumstances you can use the <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ObjectFactory</span> object as we did in the examples earlier:</p>
<pre class="brush: csharp">var newFoo = ObjectFactory.GetInstance<IFoo>()
</pre>
<p>This gives you the same type of control over when things are instantiated as you get with ordinary coupled code. But it should be clear that the easiest approach whenever possible is to use Constructor Injection and let Auto-Wiring do the work for you. When this isn't possible move to Setter Injection, and when that isn't possible, use <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ObjectFactory</span> to create an instance.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Decoupling Your Container</span><br />
Ofcourse, <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">ObjectFactory</span> is a class defined within the StructureMap namespace. If you pepper it around your code (i.e. using <span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">GetInstance</span>), then you are coupling your code to StructureMap. Some people prefer to ensure full decoupling from IoC Containers by housing Container references within custom object factories, and accessing those factories via an interface.</p>
<p>In another post I will discuss Autofac, a google code project and DI/IoC Container. Autofac, unlike StructureMap, ensures the container is fully decoupled by design. Instead of using a generic static Object Factory, Autofac allows you to create and inject custom object factories for use in your code.</p>
<p><span style="font-weight:bold;text-decoration:underline;">The IoC/DI Name</span><br />
You can see <a href="http://martinfowler.com/articles/injection.html#InversionOfControl">Martin Fowler here discussing the evolution of the name</a>. Three different techniques / approaches have merged together to form a pattern, and so we have this composite name - IoC / DI / Container.</p>
<p>You can see what I mean if you consider that it's perfectly possible to use Dependency Injection without inverting control, or decoupling via interfaces:</p>
<pre class="brush: csharp;">public class BusinessLogic {
private SomeLibrary someLibrary;
public void BusinessLogic(SomeLibrary someLib){
this.someLibrary = someLib;
}
}
</pre>
<p>It's also possible to invert control without using DI, or to use containers without DI or IoC. However these approaches have grown to compliment each other and have become a mainstream approach to creating clean, testable, scaleable application architecures.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-34255815433126180202011-06-22T15:39:00.001+01:002012-02-15T21:42:19.404+00:00What is the Inversion of Control Principle?<p>Inversion of Control and Dependency Injection, IoC and DI. You hear them so often together in day-to-day lingo that it has become hard to separate them.</p>
<p>But they're not the same thing! DI is a specific form of the abstract IoC principle. So in this article I want to discuss and briefly explain IoC without going into DI. In another post I discuss <a href="http://jahyacode.blogspot.com/2011/07/ioc-containers-and-dependency-injection.html">IoC <i>Containers</i>, DI, and how to use the IoC/DI pattern</a> to create clean, testable code.</p>
<p>But for now, what is IoC? To explain i'm going to <span style="font-style: italic">very briefly</span> jump back to basics - to explain what it is <span style="font-style:italic;">not</span>.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Traditional Control of Flow</span><br />
When I learned to program console applications, I learned to write functions (this is C-style pseudocode):</p>
<pre class="brush: plain;">void printName(string name){
print(name);
}
string readName(){
print("What is your name?");
string name = readLine();
return name;
}
</pre>
<p>... and to execute those functions from an execution-path entry point, i.e.:</p>
<pre class="brush: plain;">void main(){
string name = readName();
printName(name);
}
</pre>
<p>If you expand much further from this simple example it quickly becomes clear that there is a central 'trunk' of execution (i.e. <span style="font-family:'Courier New'">main()</span>). This central trunk is flanked by large amounts of supporting code, in the form of functions (which in turn call more functions). All of the power to control program flow resides in the central trunk.</p>
<p>When we move on to OO, the functions became wrapped in classes, but the principle of centralised program flow control remained.</p>
<pre class="brush: csharp;">public class BusinessLogic {
private string name;
public void Run(){
name = this.ReadName();
Console.WriteLine(name);
}
private string ReadName(){
Console.WriteLine("Please enter your name\n");
name = Console.ReadLine();
}
}
public class Program() {
public static void Main() {
BusinessLogic busLogic = new BusinessLogic();
busLogic.Run();
}
}
</pre>
<p>Ofcourse, with OO you end up with many more layers - your main Program class will instantiate objects and those objects will instantiate objects. But what we ended up with was a cluster of classes in the middle that control program flow, and you can draw a single line of execution through them. The classes in this cluster hand off tasks to a variety of library-style components (other classes, or 3rd-party libraries):</p>
<pre class="brush: csharp; highlight: [4,8,17,18,19,20];">public class BusinessLogic {
private string name;
private CaseLibrary lib = new CaseLibrary();
public void Run(){
name = this.ReadName();
name = this.UpperCase(name);
this.PrintName();
}
private string ReadName(){
Console.WriteLine("Please enter your name\n");
name = Console.ReadLine();
}
private string UpperCase(string name){
name = lib.UpperCase(name);
Console.WriteLine(name);
}
}
</pre>
<p>But libraries have very little freedom to control program flow. They can do what they like in responding to your requests, but they are little more than calculators, waiting for your application to give them some values and a specific task to do. They do the task and then return flow control to your central trunk.</p>
<p><span style="font-weight:bold;text-decoration:underline;">So What is Inversion of Control?</span><br />
IoC is all about handing control of program flow to somewhere other than the central trunk. It's a mainstream concept and the central principle of many event-driven architectures. IoC is commonly found in GUI applications, so in this example we'll use a framework to implement a GUI. This will mean handing over control to the (fictional) GuiFramework:</p>
<pre class="brush: csharp; highlight: [4,7,8,11,12,13,14];">public class BusinessLogic {
private string name;
private GuiFramework gui = new GuiFramework();
public void Run(){
gui.NamePrompt("Please enter your name");
gui.AddNameChangedHandler(OnNameChanged);
}
public void OnNameChanged(object sender, NameEventArgs e){
name = e.Name;
Console.WriteLine(name);
}
}
</pre>
<p>Note that our application logic is still able to react to events in the GUI. This is done by assigning an EventHandler to the relevant framework object as a listener for NameChanged events. We hand over flow control to the framework, but we are able to insert our own code to respond to certain specific events. In this way we can customise the framework, but control is clearly inverted. Hence, Inversion of Control.</p>
<p><span style="font-weight:bold;text-decoration:underline;">The Hollywood Principle</span><br />
It's the oft-quoted phrase of IoC: "Don't call us, we'll call you." Once you hand over control to another component, you don't need to badger it with requests, or re-assume control. You just set up a listener and wait for the framework to call you back. You retain just enough code to handle your business logic, no more, no less.</p>
<p>So when using IoC with a number of framework-style components, control of the program is spread, and each component takes care of it's own responsibilities. Which is good, because a GUI framework knows more about how to render a GUI than does my application logic.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Frameworks vs. Libraries</span><br />
As Martin Fowler points out, the IoC principle gives us a clear way to distinguish between libraries and frameworks:</p>
<blockquote>"Inversion of Control is a key part of what makes a framework different to a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client. A framework embodies some abstract design, with more behavior built in. In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points."</blockquote>
<p>For more info, see Martin Fowler's article on <a href="http://martinfowler.com/bliki/InversionOfControl.html">Inversion of Control</a>.</p>
<p>Or you can <a href="http://jahyacode.blogspot.com/2011/07/ioc-containers-and-dependency-injection.html">jump ahead to my article on IoC/DI Containers</a>, and learn about the IoC/DI pattern.</p>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0tag:blogger.com,1999:blog-3518945678469852273.post-59567394209181424202011-06-21T14:05:00.001+01:002012-02-15T22:06:43.692+00:00The Role of ViewState in WebForms Applications<p>In the last couple of years I've been working extensively with the .NET MVC framework. Before that, all my .NET coding was in Webforms. I never liked Webforms, and I immediately liked MVC. Now seems like a good moment to reflect on some of the features of each and evaluate why that is.</p>
<p>In this article I want to touch on what the Webforms ViewState is. I'll talk about how it works, and some of the issues it raises.</p>
<p><span style="font-weight:bold;text-decoration:underline;">The Framework is Editing My HTML</span><br />
Back when I worked with Webforms, I worked in an agency in which W3C-compliant HTML standards and accessibility were key selling points. So one of the main things that I disliked about Webforms was that it seemed so intent on interfering with my frontend code. Particularly in .NET 1.1 the WebControls spat out such untidy, non-standards-compliant HTML.</p>
<p>Microsoft revised this and the HTML became standards-compliant for .NET 2. But I still didn't like the way it wrote HTML for me, as I was generally handed a HTML template that I was to stick to religiously for accessibility reasons. We found workarounds such as doing all WebControl work in the codebehind, but as we shall see, this approach has problems of it's own.</p>
<p>On a more personal note, I was never happy either with the big, ugly _VIEWSTATE string in the source. The point for me was, the framework shouldn't be editing my HTML, that isn't it's concern. It's concern is helping me generate whatever HTML I want to generate for each request.</p>
<p>I'll touch more on some of the problems at the bottom of this article, but for now I want to discuss mechanics. What is the Webforms Viewstate for? And how does it work?</p>
<p><span style="font-weight:bold;text-decoration:underline;">Duality of a Webforms Page</span><br />
All Webforms developers know that there is a 1:1 relationship between a requested resource (a URL) and a processing resource (a Webforms 'page'). Each 'page' is composed of two elements - a codebehind (derived from System.Web.UI.Page), and an ASPX page containing server-side code (such as WebControls).</p>
<p>But although there are two elements for us as a developer, there is only one element as far as the .NET engine is concerned. Each time you edit an ASPX page it is converted into an auto-generated class which logically compliments the codebehind. As such you can make the same declarations in the codebehind or the ASPX page. The ASPX page is just a neat abstraction useful for layout and initialisation purposes, and friendly to people used to frontend HTML.</p>
<p>Any WebControls declared in the ASPX page are converted into their codebehind equivalents and compiled into the DLLs like everything else. Attributes of the WebControls are converted into value assignment operations (and conversions occur if the member variables are not typed as strings). The HTML portions of the ASPX page are converted into string literals, so the idea that you are editing a 'flat page' is illusory.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Request-Handling in Webforms</span><br />
When a page is requested from IIS over HTTP, the request is handed to the ASP.NET engine (aspnet_isapi.dll). Internally the request passes through several HTTP modules and arrives at the HTTPHandler (below), invoking the ProcessRequest() method. This method kicks off the following sequence:</p>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1Csw22gIMip9CmOM_4L-ezA_pt84bSKA5o-NTjnTix7TXNR9VCG6KeyqyzJSfC_yN3UswoQkj1Vvy-87bJJmat2ZAAysuHu6DpepikFCRYcMPoZn_kyvL-V8vireAyEqtWVgrbzkBdar7/s1600/IC152667.gif" style="margin-left: auto; margin-right: auto;"><img alt="Webforms request handling pipeline" height="256" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1Csw22gIMip9CmOM_4L-ezA_pt84bSKA5o-NTjnTix7TXNR9VCG6KeyqyzJSfC_yN3UswoQkj1Vvy-87bJJmat2ZAAysuHu6DpepikFCRYcMPoZn_kyvL-V8vireAyEqtWVgrbzkBdar7/s320/IC152667.gif" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">The Webforms HTTP request handling pipeline</td></tr>
</tbody></table>Notice the clear distinction between PostbackData and ViewState. Note that the loading of both only occurs on PostBack.</p>
<p><span style="font-weight:bold;text-decoration:underline;">PostbackData vs. ViewState</span><br />
PostbackData is a collection representing all form-field data from the HTTP POST header (all but one - the hidden _VIEWSTATE field). If you are using standard-issue WebControls such as the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx">TextBox</a> class, then your controls will have rendered the HTML form elements that generated this PostbackData. Typically there is one PostbackData item in the collection per rendered WebControl, and this item will correspond with a designated property of the WebControl. In the case of TextBox, the property <span style="font-style:italic;">TextBox.Text</span> corresponds to the <span style="font-style:italic;">value</span> attribute of a text input field.</p>
<pre class="brush:xml">
<asp:TextBox Text="somevalue" runat="server" />
<input type="text" value="somevalue" ... />
</pre>
<p>ViewState is a collection representing the <span style="font-style:italic;">dynamically assigned</span> properties of each WebControl <span style="font-style:italic;">other than</span> those designated to correspond with PostbackData.</p>
<p>I'll explain that sentence in more detail. Which properties of a WebControl is ViewState interested in storing? The answer is all properties <span style="font-style:italic;">except</span> those associated with it's <span style="font-style:italic;">value</span>. Value-related properties are covered by PostbackData because they are already included in the HTTP POST specification. Microsoft wanted some way to persist properties over HTTP requests which are not covered by the HTTP POST specification, and so they invented ViewState.</p>
<p>But there's more. If every property of every WebControl were to be serialised and deserialised on every request there would be a huge performance hit. As <a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx">this article</a> aptly points out, only WebControl properties which have been <span style="font-style:italic;">dynamically assigned</span> during execution (i.e. marked as 'dirty', i.e. changed since initialisation with a default) are included in the ViewState.</p>
<pre class="brush:xml">
<asp:TextBox ID="myTextBox" CssClass="class1" .. />
</pre>
<p>In other words, if you declare a <span style="font-style:italic;">CssClass</span> attribute in your ASPX page, the class which is auto-generated from it will mirror that attribute into an assignment. This assignment will take place during the 'Initialization' phase of the pipeline, which if you check the diagram is the first thing that is done in response to a request.</p>
<p>Now, let's assume that you don't make any changes during the Load phase (i.e. in Page_Load). When the _VIEWSTATE string is generated, the assigned value will not be included because it has not been marked as dirty. Several page requests could occur and the value would not need to be persisted because each time the TextBox is initialised the <span style="font-style:italic;">CssClass</span> will gain it's default value.</p>
<pre class="brush:csharp">
myTextBox.CssClass = "class2";
</pre>
<p>Now, perhaps during your Page_Load event, inside some conditional statement you assign the <span style="font-style:italic;">CssClass</span> property a new value of "class2". Now when execution reaches the SaveViewState part of the pipeline, it will discover that the <span style="font-style:italic;">CssClass</span> property has been marked as dirty. It's name and value will be serialised into the _VIEWSTATE string, and when the postback occurs, LoadViewState will 'remember' the change.</p>
<p>It should start to become clear now why it's a problem doing all your WebControl work in the codebehind. All of your values will always be dynamically assigned, and are therefore all persisted via ViewState. This increases page size, and reduces performance considerably.</p>
<p><span style="font-weight:bold;text-decoration:underline;">One ViewState Per Control</span><br />
In case you're interested in how the memory state maps to the serialisation process, it's worth noting how every WebControl has it's own ViewState collection. I'll explain.</p>
<p>When the ASPX-generated class is created, each control is placed in a hierarchy mirroring the hierarchy defined in the ASPX page. This is usually a top-level Page object, containing 3 x second-level objects (a string literal containing some HTML, a Form object and another string literal with the rest of the HTML). The Form object then contains a series of WebControls, each of which may contain their own children and so on.</p>
<p>In order to serialise the _VIEWSTATE string, this hierarchy is traversed so that the resulting encoded string mirrors the hierarchy. What you see in the encoded _VIEWSTATE is the result - if you look at the middle of the encoded string you are probably looking at properties of a low-level child control. If you look at either edge you are probably looking at higher-level controls.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Making Things UnRESTful</span><br />
So the ViewState isn't about remembering form field values - that's the job of PostbackData. ViewState is actually about persisting the state of controls over several PostBack requests. It's as though Microsoft said: "Ok, you handle the persistence of your data between HTTP requests, and we'll handle the persistence of the controls. You set the properties of those controls as and when you like, we'll make sure they stay set."</p>
<p>Which is kind of cool in a way, after all Webforms runs on an event model. If Microsoft didn't do this, you as a developer would have to include a procedure during all of your event handing functions to check and ensure all of the WebControls were correctly set up based on the current memory state of your application. It would be a performance hit, and a pain to create, set up and test.</p>
<p>But looking at it from another angle, it's forcing a square peg into a round hole. It's forcing an Event-driven model onto a RESTful architecture. The web, and HTTP are all based on the idea of <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a>. If, three PostBack's into a session, a user copies a URL and sends it to a friend, it is very unlikely that the friend will see the same page that was sent.</p>
<p>It is true that even if you use a RESTful programming architecture (such as Microsoft MVC) you may get the same problem, but it is much easier to code meaningful state-based views in RESTful architectures. Only the value data is lost when the URL copied, and generally that is the part that you don't <i>intend </i>to send anyway when you copy a URL.</p>
<p>I'll go more deeply into these differences in another post, but for now it's enough to point out the mismatch between an event-driven model and REST, and to think of ViewState as a kind of compromise between the two.</p>
<p><span style="font-weight:bold;text-decoration:underline;">Further Reading</span><br />
These articles made for great reading in helping to assemble this post:</p>
<ul><li><a href="http://msdn.microsoft.com/en-us/library/ms972976.aspx">The Microsoft explanation of ASP.NET Viewstate</a></li>
<li><a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx">A very readable article discussing Viewstate in detail</a></li></ul>Anonymoushttp://www.blogger.com/profile/18128476386123092269noreply@blogger.com0