<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tore Vestues blogs &#187; C#</title>
	<atom:link href="http://tore.vestues.no/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://tore.vestues.no</link>
	<description>On a quest for the silver bullet..</description>
	<lastBuildDate>Mon, 26 Jul 2010 12:22:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The Microsoft MVP Award</title>
		<link>http://tore.vestues.no/2010/07/26/the-microsoft-mvp-award/</link>
		<comments>http://tore.vestues.no/2010/07/26/the-microsoft-mvp-award/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 12:20:35 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Talks]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/?p=113</guid>
		<description><![CDATA[I am proud to announce that I have received the Microsoft MVP Award in C#, for my &#8220;exceptional contributions and commitment to technical communities worldwide&#8221;.
That means I am a C# MVP, and I am very proud of it!
I feel it is important for me to contribute to, and learn from, the technical communities around the [...]]]></description>
			<content:encoded><![CDATA[<p>I am proud to announce that I have received the Microsoft MVP Award in C#, for my &#8220;exceptional contributions and commitment to technical communities worldwide&#8221;.</p>
<p>That means I am a C# MVP, and I am very proud of it!</p>
<p>I feel it is important for me to contribute to, and learn from, the technical communities around the world, and therefore I&#8217;m honored by receiving this award for my contributions. I will do my best to continue to contribute to the communities in the time to come, and I know I will learn a lot from them.</p>
<p>- Tore Vestues</p>
<p><img src="http://vestues.no/tore/wp-content/MVP_Horizontal_FullColor_resized_500x.png" alt="MVP" title="MVP" width="500" height="202" class="size-full wp-image-114" /></p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2010/07/26/the-microsoft-mvp-award/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Reflection and performance</title>
		<link>http://tore.vestues.no/2010/07/01/reflection-and-performance/</link>
		<comments>http://tore.vestues.no/2010/07/01/reflection-and-performance/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 11:07:45 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[Bits and bytes]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/?p=85</guid>
		<description><![CDATA[The open source framework Glue that I&#8217;ve created, use a lot of reflection to invoke members on objects. This has sparked my interest in exploring the use of reflection in respect to performance. A colleague of mine, Åsmund Eldhuset, and I set aside an evening for a geeknight to get to the bottom of this, [...]]]></description>
			<content:encoded><![CDATA[<p>The open source framework <a href="http://glue.codeplex.com">Glue</a> that I&#8217;ve created, use a lot of reflection to invoke members on objects. This has sparked my interest in exploring the use of reflection in respect to performance. A colleague of mine, <a href="http://no.linkedin.com/in/aasmundeldhuset">Åsmund Eldhuset</a>, and I set aside an evening for a geeknight to get to the bottom of this, and this is what we found out.</p>
<p>There are many ways to use reflection, and the performance on them vary a lot. What we did was to try out every method and timing them to measure performance. These are the methods we tested: Normal property access, normal reflection, compiling and invoking a compiled expression, using Emit to create, compile and run the statement.</p>
<p><strong>Normal property access</strong></p>
<p>To compare the other methods, we measured the performance on accessing a property the normal way:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">Run<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Normal property access&quot;</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span> var city <span style="color: #008000;">=</span> address.<span style="color: #0000FF;">City</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>It was no surprise that this was the fastest method.</p>
<p><strong>Normal reflection (250 times slower than normal property access)</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">var cityPropertyInfo <span style="color: #008000;">=</span> <span style="color: #008000;">typeof</span> <span style="color: #000000;">&#40;</span>Address<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetProperty</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;City&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Run<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;With reflection&quot;</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> cityPropertyInfo.<span style="color: #0000FF;">GetValue</span><span style="color: #000000;">&#40;</span>address, <span style="color: #008000;">new</span> <span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>This is what most of us think about when talking about reflection. This is also the by far most common method of reflection used in Glue. Although about 250 times slower than normal property access, this method has very strong sides compared to the other methods.</p>
<p><strong>Invoking compiled expressions (twice as slow as normal property access)</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>Address, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;&gt;</span> expression <span style="color: #008000;">=</span> x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">City</span><span style="color: #008000;">;</span>
var func <span style="color: #008000;">=</span> expression.<span style="color: #0000FF;">Compile</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Run<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Invoke compiled expression&quot;</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> func.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span>address<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Using compiled expressions is another way of dynamically invoking members on objects. Due to the syntax exposed in the api in Glue, most mapping specifications enter Glue as (uncompiled) expressions. The fact that it is only about twice as slow than normal property access, is very promising. But there is a catch, a big one. In order to invoke this way, the expression must be compiled. It is not compiled when it enters Glue, so we have to include the time it takes to compile the expression as well.</p>
<p><strong>Compile Expression and invoke it (51700 times slower than normal property access)</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">RunLong<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Compile Expression and invoke&quot;</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
             <span style="color: #000000;">&#123;</span>
                 var compiledFunction <span style="color: #008000;">=</span> expression.<span style="color: #0000FF;">Compile</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                 compiledFunction.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span>address<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
             <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Yes, if you have to compile an expression before invoking it, it takes about 200 times longer to do the operation than with normal reflection. Leaving this a unattractive method to use with Glue.</p>
<p><strong>Using Emit, invoking a compiled expression (4 times slower than normal property access)</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> Func<span style="color: #008000;">&lt;</span>Address, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> GetEmitDelegate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    var dm <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DynamicMethod<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;TestMethod&quot;</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span><span style="color: #000000;">&#41;</span>, <span style="color: #008000;">new</span> <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Address<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Address<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Module</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    MethodInfo getCity <span style="color: #008000;">=</span> <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Address<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetProperty</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;City&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetGetMethod</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    ILGenerator il <span style="color: #008000;">=</span> dm.<span style="color: #0000FF;">GetILGenerator</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    il.<span style="color: #0000FF;">Emit</span><span style="color: #000000;">&#40;</span>OpCodes.<span style="color: #0000FF;">Ldarg_0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    il.<span style="color: #0000FF;">EmitCall</span><span style="color: #000000;">&#40;</span>OpCodes.<span style="color: #0000FF;">Call</span>, getCity, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    il.<span style="color: #0000FF;">Emit</span><span style="color: #000000;">&#40;</span>OpCodes.<span style="color: #0000FF;">Ret</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>Func<span style="color: #008000;">&lt;</span>Address, <span style="color: #FF0000;">String</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#41;</span>dm.<span style="color: #0000FF;">CreateDelegate</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Func<span style="color: #008000;">&lt;</span>Address, <span style="color: #FF0000;">String</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
var emitDelegate <span style="color: #008000;">=</span> GetEmitDelegate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Run<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Emit: run compiled statement&quot;</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">=&gt;</span>emitDelegate<span style="color: #000000;">&#40;</span>address<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>My guess is that using Emit is not something you will be doing a lot. But, we had to try. Again, executing a compiled expression was fast. But as with expressions, the problem comes when you have to compile before running.</p>
<p><strong>Using Emit, create statement, compile it and run (39000 times slower than normal property access)</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">RunLong<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Emit: Create statement, compile, run&quot;</span>,<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">=&gt;</span>Emit<span style="color: #000000;">&#40;</span>address<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>As we can see, this is also horribly slow.</p>
<p><strong>Conclusion</strong></p>
<p>Unless you can create an expression/emit statement and compile it and then run the compiled version more than 200 times, in the app&#8217;s lifetime, using normal reflection is by far the preferred way to go when you have to dynamically invoke members on objects.</p>
<p>- Tore Vestues</p>
<p>Thanks to <a href="http://no.linkedin.com/in/aasmundeldhuset">Åsmund Eldhuset</a>.</p>
<p><a href='http://tore.vestues.no/2010/07/01/reflection-and-performance/performancerunner/' rel='attachment wp-att-104'>Here&#8217;s the source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2010/07/01/reflection-and-performance/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How I use the Glue mapping framework</title>
		<link>http://tore.vestues.no/2009/09/02/how-i-use-the-glue-mapping-framework/</link>
		<comments>http://tore.vestues.no/2009/09/02/how-i-use-the-glue-mapping-framework/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 11:33:33 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[Bits and bytes]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/2009/09/02/how-i-use-the-glue-mapping-framework/</guid>
		<description><![CDATA[Glue is a general purpose, bidirectional automatic mapping framework for the .Net platform, with strong verification and testing tools.
I&#8217;m actively developing it. I&#8217;m also actively using it. In this post I&#8217;ll share my experience as a user of Glue, and how easy it is to set up the mappings using TDD.
The example
We want to create [...]]]></description>
			<content:encoded><![CDATA[<p>Glue is a general purpose, bidirectional automatic mapping framework for the .Net platform, with strong verification and testing tools.</p>
<p>I&#8217;m actively developing it. I&#8217;m also actively using it. In this post I&#8217;ll share my experience as a user of Glue, and how easy it is to set up the mappings using TDD.</p>
<p><strong>The example</strong></p>
<p>We want to create a mapping between DomainPerson and GuiPerson, listed here.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> DomainPerson
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> Name <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> DomainAddress Address <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> DomainAddress
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> StreetAddress <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> ZipCode <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> City <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> Country <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> GuiPerson
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Id <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span><span style="color: #000000;">&#125;</span> set <span style="color: #000000;">&#123;</span> return<span style="color: #008000;">;</span><span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> Name <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> StreetAddress <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> ZipCode <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> City <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">String</span> Country <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p><strong>Making sure all properties are related</strong></p>
<p>What I test first is that all the properties are related (or actively ignored). This makes it easy to later detect changes in the classes we map between. It also makes it easy for us to see what properties we have to handle. </p>
<p>But first, in traditional TDD style, lets start with writing a failing test. The test should verify that all properties on GuiPerson are either related or actively ignored. The test looks like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Fact<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AsserAllPropertiesRelated<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	mapping.<span style="color: #0000FF;">GetRelationsVerification</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">AssertAllPropertiesRelated</span><span style="color: #008000;">&lt;</span>GuiPerson<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>and, as this will not compile, let&#8217;s create the actual mapping:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">mapping <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Mapping<span style="color: #008000;">&lt;</span>DomainPerson, GuiPerson<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>It compiles, but as expected, it fails. We have created a mapping, but nothing is related. A nice feature with Glue is that it tries to be as informative as possible when it fails. Look at the exception we receive when running this test:</p>
<blockquote><p>
Not all properties are related (or ignored): Id, Name, StreetAddress, ZipCode, City, Country
</p></blockquote>
<p>It tells us what properties we need to handle. This makes my job easy. I&#8217;ll just have to relate (or ignore) all the properties reported in the exception:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">mapping.<span style="color: #0000FF;">Relate</span><span style="color: #000000;">&#40;</span>domain<span style="color: #008000;">=&gt;</span>domain.<span style="color: #0000FF;">Id</span>,gui<span style="color: #008000;">=&gt;</span>gui.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
mapping.<span style="color: #0000FF;">Relate</span><span style="color: #000000;">&#40;</span>domain <span style="color: #008000;">=&gt;</span> domain.<span style="color: #0000FF;">Name</span>, gui <span style="color: #008000;">=&gt;</span> gui.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var addressMapping <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Mapping<span style="color: #008000;">&lt;</span>DomainAddress, GuiPerson<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
addressMapping.<span style="color: #0000FF;">AutoRelateEqualNames</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
mapping.<span style="color: #0000FF;">Flatten</span><span style="color: #000000;">&#40;</span>domain<span style="color: #008000;">=&gt;</span>domain.<span style="color: #0000FF;">Address</span>,addressMapping<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Running the test, I get another Exception:</p>
<blockquote><p>
Glue.GlueException : The relation between &#8216;Id&#8217; and &#8216;Id&#8217; has atleast one readonly property, and can not be related TwoWays
</p></blockquote>
<p>Ah, fair enough, it went a bit fast there. I related all properties, but I didn&#8217;t check if any where readonly. Luckily, Glue tells us this early. I&#8217;ll make this change:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">mapping.<span style="color: #0000FF;">RelateTowardsRight</span><span style="color: #000000;">&#40;</span>domain <span style="color: #008000;">=&gt;</span> domain.<span style="color: #0000FF;">Id</span>, gui <span style="color: #008000;">=&gt;</span> gui.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>And when I run the test again, it goes green. Now all properties are related, and we are protected from future changes. </p>
<p><strong>Make sure the mapping actually works</strong></p>
<p>But will it really work? We can also easily check if the actual values can be set on the target object. You should do this. I always do. So, lets start with another test:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Fact<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AssertMappingWorks<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    mapping.<span style="color: #0000FF;">GetMapperVerification</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">AssertMapsCorrectlyTowards</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> GuiPerson<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Running this test, we get an Exception:</p>
<blockquote><p>
Glue.GlueException : Failed properties: Id (Failed to set value)
</p></blockquote>
<p>Ah, it detected that Id on GuiPerson is totally unable to set. Ok, lets say that this is supposed to be this way. That means we should not map Id towards GuiPerson. That means that we must remove this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">mapping.<span style="color: #0000FF;">RelateTowardsRight</span><span style="color: #000000;">&#40;</span>domain <span style="color: #008000;">=&gt;</span> domain.<span style="color: #0000FF;">Id</span>, gui <span style="color: #008000;">=&gt;</span> gui.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Running the tests again makes AssertMappingWorks gets green, but now AsserAllPropertiesRelated got red again. That is because we have not related Id on GuiPerson. But since we do not want to relate it, we ignore it, to signal that we actively have made that choice. We do it like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">mapping.<span style="color: #0000FF;">IgnoreTowards</span><span style="color: #008000;">&lt;</span>GuiPerson<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>gui<span style="color: #008000;">=&gt;</span>gui.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p><img src='http://vestues.no/tore/wp-content/glue1.jpg' alt='Glue' style='float:right'/>Running the tests, they both are green, and now we know that we have a working mapping, which also are protected from failing on future changes.</p>
<p>Note that this example only tests the mapping and relations towards GuiPerson, in a bidirectional mapping scenario I advice to write the same two tests towards DomainPerson.</p>
<p>This is how I do it, and it works great for me. Hope you liked it. To learn more about Glue, and to download it, go to <a href="http://glue.codeplex.com">the Glue homepage at Codeplex</a></p>
<p>- Tore Vestues</p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2009/09/02/how-i-use-the-glue-mapping-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Glue &#8211; the new mapping framework</title>
		<link>http://tore.vestues.no/2009/08/10/glue-the-new-mapping-framework/</link>
		<comments>http://tore.vestues.no/2009/08/10/glue-the-new-mapping-framework/#comments</comments>
		<pubDate>Mon, 10 Aug 2009 09:57:36 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[Bits and bytes]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/2009/08/10/glue-the-new-mapping-framework/</guid>
		<description><![CDATA[I&#8217;ve spent this summer implementing a new mapping framework for the .Net plattform: Glue.
You&#8217;ll find examples and code here: http://glue.codeplex.com
Glue is a general purpose, bidirectional automatic mapping for the .Net platform, with strong verification and testing tools.
I&#8217;ve seen quite a lot of less than optimal handling of mapping issues in quite a few projects over [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent this summer implementing a new mapping framework for the .Net plattform: Glue.</p>
<p><a href="http://glue.codeplex.com">You&#8217;ll find examples and code here: http://glue.codeplex.com</a></p>
<p>Glue is a general purpose, bidirectional automatic mapping for the .Net platform, with strong verification and testing tools.</p>
<p>I&#8217;ve seen quite a lot of less than optimal handling of mapping issues in quite a few projects over the years. Again and again mapping seems to be just a task we have to do, and a bit too small for automating. It becomes clearer and clearer to me that mapping is both an important task in many projects, and it is always a repetitive and boring task. In addition far to often subtle annoying bugs tend to sneak into mapping code. This motivated me to create Glue. And this is what I need from a mapping framework:</p>
<p>a) a way to automate mapping, mostly because it is boring, and that makes it error prone,<br />
b) a way to automatically test the mapping, I&#8217;ve found that manual written test code for mapping is seldom done in a good way,<br />
c) a way to prevent future changes making my mappings obsolete. When people make changes, they rarely focus on mapping (and honestly they should not either). They should be told when they have to update the mapping.</p>
<p>Now, you could argue that there is already a mapping framework available on the .Net plattform. And when I started this work, I actually started with that framework, thinking I could just make a few extensions to fulfil my needs. I actually spent some time in the  source code to try to implement it, but sadly I realized that our needs differed too much. So, I created Glue, and these where the driving forces: </p>
<p><strong>General purpose</strong></p>
<p>Glue is a general purpose mapper. We realize that in the real world there are a lot of different solutions, and not all of them follow &#8220;the one true pattern&#8221;. In fact, mapping is often used to map to and from subsystems that are far from well designed. Subsystems we try to hide in a layer because we do not want it to leak into the other layers. Thus, we believe a mapper must support quite a few different scenarios. The goal is to promote good coding practices, but not to ignore the fact that there is a lot of legacy code out there that forces us to work a bit differently at times.</p>
<p><strong>Bidirectional</strong></p>
<p>I would say that in many mapping scenarios we need to map in both directions. First we get data from an object in a layer, and map it to an object in the layer above. When that layer is done with manipulating that object, we often want to map it back to down to the layer where it all came from. I have noticed not all mapping frameworks see it this way, and this was one of the reasons why I started working on Glue instead of trying to extend existing frameworks.</p>
<p><strong>Strong verification and testing tools</strong></p>
<p>I want to be absolutely certain that my mapping works. I also want to make sure that it is very hard to break it later. Manually writing tests for mapping is even more tedious than writing manual mapping. Glue automates this. Future changes has a sad reputation of breaking mapping code. Glue helps you detect this. Tools for helping the mapping is very important to me. And more tools will be available in future releases.</p>
<p><strong>Simplicity</strong></p>
<p>Mapping should be simple. Glue tries to simplify both the mapping process, and the verification and testing. You should not have to state the obvious, and Glue support relating properties automatically based on names.</p>
<p><strong>Explicitness</strong></p>
<p>Although Glue enables you to automate much of the mapping process, it also gives you the opportunity to be explicit about the mapping. So if you want to describe every relation in detail, you can. When it comes to understandable code this can be a good thing. Taking difficult to understand implicit mappings, and stating them explicitly can sometimes make things much easier to understand. </p>
<p><strong>Current version and the future</strong></p>
<p>The current version is 0.2.0 Alpha. It is still in Alpha because if we find good ways to improve the API, we do not want to lock ourselves to it just yet, before we get more feedback. I&#8217;m guessing the next release will be Beta.</p>
<p>I am currently using Glue on the project I am working on, and in about a month it will reach production. This somewhat guarantees that it will continue to evolve as our needs expand, and that we will find bugs sooner, and they will be fixed sooner.</p>
<p>Looking into the future we have some exciting ideas on tools to help with the mapping, and we are also working hard to make Glue as easy as possible to use, so expect simplifications. In addition we want Glue to serve a broad set of needs, so feedback is highly appreciated and if you explain your special needs, we might just implement it.</p>
<p><a href="http://glue.codeplex.com">You&#8217;ll find examples and code here: http://glue.codeplex.com</a></p>
<p>- Tore Vestues</p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2009/08/10/glue-the-new-mapping-framework/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC: DefaultControllerFactory is not thread safe!</title>
		<link>http://tore.vestues.no/2009/07/03/aspnet-mvc-defaultcontrollerfactory-is-not-thread-safe/</link>
		<comments>http://tore.vestues.no/2009/07/03/aspnet-mvc-defaultcontrollerfactory-is-not-thread-safe/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 09:05:32 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[Bits and bytes]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/2009/07/03/aspnet-mvc-defaultcontrollerfactory-is-not-thread-safe/</guid>
		<description><![CDATA[I am not sure if this is a bug or a &#8220;feature&#8221; of the ASP.NET MVC framework. Either way, this is something you should be aware of as it can cause some very hard to track concurrency issues which might leak information between your HttpRequests.
In my last project we used the ASP.NET MVC framework along [...]]]></description>
			<content:encoded><![CDATA[<p>I am not sure if this is a bug or a &#8220;feature&#8221; of the ASP.NET MVC framework. Either way, this is something you should be aware of as it can cause some very hard to track concurrency issues which might leak information between your HttpRequests.</p>
<p>In my last project we used the ASP.NET MVC framework along with StructureMap, which made us create our own controller factory. I just blogged about it <a href="http://tore.vestues.no/2009/06/28/aspnet-mvc-let-structuremap-create-your-controllers/">here</a>. </p>
<p>If it was a good design decision or not I am not completely certain anymore, but we added some more framework logic to the controller factory, including checking state on the HttpRequest-object. This, it turned out, was a path to trouble. After a while we had unexpected behavior in our system, sometimes it leaked information between HttpRequests it seemed! But since this only happened during stress testing, it was hard to find the cause.</p>
<p>What we found was that the RequestContext.HttpContext-object was not all the way thread safe. When a request hits our custom controller, and the request goes to sleep to serve another request, the HttpContext of the factory changes to the second requests HttpContext. This means that the first request will work on the second requests HttpContext when it wakes up. This is bad news if you are dependent on the HttpContext in your custom controller factory.</p>
<p>The lesson is this: you have to do at least one of the two actions below if you want to access the HttpContext in your custom controller factory.</p>
<p>1) </p>
<p>The problem occurs when you set your controller factory like this (normally in the global.asax file)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">ControllerBuilder.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">SetControllerFactory</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> CustomControllerFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>If you send in an instance lik this, it will be the only instance of your controller factory, and this is where the HttpContext-concurrency issues arrive in the first place. What you can do, which will take away all the concurrency issues is to send in the type instead of an instance, like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">ControllerBuilder.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">SetControllerFactory</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>CustomControllerFactory<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>The drawback to sending in the type is a) your controller factory will be instantiated for every request and b) you cannot send in anything to your instance (since you&#8217;re not instantiating it). This might not be a problem, and if not, you&#8217;re good to go.</p>
<p>2) </p>
<p>If you have to use one instance only of your controller factory, and you need to access the HttpContext for a request, you MUST use the HttpContext.Current-instance and not the RequestContext.HttpContext. The HttpContext.Current is as far as I&#8217;ve tested thread safe.</p>
<p>Not thread safe:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">RequestContext.<span style="color: #0000FF;">HttpContext</span></pre></td></tr></table></div>

<p>The thread safe alternative:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">HttpContext.<span style="color: #0000FF;">Current</span></pre></td></tr></table></div>

<p><a href="http://aspnet.codeplex.com/WorkItem/View.aspx?WorkItemId=3724">I just found out that this is a bug</a> </p>
<p>- Tore Vestues</p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2009/07/03/aspnet-mvc-defaultcontrollerfactory-is-not-thread-safe/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC: Let StructureMap create your controllers</title>
		<link>http://tore.vestues.no/2009/06/28/aspnet-mvc-let-structuremap-create-your-controllers/</link>
		<comments>http://tore.vestues.no/2009/06/28/aspnet-mvc-let-structuremap-create-your-controllers/#comments</comments>
		<pubDate>Sun, 28 Jun 2009 10:09:41 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[Bits and bytes]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Frameworks]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/2009/06/28/aspnet-mvc-let-structuremap-create-your-controllers/</guid>
		<description><![CDATA[For those of you already familiar with StructureMap and want to use it to configure your objects in ASP.NET MVC, read on.
The ASP.NET MVC framework has a default controller factory (DefaultControllerFactory) that requires all controllers to have a parameterless constructor. So, if you want to inject your dependencies to the constructor, you can&#8217;t do it. [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you already familiar with StructureMap and want to use it to configure your objects in ASP.NET MVC, read on.</p>
<p>The ASP.NET MVC framework has a default controller factory (DefaultControllerFactory) that requires all controllers to have a parameterless constructor. So, if you want to inject your dependencies to the constructor, you can&#8217;t do it. In addition, Microsoft suggests the following pattern to mock out the dependencies when testing:</p>
<p><strong>The Microsoft way of testing</strong></p>
<p>(Example from <a href="http://www.asp.net/learn/mvc/tutorial-31-cs.aspx">www.asp.net/mvc</a>)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//The Microsoft way...</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> GroupController <span style="color: #008000;">:</span> Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> IContactManagerService _service<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> GroupController<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _service <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ContactManagerService<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ModelStateWrapper<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">ModelState</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> GroupController<span style="color: #000000;">&#40;</span>IContactManagerService service<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _service <span style="color: #008000;">=</span> service<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>In other words, create one constructor for the actual application, and one constructor for testing. It works, you get to test it, it&#8217;s not all that bad, but it just doesn&#8217;t sit well with me.</p>
<p><strong>Take control of your controllers!</strong></p>
<p>Don&#8217;t you like this either? Well, there is an easy way out of it. One of the really good things about ASP.NET MVC is that it is easy to configure. You can create your own controller factory and take control of the whole process. It might sound like a complex task, but it isn&#8217;t.</p>
<p>Let’s start with our controller, it has a dependency that is injected through the constructor:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> HomeController <span style="color: #008000;">:</span> Controller
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> Speaker speaker<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> HomeController<span style="color: #000000;">&#40;</span>Speaker speaker<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">speaker</span> <span style="color: #008000;">=</span> speaker<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        ViewData.<span style="color: #0000FF;">Model</span> <span style="color: #008000;">=</span> speaker<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Running the website now, trying to reach this controller, will make the framework crash (&#8221;No parameterless constructor defined for this object.&#8221;). We need our own controller factory to make this work:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> StructureMapControllerFactory <span style="color: #008000;">:</span> DefaultControllerFactory
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> IContainer container<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> StructureMapControllerFactory<span style="color: #000000;">&#40;</span>IContainer container<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">container</span> <span style="color: #008000;">=</span> container<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> IController GetControllerInstance<span style="color: #000000;">&#40;</span>Type controllerType<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>IController<span style="color: #000000;">&#41;</span>container.<span style="color: #0000FF;">GetInstance</span><span style="color: #000000;">&#40;</span>controllerType<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>This controller takes in a StructureMap.IContainer and uses it to create all the controllers. It inherits from the DefaultControllerFactory and overrides the GetControllerInstance-method that is used to create controllers.</p>
<p>Now all we have to do is to tell the ASP.NET MVC framework that it should use our controller factory. To do that simply add this line in the Application_Start() method in the Global.asax file:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">ControllerBuilder.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">SetControllerFactory</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> StructureMapControllerFactory<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Container<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>(Notice that we do not need to configure StructureMap since our dependencies are so easy to resolve. In a real world app you will most probably need to configure the container)</p>
<p>There you go. Using StructureMap with the ASP.NET MVC framework is easy!</p>
<p><a href='http://vestues.no/tore/wp-content/structuremapcontrollerfactoryexample.zip'>Download the complete example here </a></p>
<p>-Tore Vestues</p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2009/06/28/aspnet-mvc-let-structuremap-create-your-controllers/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Creating a dynamic xml reader with C# 4.0</title>
		<link>http://tore.vestues.no/2009/01/05/creating-a-dynamic-xml-reader-with-c-40/</link>
		<comments>http://tore.vestues.no/2009/01/05/creating-a-dynamic-xml-reader-with-c-40/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 21:28:49 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[Bits and bytes]]></category>
		<category><![CDATA[Boo]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/2009/01/05/creating-a-dynamic-xml-reader-with-c-40/</guid>
		<description><![CDATA[&#8220;The static type dynamic&#8221; was the catchphrase at PDC&#8217;08 when talking about what&#8217;s new in C# 4.0. The dynamic type seems to be introduced mainly to simplify the code you write when doing Com interop. But many also see this as a step towards the dynamic languages for C#. I like C#. I also like [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;The static type dynamic&#8221; was the catchphrase at PDC&#8217;08 when talking about what&#8217;s new in C# 4.0. The dynamic type seems to be introduced mainly to simplify the code you write when doing Com interop. But many also see this as a step towards the dynamic languages for C#. I like C#. I also like dynamic languages like python. In addition I am a big fan of the static language Boo that actually feels quite dynamic. This has given me a special interest in the dynamic type in C#.</p>
<p>One of the nice things (there are several others!) about dynamic languages like Python is that the code feels much cleaner. It is not bloated with type declarations all over. This clean feel was also the goal of the language Boo, and even though it is a static language, Boo really gives you that dynamic feel.</p>
<p>The question is the of course: Is the C# getting more dynamic?</p>
<p>Well to be honest I do not think so. Having to declare a type at all (even if the declaration is &#8220;dynamic&#8221;) feels quite static, and the code bloats like static languages. Most of the time. I think it is wrong to think that C# is a more dynamic language due to the dynamic keyword, and I feel you are not using the right tools if you try to use C# as a dynamic language. If you want to write dynamic code, use a dynamic language.</p>
<p>But when we get the dynamic keyword, lets find things to use it for. When I am introduced to new features I am not that interested in all the fancy things you can do with it, I want real value. And I think I have found an example of real value in the dynamic keyword. I&#8217;ll give you an example, other than in com-interop, where the dynamic keyword will help you keep your code nice and clean, where otherwise you&#8217;d have to write a whole lot of ugly code.</p>
<p><strong>The Quick Xml Reader</strong></p>
<p>The funny thing is that I have already implemented a nice xmlreader in Boo (using the IQuackFoo-interface). When the dynamic keyword was introduced in C# 4 and you&#8217;ve got the IDynamicObject from the DLR, I figured I can do the exact same thing in C#. That&#8217;s just cool!</p>
<p>So what did I do? Here&#8217;s the comment from the Boo code file:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> XmlReader<span style="color: black;">&#40;</span>IQuackFu<span style="color: black;">&#41;</span>:
<span style="color: #483d8b;">&quot;&quot;&quot;
Represents an xmldocument using &quot;dynamic typing&quot;. 
Can be used to retrieve single values from the xml-document.
There is no support for retrieving lists.
&nbsp;
Language: 
 Element: Both nodes and leaves
 Node: an element containing sub-elements
 Leaf: An element that represents a value (in xml this is an attribute or a node with nodetype text)
&nbsp;
use method names to retrieve nodes, and properties to retrieve leaves
example:
&lt;myXml stat=&quot;ok&quot;&gt;
	&lt;user id=&quot;123&quot; nsid=&quot;123&quot;&gt;
	    &lt;username&gt;Tore&lt;/username&gt;
	    &lt;password&gt;foo&lt;/password&gt;
	&lt;/user&gt;
&lt;/myXml&gt;
&nbsp;
myXml as duck = XmlReader(xmlString)
myXml //will fail since &quot;myXml&quot; is no leaf
myXml() // will return a new XmlReaderrepresenting the rsp-node with children
myXml().stat // will return &quot;ok&quot;
myXml().user().username // will return &quot;Tore&quot;
&quot;&quot;&quot;</span></pre></td></tr></table></div>

<p>How cool is that? This is dynamic, resolved at run time, and it can now be done in C# as well. The point with parsing xml is that you won&#8217;t catch errors in the xml structure at compile time anyway. So why not just do the code dynamic?</p>
<p>So, our Xml reader let&#8217;s you easily get values from an xml structure without having to declare all the types and without having to worry about all the details of the xml-parsing that normally is a bit complex and frankly, boring. In addition the code is much more readable than normal xml-parsing code.</p>
<p><strong>Xml reading in C#</strong></p>
<p>So, how do we do this in C#? Our XmlReader is a class where you can use any method name or property name on it, and it will still compile. For example, This will compile:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">dynamic ourReader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlReader<span style="color: #000000;">&#40;</span>xmlString<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
ourReader.<span style="color: #0000FF;">WhateverMethodNameYouLike</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>To do this, the XmlReader needs to inherit the IDynamicObject, and it has to implement the method GetMetaObject that returns a MetaObject. </p>
<p><strong>Simplifying the MetaObject</strong></p>
<p>To implement a MetaObject and do some useful stuff you actually have to understand how to build a Linq expression tree that describes the action to be taken. If people are going to use this, it should be as simple as possible. Building Linq expression trees is not as simple as possible IMHO. So, I&#8217;ll make a generic base class that hides the whole MetaObject with its Linq expression trees, and let you override some methods in your XmlReader class instead.</p>
<p>I will not go into details on how I have done this, but if you&#8217;re interested, you can look at the source (there&#8217;s a link at the end). The &#8216;magic&#8217; is within the MetaBaseDynamicObject. Together with the BaseDynamicObject these can be reused for different tasks that needs on the fly interpreting of property and method calls.</p>
<p>All <i>you</i> have to do is to inherit the BaseDynamicObject, and override any of these methods:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> BaseDynamicObject<span style="color: #008000;">:</span>IDynamicObject
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// If a method on this object is called run time, this method will be called.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;action&quot;&gt;Information on the method that has been called&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;args&quot;&gt;parameters on the method call&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The return value for the originally called method&lt;/returns&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">Object</span> Call<span style="color: #000000;">&#40;</span>CallAction action, <span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// If a property is set on this object run time, this method will be called.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;action&quot;&gt;Information on the property which value is attemted set&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;value&quot;&gt;the value that the property is attemted set with&lt;/param&gt;    </span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> SetMember<span style="color: #000000;">&#40;</span>SetMemberAction action, <span style="color: #FF0000;">object</span> value<span style="color: #000000;">&#41;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// If a property is called on this object run time, this method will be called.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;action&quot;&gt;Information on the property which is being called&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The return value for the property that has been called&lt;/returns&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #FF0000;">Object</span> GetMember<span style="color: #000000;">&#40;</span>GetMemberAction action<span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">//, MetaObject[] args)</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p><strong>Implementing the XmlReader</strong></p>
<p>So what we have to do here is to create a class (XmlReader), inherit the BaseDynamicObject, and override Call and GetMember. We will not bother with SetMember now, as we do not want to support updating the xml. This is what it looks like:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> XmlReader<span style="color: #008000;">:</span>BaseDynamicObject
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> XmlElement element<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> XmlReader<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> xmlText<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        var doc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlDocument<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        doc.<span style="color: #0000FF;">LoadXml</span><span style="color: #000000;">&#40;</span>xmlText<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        element <span style="color: #008000;">=</span> doc.<span style="color: #0000FF;">DocumentElement</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> XmlReader<span style="color: #000000;">&#40;</span>XmlElement xmlelement<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        element <span style="color: #008000;">=</span> xmlelement<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">object</span> Call<span style="color: #000000;">&#40;</span>CallAction action, <span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var elements <span style="color: #008000;">=</span> element.<span style="color: #0000FF;">SelectNodes</span><span style="color: #000000;">&#40;</span>action.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>elements.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> 
            <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Element '&quot;</span> <span style="color: #008000;">+</span> action.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;' doesn't exist in xml&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>IsLeaf<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>XmlElement<span style="color: #000000;">&#41;</span>elements<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Element '&quot;</span> <span style="color: #008000;">+</span> action.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;' is a Leaf and cannot be fetched as a Node&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> XmlReader<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>XmlElement<span style="color: #000000;">&#41;</span>elements<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">object</span> GetMember<span style="color: #000000;">&#40;</span>GetMemberAction action<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var elements <span style="color: #008000;">=</span> element.<span style="color: #0000FF;">SelectNodes</span><span style="color: #000000;">&#40;</span>action.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>elements.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>IsLeaf<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>XmlElement<span style="color: #000000;">&#41;</span>elements<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> elements<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">InnerText</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Element '&quot;</span><span style="color: #008000;">+</span>action.<span style="color: #0000FF;">Name</span><span style="color: #008000;">+</span><span style="color: #666666;">&quot;' is not a Leaf and cannot be fetched one&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        var attribute <span style="color: #008000;">=</span> element.<span style="color: #0000FF;">GetAttributeNode</span><span style="color: #000000;">&#40;</span>action.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>attribute <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Element '&quot;</span><span style="color: #008000;">+</span>action.<span style="color: #0000FF;">Name</span><span style="color: #008000;">+</span><span style="color: #666666;">&quot;' doesn't exist in xml&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> attribute.<span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">bool</span> IsLeaf<span style="color: #000000;">&#40;</span>XmlElement leafElement<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> leafElement.<span style="color: #0000FF;">ChildNodes</span>.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">&amp;&amp;</span>
            leafElement.<span style="color: #0000FF;">ChildNodes</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">NodeType</span> <span style="color: #008000;">==</span> XmlNodeType.<span style="color: #0000FF;">Text</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>This class now does all the xml-handling. So that means you can do stuff like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span> xmlString <span style="color: #008000;">=</span> 
	<span style="color: #666666;">&quot;&lt;?xml version=<span style="color: #008080; font-weight: bold;">\&quot;</span>1.0<span style="color: #008080; font-weight: bold;">\&quot;</span> encoding=<span style="color: #008080; font-weight: bold;">\&quot;</span>utf-8<span style="color: #008080; font-weight: bold;">\&quot;</span> ?&gt;&quot;</span> <span style="color: #008000;">+</span>
	<span style="color: #666666;">&quot;&lt;myXml stat=<span style="color: #008080; font-weight: bold;">\&quot;</span>ok<span style="color: #008080; font-weight: bold;">\&quot;</span>&gt;&quot;</span> <span style="color: #008000;">+</span>
		<span style="color: #666666;">&quot;&lt;user id=<span style="color: #008080; font-weight: bold;">\&quot;</span>321<span style="color: #008080; font-weight: bold;">\&quot;</span> nsid=<span style="color: #008080; font-weight: bold;">\&quot;</span>123<span style="color: #008080; font-weight: bold;">\&quot;</span>&gt;&quot;</span> <span style="color: #008000;">+</span>
		    <span style="color: #666666;">&quot;&lt;username&gt;Tore&lt;/username&gt;&quot;</span> <span style="color: #008000;">+</span>
		    <span style="color: #666666;">&quot;&lt;password&gt;foo&lt;/password&gt;&quot;</span> <span style="color: #008000;">+</span>
		<span style="color: #666666;">&quot;&lt;/user&gt;&quot;</span> <span style="color: #008000;">+</span>
	<span style="color: #666666;">&quot;&lt;/myXml&gt;&quot;</span><span style="color: #008000;">;</span>
dynamic myXml <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlReader<span style="color: #000000;">&#40;</span>xmlString<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>myXml.<span style="color: #0000FF;">stat</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// &quot;ok&quot;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>myXml.<span style="color: #0000FF;">user</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">username</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// &quot;Tore&quot;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>myXml.<span style="color: #0000FF;">user</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">nsid</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// &quot;123&quot;</span></pre></td></tr></table></div>

<p>This is a real declarative and easy way to handle xml, and since xml will only fail run time anyway, there is no argument that you lose compile time checking either.</p>
<p>I hope that has triggered you a bit on some exciting possibilities on using the dynamic type.</p>
<p><a href='http://vestues.no/tore/wp-content/dynamic.zip' title='Dynamic C#4.0 Xml example'>Here&#8217;s</a> the source. Please remember you will need C# 4.0 to make this work.</p>
<p>Thanks to <a href="http://saftsack.fs.uni-bayreuth.de/~dun3/archives/first-look-ducktyping-c-4-0-idynamicobject-metaobject/202.html">this</a> and <a href="http://blogs.msdn.com/cburrows/archive/2008/10/28/c-dynamic-part-ii.aspx">this</a> blog for giving me information and ideas.</p>
<p>-Tore Vestues</p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2009/01/05/creating-a-dynamic-xml-reader-with-c-40/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Looping collections in C#</title>
		<link>http://tore.vestues.no/2008/08/04/looping-collections-in-c/</link>
		<comments>http://tore.vestues.no/2008/08/04/looping-collections-in-c/#comments</comments>
		<pubDate>Mon, 04 Aug 2008 18:32:16 +0000</pubDate>
		<dc:creator>Tore Vestues</dc:creator>
				<category><![CDATA[Bits and bytes]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding principles]]></category>

		<guid isPermaLink="false">http://tore.vestues.no/2008/08/04/looping-collections-in-c/</guid>
		<description><![CDATA[In this post I want to demonstrate that with a few nice language features in C# we can do more with less when working with collections, meaning expressing more with less code.
There are a couple of points I want to make here. First I care about writing code that can be easily understood after it [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I want to demonstrate that with a few nice language features in C# we can do more with less when working with collections, meaning expressing more with less code.</p>
<p>There are a couple of points I want to make here. First I care about writing code that can be easily understood after it is written. Secondly, I want to express as much as possible with as little as possible. I do not want to write five lines of code if I can express the same thing with just one line of code. These two concerns do of course relate. The keywords here are flexibility and efficiency. And let us not forget writing clean, expressive code is a lot more fun than fiddling with repetitive code: How many times have you written code (more than one line) to loop a collection? And how inspiring is it really? We want to loop those collections as easy as possible.</p>
<p>Languages like Python (and its relatives like Ruby and Boo) has put a lot of effort into making working with collections (or lists) as easy as possible. My main language at work nowadays is C#, and I must admit I envy developers in these languages when it comes to collections.</p>
<p>I actually envy them so much that I&#8217;ve been reflecting on how we can make our lives easier as well. With .Net 3.5 there is actually something we can do about it.</p>
<p><strong>Collections in Python, Ruby and Boo</strong></p>
<p>But first let me show you what I envy.</p>
<p>Let&#8217;s use a simple example to demonstrate my point: We have a list of numbers where we want to make a sub list with all the numbers bigger than 10. In addition, we do of course want to print the sub list to the console.</p>
<p><a href="http://boo.codehaus.org/" title="Boo">Boo</a> (one of the most exiting languages for me these days) will simply do it this way:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">numbers = <span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">15</span>,<span style="color: #ff4500;">7</span>,<span style="color: #ff4500;">100</span>,<span style="color: #ff4500;">3</span>,<span style="color: #ff4500;">4</span>,<span style="color: #ff4500;">5</span>,<span style="color: #ff4500;">19</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> numbers.<span style="color: black;">Collect</span> <span style="color: black;">&#40;</span><span style="color: black;">&#123;</span>number <span style="color: #ff7700;font-weight:bold;">as</span> <span style="color: #008000;">int</span>| number<span style="color: #66cc66;">&gt;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>In Boo, lists have built in functionality for making sub lists.  I think this code is beautiful. The elegance (and often confusion for C#-developers not familiar with these kinds of languages) is how you declare the conditions for making the sub list. I won&#8217;t go into details about this but what we say here is: for the list &#8220;numbers&#8221;, take each &#8220;number&#8221; and add it to the sub list if &#8220;number&gt;10&#8243;. The print statement is all you need to print the list (in an understandable human form) to the console.</p>
<p>It can&#8217;t be much simpler than this. Although I actually like the Ruby-way of doing this a micro-tad better:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">numbers = <span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">15</span>,<span style="color: #ff4500;">7</span>,<span style="color: #ff4500;">100</span>,<span style="color: #ff4500;">3</span>,<span style="color: #ff4500;">4</span>,<span style="color: #ff4500;">5</span>,<span style="color: #ff4500;">19</span><span style="color: black;">&#93;</span>
puts numbers.<span style="color: black;">find_all</span><span style="color: black;">&#123;</span>|number| number<span style="color: #66cc66;">&gt;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#125;</span></pre></div></div>

<p>I like the find_all method name a bit better than Collect, and I like that you do not have to say &#8220;as int&#8221;. On the downside the &#8220;puts&#8221;-statement is a bit less intuitive than plain &#8220;print&#8221;. But in the long run these are details (or at least we can pretend it is in this context).</p>
<p>In python you can say it like this:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">numbers = <span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">15</span>,<span style="color: #ff4500;">7</span>,<span style="color: #ff4500;">100</span>,<span style="color: #ff4500;">3</span>,<span style="color: #ff4500;">4</span>,<span style="color: #ff4500;">5</span>,<span style="color: #ff4500;">19</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: black;">&#91;</span>number <span style="color: #ff7700;font-weight:bold;">for</span> number <span style="color: #ff7700;font-weight:bold;">in</span> numbers <span style="color: #ff7700;font-weight:bold;">if</span> number <span style="color: #66cc66;">&gt;</span> <span style="color: #ff4500;">10</span><span style="color: black;">&#93;</span></pre></div></div>

<p>Maybe a bit weirder at first glance, but it&#8217;s very concise if you&#8217;re used to it.</p>
<p>Ok, the point of this was to demonstrate that it is actually quite easy to express a loop very compact and elegant, and this is where I want to be when I loop collections in C#.</p>
<p><strong>Looping collections in C#</strong></p>
<p>The &#8220;this will work in almost any language&#8221;-code for doing the same job in C# will look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> numbers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">15</span>, <span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">100</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span>, <span style="color: #FF0000;">19</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span> subset <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> number <span style="color: #0600FF;">in</span> numbers<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>number <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span>
        subset.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>number<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> number <span style="color: #0600FF;">in</span> subset<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>number <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>It&#8217;s outright horrible compared to the Boo-example! It makes me wonder how many times longer it takes to develop a C#-application, and how much less readable it will be.</p>
<p>So what can we do? Well, let&#8217;s see if we can make it simpler.</p>
<p><strong>Using delegates</strong></p>
<p>With .Net 2.0, we were introduced to the concept of delegates (function pointers). It&#8217;s an odd concept for the traditional C#/vb/Java-developer. Function pointers are very common in some languages (again, typically in Python and friends), but not in &#8220;our&#8221; languages. Anyway, I&#8217;m really happy that Microsoft introduced us to this as it gives us some interesting possibilities.</p>
<p>We can remove a foreach-loop by using the Array.FindAll-method that takes a delegate. The delegate specifies how to filter the array, and then we have a sub list. This sounds a bit nicer. It looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> numbers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">15</span>, <span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">100</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span>, <span style="color: #FF0000;">19</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> subset <span style="color: #008000;">=</span> Array.<span style="color: #0000FF;">FindAll</span><span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>numbers, 
      <span style="color: #FF0000;">delegate</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> number<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> number <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> number <span style="color: #0600FF;">in</span> subset<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>number <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Still a lot of code unfortunately, and the FindAll-method call isn&#8217;t really as clear and simple as it could have been either. I won&#8217;t go into details about the delegate-concept here, but if you do not understand how it works, I really advice you to take a look. It&#8217;s a powerful tool. (Look at my post <a href="http://tore.vestues.no/2007/12/10/delegates-the-interface-for-methods/">Delegates, the interface for methods</a>)</p>
<p><strong>Using extension methods</strong></p>
<p>The fact that you can just write &#8220;print&#8221; in Boo, where I have to write a foreach/Console.Write in C#, annoys me. Let&#8217;s fix it.</p>
<p>We could fix this by creating a subclass of Array, and override the ToString()-method. But frankly I do not like the idea. That would mean that everybody everywhere have to use that subclass instead of the standard Array-class. And that isn&#8217;t going to happen. There must be an easier way, and it is if you are fortunate enough to be working with .Net 3.0 . Here you can add an <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">Extension Method</a> to the Array-class. Unfortunately you cannot override a method by doing this (i.e. ToString), but you can create new methods on the Array. So let&#8217;s do that.</p>
<p>First the extension method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> ArrayExtension
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Print<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> list<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> number <span style="color: #0600FF;">in</span> list<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>number <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; &quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>And then the main code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> numbers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">15</span>, <span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">100</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span>, <span style="color: #FF0000;">19</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> subset <span style="color: #008000;">=</span> Array.<span style="color: #0000FF;">FindAll</span><span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>numbers, 
      <span style="color: #FF0000;">delegate</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> number<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> number <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
subset.<span style="color: #0000FF;">Print</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// extension method</span></pre></div></div>

<p>Look at that. I&#8217;m feeling better now. We&#8217;re getting somewhere.</p>
<p><strong>Using Lambdas</strong></p>
<p>I still do not like the delegate-declaration in the &#8220;FindAll&#8221;-method call. It&#8217;s clumsy, verbose, and not enough to the point. Lambdas introduced in .Net 3.0 will help us simplify this. Read more about lambdas <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx">here</a>. For us, a lambda is just an easy way to declare a delegate. Look at this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> numbers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">15</span>, <span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">100</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span>, <span style="color: #FF0000;">19</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> subset <span style="color: #008000;">=</span> Array.<span style="color: #0000FF;">FindAll</span><span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>numbers, number <span style="color: #008000;">=&gt;</span> number <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">10</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
subset.<span style="color: #0000FF;">Print</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Sweet! When you get used to it (and you should) the lambda-syntax is very easy to read. And look at how we do not have to declare the types anymore. I really like it. There can be a big difference between how you <em>can</em> do things, and how you <em>should</em> do things. I think this is how you <em>should</em> do it.</p>
<p><strong>Using Linq</strong></p>
<p>Actually, .Net introduces another elegant way to do this, Linq. It has quite a different syntax from most other languages with one notable exception: Sql. Linq treats almost anything like a collection that can be queried. Thus link is in itself a little dsl query language. It&#8217;s a great idea, I&#8217;ll give Microsoft that. Anyway, this is how our solution will look if we use Linq:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> numbers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">15</span>, <span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">100</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span>, <span style="color: #FF0000;">19</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
var subset <span style="color: #008000;">=</span>
    from n <span style="color: #0600FF;">in</span> numbers
    where n <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">10</span>
    select n<span style="color: #008000;">;</span>
&nbsp;
subset.<span style="color: #0000FF;">Print</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// new extension method</span></pre></div></div>

<p>Yes, I like this one too. If you know Sql, and we probably all do, this is very easy to read.</p>
<p>Which one of these two do I like the most? To be honest, I&#8217;m not sure. I like them both. Feel free to give your thoughts on the issue.</p>
<p><strong>Conclusion</strong></p>
<p>To be honest I still like the Python/Ruby/Boo- way a little bit better, but with lambdas or linq I think C# is almost as elegant.</p>
<p>I want to make two points here:</p>
<p>First, it’s important to evaluate how we write code. We should always try to find ways to express more with less, and in this case we have been given several tools to help us on the way. It&#8217;s just up to us to use them, and use them well.</p>
<p>Secondly, do not let a language limit you. Try different languages and look at how they solve problems in different ways. Many times it will inspire you to find new and better ways to use a language, like here where we&#8217;ve applied a little <a href="http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0">pythonic</a> thinking to C#.</p>
<p>- Tore Vestues</p>
]]></content:encoded>
			<wfw:commentRss>http://tore.vestues.no/2008/08/04/looping-collections-in-c/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
