<?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>MSDN Blogs</title>
	<atom:link href="http://msdnrss.thecoderblogs.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://msdnrss.thecoderblogs.com</link>
	<description>via RSS Feed &#38; Other Development Resources</description>
	<lastBuildDate>Sat, 04 Feb 2012 17:59:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>The journal of becoming senior tester (13) &#8211; Understand the product</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-13-understand-the-product/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-13-understand-the-product/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 17:59:08 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-13-understand-the-product/</guid>
		<description><![CDATA[I beleive as a senior tester, we should fully understand the product we are testing aginst. Knowing the direction/future of the production is the first step of creating the best tests. We should ?be actively involved in project/product planing, and &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-13-understand-the-product/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<!-- AdSense Now! V1.98 -->
<!-- Post[count: 2] -->
<div class="adsense adsense-leadin" style="float:right;margin: 12px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-0070021183285208";
/* 300x250, created 7/24/10 */
google_ad_slot = "3375814894";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>I beleive as a senior tester, we should fully understand the product we are testing aginst. Knowing the direction/future of the production is the first step of creating the best tests.<br />
 We should ?be actively involved in project/product planing, and make impact on the strategy of the product (not the test). Note, this is one of the important way which we can improve product quality.<br />
 Being involved on production design can also help us enhance skills about manging/build a project. And enhance&#8230;(<a href="http://blogs.msdn.com/b/qingsongyao/archive/2012/02/04/the-journal-of-becoming-senior-tester-13-understand-the-product.aspx">read more</a>)<img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/d679f_aggbug.aspx?PostID=10263948" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-13-understand-the-product/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The journal of becoming senior tester (12) &#8211; Coding, Coding, Coding</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-12-coding-coding-coding/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-12-coding-coding-coding/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 16:59:09 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-12-coding-coding-coding/</guid>
		<description><![CDATA[Today, I like to discuss the single most important skill our testers should master in their career, which is coding. Why coding is important? Because you are SDET, Software Development Engineer in Test, you are software engineer. As a software &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-12-coding-coding-coding/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>Today, I like to discuss the single most important skill our testers should master in their career, which is coding.<br />
 Why coding is important?<br />
 Because you are SDET, Software Development Engineer in Test, you are software engineer. As a software engineer, coding is the task you should do every day, and that is the skill you should get. </p>
<p> You may ask whether writing tests is not important than coding. The reason is that writing tests can help the product improve quality, but it does not grow&#8230;(<a href="http://blogs.msdn.com/b/qingsongyao/archive/2012/02/04/the-journal-of-becoming-senior-tester-12-coding-coding-coding.aspx">read more</a>)<img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/19bdf_aggbug.aspx?PostID=10263946" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/the-journal-of-becoming-senior-tester-12-coding-coding-coding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++98 -&gt; C++11: Pass by value or pass by reference?</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/c98-c11-pass-by-value-or-pass-by-reference/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/c98-c11-pass-by-value-or-pass-by-reference/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 15:59:08 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/c98-c11-pass-by-value-or-pass-by-reference/</guid>
		<description><![CDATA[In GoingNative 2012, there are some discussions on the new coding style for C++11. One interesting thing which is mentioned by Bjarne Stroustrup, Stephan T. Lavavej and Herb Sutter is the most efficient way to pass the argument. In C++98, &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/c98-c11-pass-by-value-or-pass-by-reference/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://channel9.msdn.com/Events/GoingNative/GoingNative-2012" target="_blank">GoingNative 2012</a>, there are some discussions on the new coding style for C++11. One interesting thing which is mentioned by Bjarne Stroustrup, Stephan T. Lavavej and Herb Sutter is the most efficient way to pass the argument.</p>
<p>In C++98, pass by reference is in general more efficient because it saves extra copies (if the copy is expensive, otherwise the extra indirection may hurt the perf instead). However, after the introduction of move semantics in C++11, the story is now a little different (Note that premature optimization doesn’t buy you anything, so the following is to give you a full picture of the new thought introduced in C++11, see the guidelines at the end and use it when appropriated)</p>
<p>Let’s see the following example:    </p>
<p><span>#include</span>&#160;<span>&lt;iostream&gt;</span>     <br /><span>#include</span>&#160;<span>&lt;vector&gt;</span>     </p>
<p><span>using</span>&#160;<span>namespace</span> std;     </p>
<p><span>struct</span> String {     <br />&#160;&#160;&#160; String(<span>const</span>&#160;<span>wchar_t</span> *) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; cout &lt;&lt; <span>&quot;ctor&quot;</span> &lt;&lt; endl;     <br />&#160;&#160;&#160; }     <br />&#160;&#160;&#160; String(<span>const</span> String &amp;) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; cout &lt;&lt; <span>&quot;copy ctor&quot;</span> &lt;&lt; endl;     <br />&#160;&#160;&#160; }     <br />&#160;&#160;&#160; String(String &amp;&amp;) {     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; cout &lt;&lt; <span>&quot;move ctor&quot;</span> &lt;&lt; endl;     <br />&#160;&#160;&#160; }     <br />};     </p>
<p><span>void</span> f1(String s) {     <br />&#160;&#160;&#160; vector&lt;String&gt; v;     <br />&#160;&#160;&#160; v.push_back(std::move(s));     <br />}     <br /><span>void</span> f2(<span>const</span> String &amp;s) {     <br />&#160;&#160;&#160; vector&lt;String&gt; v;     <br />&#160;&#160;&#160; v.push_back(s);     <br />}     </p>
<p><span>void</span> g() {     <br />&#160;&#160;&#160; String s(L<span>&quot;&quot;</span>);     <br />&#160;&#160;&#160; cout &lt;&lt; <span>&quot;f1(s)&quot;</span> &lt;&lt; endl;     <br />&#160;&#160;&#160; f1(s);     <br />&#160;&#160;&#160; cout &lt;&lt; <span>&quot;f1(L&quot;&quot;)&quot;</span> &lt;&lt; endl;     <br />&#160;&#160;&#160; f1(L<span>&quot;&quot;</span>);     <br />&#160;&#160;&#160; cout &lt;&lt; <span>&quot;f2(s)&quot;</span> &lt;&lt; endl;     <br />&#160;&#160;&#160; f2(s);     <br />&#160;&#160;&#160; cout &lt;&lt; <span>&quot;f2(L&quot;&quot;)&quot;</span> &lt;&lt; endl;     <br />&#160;&#160;&#160; f2(L<span>&quot;&quot;</span>);     <br />}     </p>
<p>If you run the code, you will find that ‘f1’ has one less copy ctor call for rvalue argument and the same&#160; amount of copy ctor call for lvalue argument than ‘f2’, which means ‘f1’ is more efficient (assume that move ctor is much cheaper than copy ctor).</p>
<p>The trick is as follows: for lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’.</p>
<p>This means in C++11 we can get better performance by using pass-by-value approach when:</p>
<ol>
<li>The parameter type supports move semantics. </li>
<li>The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage). </li>
<li>Inside the function, the parameter type will be passed to another function or operation which supports both copy and move. </li>
<li>It is common to pass a temporary as the argument. </li>
</ol>
<p>One example for the above guidelines (no copies here!):    </p>
<p><span>// Assume that Matrix has a cheap move ctor</span>     <br />Matrix <span>operator</span>-(Matrix m)     <br />{     <br />&#160;&#160;&#160; <span>// Manipulate m</span>     <br />&#160;&#160;&#160; <span>return</span> std::move(m);     <br />}     </p>
<p>Matrix m = -(a + b);     </p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/f620f_aggbug.aspx?PostID=10263938" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/c98-c11-pass-by-value-or-pass-by-reference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Know Thine Implicit Allocations</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/know-thine-implicit-allocations/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/know-thine-implicit-allocations/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 14:59:07 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/know-thine-implicit-allocations/</guid>
		<description><![CDATA[For .NET 4.5, we’ve invested quite a bit of effort into performance, and in particular for the Task Parallel Library (Joe Hoag wrote a good paper covering some of these improvements).&#160; We focused such effort on TPL because it is &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/know-thine-implicit-allocations/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>For .NET 4.5, we’ve invested quite a bit of effort into performance, and in particular for the Task Parallel Library (Joe Hoag wrote a <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/11/10/10235962.aspx">good paper</a> covering some of these improvements).&#160; We focused such effort on TPL because it is a core component used in async programming and at a foundational level for many libraries and applications.&#160; Small tweaks to the performance characteristics of TPL can thusly have a noticeable impact on the performance of these higher-level systems.</p>
<p>In particular, one of the areas we focused a lot of attention on is memory utilization: how many objects are we allocating, and how big are those objects.&#160; This is primarily due to the subsequent costs of garbage collection necessary to clean up those objects… the less we allocate, the less often the GC will need to run and the shorter it will take to run.&#160; Sometimes these allocations are clearly visible, in that you see a “new” expression in the code.&#160; But often these allocations are hidden.</p>
<p>The Task Parallel Library is written in C#, and C# has some incredibly useful features that help to make programming very productive.&#160; The implementation of those features, however, can sometimes result in allocations of which it’s easy to be blissfully unaware. The developers that wrote the C# compiler have done some great work to make the code generated by the compiler efficient, and they’ve implemented a variety of optimizations to help minimize allocations.&#160; Still, if you care about eking out the best performance possible and minimizing all possible allocations in the process, it can be very useful to understand the intricacies of the code the compiler generates such that you can bend the behavior better to your will.</p>
<p>In this post, I’ll highlight some of these behaviors we came across during our performance push for TPL, and I’ll demonstrate how you can work around them to help get the best performance possible.</p>
<p><em>WARNING: Everything I’m discussing in this post is an implementation detail based on one version of the C# compiler (that in .NET 4.5 Developer Preview).&#160; It’s certainly possible that these characteristics may change in a future release, as the C# compiler gets more and more optimizations added to it.</em></p>
<p><strong>Closure and Delegate Allocations</strong></p>
<p>Lambdas and anonymous methods are very powerful features that save the developer from having to write a lot of boilerplate code.&#160; Consider the Framework’s ThreadPool.QueueUserWorkItem method:</p>
<blockquote><p>public static bool ThreadPool(WaitCallback callback);</p>
</blockquote>
<p>With lambdas/anonymous methods, I can write code like the following (I’m not recommending this as an approach towards writing to a stream asynchronously, rather just using it as an example of passing state around):</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte [] data)       <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(delegate        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; stream.Write(data, 0, data.Length);        <br />&#160;&#160;&#160; });        <br />}</p>
</blockquote>
<p>Before lambdas/anonymous methods were introduced, C# developers wanting to call a method that accepted a delegate would typically need to define a class to store their state, add a method to that class to do their processing, and then create a delegate that pointed to that method on that state instance, e.g.</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte [] data)       <br />{        <br />&#160;&#160;&#160; var state = new WriteOnPoolState();        <br />&#160;&#160;&#160; state.stream = stream;        <br />&#160;&#160;&#160; state.data = data;        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(new WaitCallback(state.Invoke));        <br />}        </p>
<p>private sealed class WriteOnPoolState        <br />{        <br />&#160;&#160;&#160; public Stream stream;        <br />&#160;&#160;&#160; public byte [] data;        </p>
<p>&#160;&#160;&#160; public void Invoke(object ignored)        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; stream.Write(data, 0, data.Length);        <br />&#160;&#160;&#160; }&#160;&#160;&#160; <br />}</p>
</blockquote>
<p>Now in C#, when you use an anonymous method or lambda, the compiler actually ends up generating code almost identical to this on your behalf so that you no longer have to do so manually.&#160; Here’s a decompiled version of what gets generated for my previous example that used an anonymous method:</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; var locals2 = new DisplayClass1();        <br />&#160;&#160;&#160; locals2.stream = stream;        <br />&#160;&#160;&#160; locals2.data = data;        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; new WaitCallback(locals2.&lt;WriteOnPool&gt;b__0));        <br />}        </p>
<p>[CompilerGenerated]        <br />private sealed class DisplayClass1        <br />{        <br />&#160;&#160;&#160; public Stream stream;        <br />&#160;&#160;&#160; public byte[] data;        </p>
<p>&#160;&#160;&#160; public void &lt;WriteOnPool&gt;b__0(object param0)        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; this.stream.Write(this.data, 0, this.data.Length);        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>The important thing to note here is that there are two allocations involved: one for the closure object (in my hand-written version, WriteOnPoolState, and in the compiler-generated version, DisplayClass1), and one for the delegate to the method on the closure.&#160; For a method that simply accepts a delegate, there’s really no way around two allocations: the delegate object needs to be allocated, and it needs to target an object containing the state (assuming that state needs to change for each invocation, this state object also needs to be allocated for each call).</p>
<p>Luckily, many library methods that accept delegates recognize the need to pass state into the method, and thus accept not only a delegate object but also a state object that will be passed into the delegate when it’s invoked.&#160; In fact, ThreadPool has an additional overload of QueueUserWorkItem that accepts both, and the overload we’ve been using above just passes in null; that’s why the WriteOnPoolState.Invoke and DisplayClass1.&lt;WriteOnPool&gt;b__0 methods both accept an object parameter, so as to match the required signature of a WaitCallback, which accepts an object parameter.</p>
<p>This pattern of accepting an object state is useful because it allows us to avoid allocations.&#160; The reason we need to allocate a delegate each time is because its Target needs to point to the right “this” object.&#160; But if there is no “this”, i.e. we’re dealing with a static method, then we can reuse the same delegate object over and over, simply passing in different state as a parameter each time.&#160; To achieve that, we can rewrite our WriteOnPool example as follows:</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte [] data)       <br />{        <br />&#160;&#160;&#160; var state = new WriteOnPoolState();        <br />&#160;&#160;&#160; state.stream = stream;        <br />&#160;&#160;&#160; state.data = data;        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(s_writeOnPoolBody, state);        <br />}        </p>
<p>private static readonly WaitCallback s_writeOnPoolBody =&#160; <br />&#160;&#160;&#160; new WaitCallback(WriteOnPoolBody);        </p>
<p>private static void WriteOnPoolBody(object state)        <br />{        <br />&#160;&#160;&#160; var poolState = (WriteOnPoolState)state;        <br />&#160;&#160;&#160; poolState.stream.Write(poolState.data, 0, poolState.data.Length);        <br />}&#160;&#160;&#160; </p>
<p>private sealed class WriteOnPoolState        <br />{        <br />&#160;&#160;&#160; public Stream stream;        <br />&#160;&#160;&#160; public byte [] data;         <br />}</p>
</blockquote>
<p>We’re now still allocating a delegate and a state object, but we allocate the delegate only once and cache it into a static field.&#160; On each call to WriteOnPool, then, we only allocate once, for the WriteOnPoolState object, saving half of the allocations.</p>
<p>As it turns out, the C# compiler has smarts to provide similar savings when using lambdas and anonymous methods.&#160; Let’s say I instead rewrite my implementation as follows, still using a lambda, but now passing in my state via the object state parameter and ensuring that my lambda doesn’t close over anything (I’m also using a Tuple&lt;,&gt; for conciseness to avoid needing to define my own custom state type):</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(state =&gt;        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; var poolState = (Tuple&lt;Stream,byte[]&gt;)state;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; poolState.Item1.Write(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; poolState.Item2, 0, poolState.Item2.Length);        <br />&#160;&#160;&#160; }, Tuple.Create(stream, data));        <br />}</p>
</blockquote>
<p>This now results in the following code from the compiler:</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; if (CachedAnonymousMethodDelegate1 == null)        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; CachedAnonymousMethodDelegate1 =&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; new WaitCallback(Program.&lt;WriteOnPool&gt;b__0);        </p>
<p>&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; CachedAnonymousMethodDelegate1,&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Tuple.Create&lt;Stream, byte[]&gt;(stream, data));        <br />}        </p>
<p>[CompilerGenerated]        <br />private static WaitCallback CachedAnonymousMethodDelegate1;        </p>
<p>[CompilerGenerated]        <br />private static void &lt;WriteOnPool&gt;b__0(object state)        <br />{        <br />&#160;&#160;&#160; Tuple&lt;Stream, byte[]&gt; poolState = (Tuple&lt;Stream, byte[]&gt;) state;        <br />&#160;&#160;&#160; poolState.Item1.Write(poolState.Item2, 0, poolState.Item2.Length);        <br />}</p>
</blockquote>
<p>Note that the compiler has done something very similar to what we did manually, creating a static field to cache the delegate.&#160; The primary difference between what we manually wrote and what the compiler generated is the compiler is lazily instantiating the delegate on first use, rather than doing it in the static constructor as we did by using a field initializer.&#160; So, we get to have our cake and eat most of it, too… we still get most of the convenience of lambdas while getting the efficiency benefits of the delegate caching.&#160; And, of course, if the state I’m trying to pass in is already a single object, that object can be passed in directly (rather than wrapping it in a state object), bringing us down to zero additional allocations.</p>
<p><strong>When Automatic Caching Fails</strong></p>
<p>This is all well and good, but it can lead us into a fall sense of security, as there are times when the compiler will not cache the delegate.</p>
<p>One prime example is that the compiler won’t cache the delegate when a method group is used rather than a lambda / anonymous method, e.g.</p>
<blockquote><p>public void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; WriteOnPoolCallback,&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Tuple.Create(stream, data));        <br />}        </p>
<p>private static void WriteOnPoolCallback(object state)        <br />{        <br />&#160;&#160;&#160; var poolState = (Tuple&lt;Stream, byte[]&gt;)state;        <br />&#160;&#160;&#160; poolState.Item1.Write(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; poolState.Item2, 0, poolState.Item2.Length);        <br />}</p>
</blockquote>
<p>Some developers prefer the explicitness of having a named method, but the compiler currently generates code like the following for this:</p>
<blockquote><p>public void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; new WaitCallback(Program.WriteOnPoolCallback),&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Tuple.Create&lt;Stream, byte[]&gt;(stream, data));        <br />}        </p>
<p>private static void WriteOnPoolCallback(object state)        <br />{        <br />&#160;&#160;&#160; Tuple&lt;Stream, byte[]&gt; poolState = (Tuple&lt;Stream, byte[]&gt;) state;        <br />&#160;&#160;&#160; poolState.Item1.Write(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; poolState.Item2, 0, poolState.Item2.Length);        <br />}</p>
</blockquote>
<p>Notice the delegate allocation on each call.&#160; In such a situation, you might prefer to do the caching manually, or to revert to using a lambda or anonymous method.</p>
<p>Another example where the compiler won’t cache is when dealing with certain patterns of generics usage.&#160; Consider the following variation.&#160; Here rather than writing a byte[] to the stream, I’m using a BinaryFormatter to serialize an arbitrary generic T to the stream:</p>
<blockquote><p>public void WriteOnPool&lt;T&gt;(Stream stream, T data)       <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(state =&gt;        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; var poolState = (Tuple&lt;Stream, T&gt;)state;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; new BinaryFormatter().Serialize(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; poolState.Item1, poolState.Item2);        <br />&#160;&#160;&#160; }, Tuple.Create(stream, data));        <br />}</p>
</blockquote>
<p>The compiler will currently not cache a delegate for this case, instead generating code like the following:</p>
<blockquote><p>public void WriteOnPool&lt;T&gt;(Stream stream, T data)       <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; new WaitCallback(Program.&lt;WriteOnPool&gt;b__0&lt;T&gt;),&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Tuple.Create&lt;Stream, T&gt;(stream, data));        <br />}        </p>
<p>[CompilerGenerated]        <br />private static void &lt;WriteOnPool&gt;b__0&lt;T&gt;(object state)        <br />{        <br />&#160;&#160;&#160; Tuple&lt;Stream, T&gt; poolState = (Tuple&lt;Stream, T&gt;) state;        <br />&#160;&#160;&#160; new BinaryFormatter().Serialize(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; poolState.Item1, poolState.Item2);        <br />}</p>
</blockquote>
<p>A little thought reveals why the compiler doesn’t use the same caching pattern it does elsewhere.&#160; Notice that the method generated for the lambda is a generic method, and for it to be cached, it would need to be cached in a static field for each T that might exist… that’s not possible in a field on a class that’s not parameterized on the same generic type parameter.&#160; We can manually work around this by caching the delegate manually: we just need to create a generic type to contain the field:</p>
<blockquote><p>public void WriteOnPool&lt;T&gt;(Stream stream, T data)       <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; DelegateCache&lt;T&gt;.s_writeOnPoolCallback,&#160; <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Tuple.Create(stream, data));        <br />}        </p>
<p>private static class DelegateCache&lt;T&gt;        <br />{        <br />&#160;&#160;&#160; internal static readonly WaitCallback s_writeOnPoolCallback =         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; state =&gt;        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; var poolState = (Tuple&lt;Stream, T&gt;)state;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; new BinaryFormatter().Serialize(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; poolState.Item1, poolState.Item2);        <br />&#160;&#160;&#160; };        <br />}</p>
</blockquote>
<p>Theoretically, the compiler could perform a similar transformation, for example creating one such generic cache per assembly and per generic arity, but it currently does not do so.</p>
<p>Another common case where such lack-of-caching goes unnoticed is when dealing with instance methods and data.&#160; Consider the following similar code:</p>
<blockquote><p>internal class MyCoolType       <br />{        <br />&#160;&#160;&#160; private Stream m_stream;        <br />&#160;&#160;&#160; private byte[] m_data;        </p>
<p>&#160;&#160;&#160; public void WriteOnPool()        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(delegate        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_stream.Write(m_data, 0, m_data.Length);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; });        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>This example will generate code like the following:</p>
<blockquote><p>internal class MyCoolType       <br />{        <br />&#160;&#160;&#160; private Stream m_stream;        <br />&#160;&#160;&#160; private byte[] m_data;        </p>
<p>&#160;&#160;&#160; public void WriteOnPool()        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; new WaitCallback(this.&lt;WriteOnPool&gt;b__0));        <br />&#160;&#160;&#160; }        </p>
<p>&#160;&#160;&#160; [CompilerGenerated]        <br />&#160;&#160;&#160; private void &lt;WriteOnPool&gt;b__0(object param0)        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; this.m_stream.Write(this.m_data, 0, this.m_data.Length);        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>The anonymous method refers implicitly to ‘this’, closing over member fields of the current instance.&#160; As such, the compiler generates an instance method for that anonymous method, and then because it needs a delegate instance with a Target set to this particular instance, each call to WriteOnPool will end up allocating a new delegate (it would be possible for the compiler to have added an instance field in order to cache this delegate, but that could have negative consequences, such as making each instance of this class bigger, and the compiler can’t easily reason about the global impacts of such caching).&#160; Of course, we have knowledge that the compiler doesn’t have: we know that we can use the object state parameter in order to pass data into the method.&#160; So, we could instead write our code as:</p>
<blockquote><p>internal class MyCoolType       <br />{        <br />&#160;&#160;&#160; private Stream m_stream;        <br />&#160;&#160;&#160; private byte[] m_data;        </p>
<p>&#160;&#160;&#160; public void WriteOnPool()        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(state =&gt;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; MyCoolType mct = (MyCoolType)state;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; mct.m_stream.Write(mct.m_data, 0, mct.m_data.Length);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }, this);        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>or as:</p>
<blockquote><p>internal class MyCoolType       <br />{        <br />&#160;&#160;&#160; private Stream m_stream;        <br />&#160;&#160;&#160; private byte[] m_data;        </p>
<p>&#160;&#160;&#160; public void WriteOnPool()        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; state =&gt; ((MyCoolType)state).Write(), this);        <br />&#160;&#160;&#160; }        </p>
<p>&#160;&#160;&#160; private void Write()        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_stream.Write(m_data, 0, m_data.Length);        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>and in both cases, we’ll get the caching we expect.&#160; This is an example of the case I referred to earlier, where we already have a single state object to pass in, and thus we don’t need to allocate a wrapper (e.g. a tuple), which means there are no additional allocations here.</p>
<p><strong>Closures and Fast Paths</strong></p>
<p>There are other times when the compiler isn’t yet quite as clever as we might expect it to be.&#160; One case in which this comes up is when using “fast paths” to optimize frequented code paths.&#160; Consider a change to our WriteOnPool method: the goal of the method isn’t to queue a work item to do the write, but rather to ensure the write happens on a ThreadPool thread; as such, if we’re already on a ThreadPool thread, we can avoid the queueing operation:</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; if (Thread.CurrentThread.IsThreadPoolThread)        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; stream.Write(data, 0, data.Length);        <br />&#160;&#160;&#160; }        <br />&#160;&#160;&#160; else        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(delegate        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; stream.Write(data, 0, data.Length);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; });        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>I might then expect that my “fast path” that occurs when I’m already on a ThreadPool thread won’t involve any additional allocations for the closure/delegate used on the “slow path.”&#160; But such an expectation is based on an assumption that the compiler allocates the closure in the “else” block.&#160; In fact, the compiler currently generates code like the following:</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; var locals3 = new DisplayClass2();        <br />&#160;&#160;&#160; locals3.stream = stream;        <br />&#160;&#160;&#160; locals3.data = data;        <br />&#160;&#160;&#160; if (Thread.CurrentThread.IsThreadPoolThread)        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; locals3.stream.Write(locals3.data, 0, locals3.data.Length);        <br />&#160;&#160;&#160; }        <br />&#160;&#160;&#160; else        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; new WaitCallback(locals3.&lt;WriteOnPool&gt;b__0));        <br />&#160;&#160;&#160; }        <br />}        </p>
<p>[CompilerGenerated]        <br />private sealed class DisplayClass2        <br />{        <br />&#160;&#160;&#160; public byte[] data;        <br />&#160;&#160;&#160; public Stream stream;        </p>
<p>&#160;&#160;&#160; public void &lt;WriteOnPool&gt;b__0(object param0)        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; this.stream.Write(this.data, 0, this.data.Length);        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>Note that the “locals” that are captured into the closure actually live on the heap-allocated closure object and are accessed there, even from code paths that don’t use the closure. Thus, the closure object gets allocated at the beginning of the method.&#160; This means that we’re still paying for the closure object even if we only take the “fast path” that doesn’t actually require it.&#160; If we instead separate out the closure into a separate method, we can eliminate that allocation from the fast path, e.g.</p>
<blockquote><p>public static void WriteOnPool(Stream stream, byte[] data)       <br />{        <br />&#160;&#160;&#160; if (Thread.CurrentThread.IsThreadPoolThread)        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; stream.Write(data, 0, data.Length);        <br />&#160;&#160;&#160; }        <br />&#160;&#160;&#160; else WriteOnPoolPrivate(stream, data);        <br />}        </p>
<p>private static void WriteOnPoolPrivate(Stream stream, byte[] data)        <br />{        <br />&#160;&#160;&#160; ThreadPool.QueueUserWorkItem(delegate        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; stream.Write(data, 0, data.Length);        <br />&#160;&#160;&#160; });        <br />}</p>
</blockquote>
<p><strong>Moral of the Story</strong></p>
<p>C# and Visual Basic provide some very powerful language features for you to use, and they typically do a very good job of implementing what’s under the hood.&#160; But if your particular scenario demands pedal-to-the-medal performance, you need to at least understand what’s happening on your behalf so that you can better influence it as necessary.&#160; Get friendly with tools like .NET Reflector that help you to see what’s actually going on in the compiled code. </p>
<p>If you do use a decompiler for this kind of analysis, be certain that it’s not sweeping such details under the rug for you.&#160; A primary use of these decompilers is to get high-quality source generated from low-level IL, and thus decompilers will often attempt to decompile back to source that employs anonymous methods and lambdas and the like.&#160; If instead your goal is to get a closer view on what’s actually happening, try tweaking the settings of the decompiler to minimize what language features it reverse engineers to, e.g. in .NET Reflector, you can change the “optimization level” so that it shows you code like what I’ve shown in this post, rather than hiding these allocations behind a lambda.</p>
<p>One last thought. Throughout this post, I kept harping on the number of allocations, but I didn’t spend much time on the size of the allocations. The number of allocations is only one aspect to consider. We also want to consider the amount of memory being allocated, as that will factor into how often the garbage collector runs. There are lots of tools to help determine the amount of memory .NET applications are allocating, but when prototyping I often find myself using a function like the following to give me a rough sense for what something is costing:</p>
<blockquote><p>public static class MemoryAnalysis       <br />{        <br />&#160;&#160;&#160; public static long AveragedApproximateSize&lt;T&gt;(Func&lt;T&gt; rootGenerator) where T : class        <br />&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; const int iters = 1000000;        </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; var items = new object[iters];        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; long start = GC.GetTotalMemory(true);        </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; for (int i = 0; i &lt; items.Length; i++)         <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; items[i] = rootGenerator();        </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; long end = GC.GetTotalMemory(true);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; GC.KeepAlive(items);        </p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160; return (long)Math.Round((end &#8211; start) / (double)iters);        <br />&#160;&#160;&#160; }        <br />}</p>
</blockquote>
<p>When I then run:</p>
<blockquote><p>static void Main()       <br />{        <br />&#160;&#160;&#160; Console.WriteLine(MemoryAnalysis.AveragedApproximateSize(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; () =&gt; new WriteOnPoolState()));        <br />&#160;&#160;&#160; Console.WriteLine(MemoryAnalysis.AveragedApproximateSize(        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; () =&gt; new WaitCallback(WriteOnPoolBody)));        <br />}</p>
</blockquote>
<p>I see that WriteOnPoolState is 16 bytes and WaitCallback is 32 bytes (in a 32-bit compilation), which makes logical sense if you add up the size of the fields on the objects plus the object headers. That means that for the examples where we were able to eliminate the delegate allocation by caching the delegate in a static, we were not only saving half the number of allocations, but we were also saving 2/3<sup>rds</sup> of the memory being allocated.</p>
<p>Happy optimizing.</p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/11e91_aggbug.aspx?PostID=10263921" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/know-thine-implicit-allocations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning the Building Blocks of Life through Lego</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-4/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-4/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 13:59:11 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-4/</guid>
		<description><![CDATA[Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-4/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><em>Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. </em><img style="border-bottom-style: none;border-left-style: none;border-top-style: none;border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/237cc_0410.wlEmoticon_2D00_smile_5F00_72E043B2.png" /></p>
<p>First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this post I’m focusing on the building of knowledge and awareness through hands on learning.</p>
<p>Second, I’m a huge Lego fan! One of my childhood passions has been totally revised by having two young daughters. If you doubt me, here’s an excerpt from a letter my parents received almost 30 years ago…</p>
<blockquote><p><i>Thank you for your nice letter and for sending the newspaper article and photographs relating to your son, Kevin’s, “Transformer” creations. We are glad to hear that Kevin enjoys building with LEGO® products. He certainly seems to have very creative and innovative talent with the models he has made….We will be happy to post the newspaper article and photographs our Company bulletin board for our employees and visitors to enjoy and admire.</i></p>
</blockquote>
<p>Now, as a youngster, I was completely amazed to receive this letter (plus they threw in a gift right before my birthday too!), but looking back, it’s great to see how this remarkable response has really stuck with me over the years. In the pre-internet information age, there was no such thing as an instant response. Someone carved out a little time in their busy day to personally mail a note back.</p>
<p>Finally, circling back to building knowledge and awareness, I’m really excited to see this year Lego introduced a line of products specifically targeted at girls – LEGO® Friends. I’m all for Star Wars, Harry Potter, etc. but right now I’m pretty sure my “dolls rule the world” daughters will be really excited to play with these. I can hardly wait to see their imaginations run wild. Easily hours of enjoyment for the whole family!</p>
<p>&#8211;Kevin</p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/237cc_aggbug.aspx?PostID=10263877" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning the Building Blocks of Life through Lego</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-3/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-3/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 12:59:07 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-3/</guid>
		<description><![CDATA[Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-3/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><em>Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. </em><img style="border-bottom-style: none;border-left-style: none;border-top-style: none;border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/5b9fd_0410.wlEmoticon_2D00_smile_5F00_72E043B2.png" /></p>
<p>First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this post I’m focusing on the building of knowledge and awareness through hands on learning.</p>
<p>Second, I’m a huge Lego fan! One of my childhood passions has been totally revised by having two young daughters. If you doubt me, here’s an excerpt from a letter my parents received almost 30 years ago…</p>
<blockquote><p><i>Thank you for your nice letter and for sending the newspaper article and photographs relating to your son, Kevin’s, “Transformer” creations. We are glad to hear that Kevin enjoys building with LEGO® products. He certainly seems to have very creative and innovative talent with the models he has made….We will be happy to post the newspaper article and photographs our Company bulletin board for our employees and visitors to enjoy and admire.</i></p>
</blockquote>
<p>Now, as a youngster, I was completely amazed to receive this letter (plus they threw in a gift right before my birthday too!), but looking back, it’s great to see how this remarkable response has really stuck with me over the years. In the pre-internet information age, there was no such thing as an instant response. Someone carved out a little time in their busy day to personally mail a note back.</p>
<p>Finally, circling back to building knowledge and awareness, I’m really excited to see this year Lego introduced a line of products specifically targeted at girls – LEGO® Friends. I’m all for Star Wars, Harry Potter, etc. but right now I’m pretty sure my “dolls rule the world” daughters will be really excited to play with these. I can hardly wait to see their imaginations run wild. Easily hours of enjoyment for the whole family!</p>
<p>&#8211;Kevin</p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/5b9fd_aggbug.aspx?PostID=10263877" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning the Building Blocks of Life through Lego</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-2/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-2/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 11:59:14 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-2/</guid>
		<description><![CDATA[Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-2/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><em>Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. </em><img style="border-bottom-style: none;border-left-style: none;border-top-style: none;border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/e83df_0410.wlEmoticon_2D00_smile_5F00_72E043B2.png" /></p>
<p>First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this post I’m focusing on the building of knowledge and awareness through hands on learning.</p>
<p>Second, I’m a huge Lego fan! One of my childhood passions has been totally revised by having two young daughters. If you doubt me, here’s an excerpt from a letter my parents received almost 30 years ago…</p>
<blockquote><p><i>Thank you for your nice letter and for sending the newspaper article and photographs relating to your son, Kevin’s, “Transformer” creations. We are glad to hear that Kevin enjoys building with LEGO® products. He certainly seems to have very creative and innovative talent with the models he has made….We will be happy to post the newspaper article and photographs our Company bulletin board for our employees and visitors to enjoy and admire.</i></p>
</blockquote>
<p>Now, as a youngster, I was completely amazed to receive this letter (plus they threw in a gift right before my birthday too!), but looking back, it’s great to see how this remarkable response has really stuck with me over the years. In the pre-internet information age, there was no such thing as an instant response. Someone carved out a little time in their busy day to personally mail a note back.</p>
<p>Finally, circling back to building knowledge and awareness, I’m really excited to see this year Lego introduced a line of products specifically targeted at girls – LEGO® Friends. I’m all for Star Wars, Harry Potter, etc. but right now I’m pretty sure my “dolls rule the world” daughters will be really excited to play with these. I can hardly wait to see their imaginations run wild. Easily hours of enjoyment for the whole family!</p>
<p>&#8211;Kevin</p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/e83df_aggbug.aspx?PostID=10263877" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning the Building Blocks of Life through Lego</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 10:59:13 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego/</guid>
		<description><![CDATA[Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><em>Periodically, I’ll post a non-work related blog leaning toward more personal observations. I hope you still enjoy the read. </em><img style="border-bottom-style: none;border-left-style: none;border-top-style: none;border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/aa8a4_0410.wlEmoticon_2D00_smile_5F00_72E043B2.png" /></p>
<p>First off, yes, I know the building blocks of life are more biological in nature (cells, genes, etc.). But, in this post I’m focusing on the building of knowledge and awareness through hands on learning.</p>
<p>Second, I’m a huge Lego fan! One of my childhood passions has been totally revised by having two young daughters. If you doubt me, here’s an excerpt from a letter my parents received almost 30 years ago…</p>
<blockquote><p><i>Thank you for your nice letter and for sending the newspaper article and photographs relating to your son, Kevin’s, “Transformer” creations. We are glad to hear that Kevin enjoys building with LEGO® products. He certainly seems to have very creative and innovative talent with the models he has made….We will be happy to post the newspaper article and photographs our Company bulletin board for our employees and visitors to enjoy and admire.</i></p>
</blockquote>
<p>Now, as a youngster, I was completely amazed to receive this letter (plus they threw in a gift right before my birthday too!), but looking back, it’s great to see how this remarkable response has really stuck with me over the years. In the pre-internet information age, there was no such thing as an instant response. Someone carved out a little time in their busy day to personally mail a note back.</p>
<p>Finally, circling back to building knowledge and awareness, I’m really excited to see this year Lego introduced a line of products specifically targeted at girls – LEGO® Friends. I’m all for Star Wars, Harry Potter, etc. but right now I’m pretty sure my “dolls rule the world” daughters will be really excited to play with these. I can hardly wait to see their imaginations run wild. Easily hours of enjoyment for the whole family!</p>
<p>&#8211;Kevin</p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/aa8a4_aggbug.aspx?PostID=10263877" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/learning-the-building-blocks-of-life-through-lego/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CQRS with OData and Actions?</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-3/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-3/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 09:59:13 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-3/</guid>
		<description><![CDATA[I love the Actions feature in OData – which is hardly surprising given I was one of its designers.&#160; Here’s the main reason why I love it: Actions allow you move from a CRUD architecture style, where you query and &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-3/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>I love the Actions feature in OData – which is hardly surprising given I was one of its designers.&#160; </p>
<p>Here’s the main reason why I love it: Actions allow you move from a CRUD architecture style, where you query and modify data using the same model, to an architectural style where you have a clear separation between the model used to query and the model used to update. To me this feels a lot like <a href="http://codebetter.com/gregyoung/">Greg Young</a>’s baby CQRS, or <a href="http://martinfowler.com/bliki/CQRS.html">Command Query Responsibility Segregation</a>. </p>
<p>I’ll admit I’m taking some liberties here because these two models are actually ‘merged’ into a single metadata document ($metadata) that describes them both, and you can share types between these two models… however this feels insignificant because the key benefits remain.</p>
<p>Why would you want to move from a CRUD style application to a CQRS style one?</p>
<p>Let’s look at a simple scenario, imagine you have Products that look like this:</p>
<p>public class Product      <br />{       <br />&#160;&#160; public int ID {get;set;}       <br />&#160;&#160; public string Name {get;set;}       <br />&#160;&#160; public Decimal Cost {get;set;}       <br />&#160;&#160; public Decimal Price {get;set;}       <br />}</p>
<p>And imagine you want to Discount Marmite (a product in your catalog) by 15%. Today using the CRUD style, the default in OData before Actions, there is only one option: you PUT a new version of the Marmite resource with the new Price to the URL that represents Marmite, i.e. something like this:</p>
<p>POST ~/Products(15) HTTP/1.1      <br />Content-Type: application/json       </p>
<p>{       <br />&#160;&#160; // abbreviated for readability        <br />&#160;&#160; “ID”: 15,       <br />&#160;&#160; “Name”: “Marmite”,       <br />&#160;&#160; “Cost”: 3.50,       <br />&#160;&#160; “Price”: 4.25&#160;&#160;&#160; // ( – 15%)&#160; <br />}</p>
<p>Notice to support this you have to allow PUT for Products. And this has some real issues:</p>
<ul>
<li>People can now make changes that we don’t necessarily want to allow, i.e. modifying the Name &amp; Cost or changing the Price too much.
<ul>
<li>Basically “Update Product” is NOT the same as “Discount Product”. </li>
</ul>
</li>
<li>When a change comes through we don’t actually know it is a Discount. It just looks like an attempt to update a Product. </li>
<li>If you need information that is not part of Product to perform a Discount (perhaps a justification) there is no where to put that information. </li>
</ul>
<p>More generally the CRUD model is painful because:</p>
<ul>
<li>If you want to update lots of resources simultaneously, imagine for example that you want to discount every product in a particular category, you first have to retrieve every product in that category, and then you have to do a PUT for each of them. This of course introduces a lot of unnecessary latency and introduces consistency challenges (it is hard to maintain a transaction boundary across requests &amp; it the longer the ‘transaction’ lasts the more likely a concurrency check will fail). </li>
<li>If you want to update something you have to allow it to be read somewhere. </li>
</ul>
<p>Back to our scenario, it would be much better to disable PUT completely and create a Discount action, and advertise it’s availability in the Marmite resource (to keep your system as Hypermedia driven as possible):</p>
<p>{      <br />&#160; “__metadata”: {       <br />&#160;&#160;&#160;&#160; // abbreviated for simplicity       <br />&#160;&#160;&#160;&#160; “Actions”: {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; “#MyActions.Discount”: [{ “title”: “Discount Marmite”, “target”: “Products(15)/Discount”}]       <br />&#160;&#160;&#160;&#160; }       <br />&#160; },&#160; <br />&#160; “ID”: 15,       <br />&#160; “Name”: “Marmite”,       <br />&#160; “Cost”: 3.50,       <br />&#160; “Price”: 5.00       <br />}</p>
<p>The name of the Action (i.e. #MyActions.Discount) is an ‘anchor’ into the metadata document that can be found at ~/$metadata that says you need to provide a percentage.</p>
<p>POST ~/Products(15)/Discount HTTP/1.1      <br />Content-Type: application/json</p>
<p>{      <br />&#160;&#160;&#160; “percentage”: 15       <br />}</p>
<p>This is much better. Notice this doesn’t allow me to modify the Cost or the Name, and indeed can easily be validated to make sure the percentage is within an acceptable range, and it is semantically much clearer what is happening.</p>
<p>In fact by moving from a CRUD style architecture to one inspired by CQRS but based on actions you can:</p>
<ul>
<li>Give targeted update capabilities that:
<ul>
<li>Allow only certain parts of the ‘Read’ model to be modified. </li>
<li>Allow things that are not even in the ‘Read’ model to be modified or provided if needed. </li>
</ul>
</li>
<li>Selectively give users permissions to only the ‘Actions’ or Commands they need. </li>
<li>Log every Action and replay them at a later date to rebuild your data (i.e. Event Sourcing). </li>
<li>Capture what is requested (i.e. Discount the product) and respond immediately before the change has actually been made, safe in the knowledge you will eventually process the request and achieve “Eventual Consistency”. </li>
<li>Capture more information about what is happening (i.e. User X discounted Marmite by 15% is much better than User X updated Marmite). </li>
<li>Create Actions that manipulate a lot of entities simultaneously (i.e. POST ~/Categories(‘Yeast Spreads’)/Products/Discount…) </li>
</ul>
<p>Of course simply separating the read/write models in OData doesn’t give you all of these advantages immediately, but at least it creates a foundation that can scale to support things like Event Sourcing or Eventual Consistency later if required. </p>
<p>Some of you may be thinking you can achieve many of these goals by having a more granular model that makes things like “Discount” a resource, and that would be true. However for most people using OData that way of thinking is foreign and more importantly the EDM foundations of OData get in the way a little too. So for me Actions seems like the right approach in OData.</p>
<p>I love this.    <br />But what do you think?     <br />-<a href="http://twitter.com/adjames">Alex</a></p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/c109c_aggbug.aspx?PostID=10263906" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CQRS with OData and Actions?</title>
		<link>http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-2/</link>
		<comments>http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-2/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 08:59:12 +0000</pubDate>
		<dc:creator>Code Monkey</dc:creator>
				<category><![CDATA[MSDN Blog]]></category>

		<guid isPermaLink="false">http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-2/</guid>
		<description><![CDATA[I love the Actions feature in OData – which is hardly surprising given I was one of its designers.&#160; Here’s the main reason why I love it: Actions allow you move from a CRUD architecture style, where you query and &#8230;<p class="read-more"><a href="http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-2/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>I love the Actions feature in OData – which is hardly surprising given I was one of its designers.&#160; </p>
<p>Here’s the main reason why I love it: Actions allow you move from a CRUD architecture style, where you query and modify data using the same model, to an architectural style where you have a clear separation between the model used to query and the model used to update. To me this feels a lot like <a href="http://codebetter.com/gregyoung/">Greg Young</a>’s baby CQRS, or <a href="http://martinfowler.com/bliki/CQRS.html">Command Query Responsibility Segregation</a>. </p>
<p>I’ll admit I’m taking some liberties here because these two models are actually ‘merged’ into a single metadata document ($metadata) that describes them both, and you can share types between these two models… however this feels insignificant because the key benefits remain.</p>
<p>Why would you want to move from a CRUD style application to a CQRS style one?</p>
<p>Let’s look at a simple scenario, imagine you have Products that look like this:</p>
<p>public class Product      <br />{       <br />&#160;&#160; public int ID {get;set;}       <br />&#160;&#160; public string Name {get;set;}       <br />&#160;&#160; public Decimal Cost {get;set;}       <br />&#160;&#160; public Decimal Price {get;set;}       <br />}</p>
<p>And imagine you want to Discount Marmite (a product in your catalog) by 15%. Today using the CRUD style, the default in OData before Actions, there is only one option: you PUT a new version of the Marmite resource with the new Price to the URL that represents Marmite, i.e. something like this:</p>
<p>POST ~/Products(15) HTTP/1.1      <br />Content-Type: application/json       </p>
<p>{       <br />&#160;&#160; // abbreviated for readability        <br />&#160;&#160; “ID”: 15,       <br />&#160;&#160; “Name”: “Marmite”,       <br />&#160;&#160; “Cost”: 3.50,       <br />&#160;&#160; “Price”: 4.25&#160;&#160;&#160; // ( – 15%)&#160; <br />}</p>
<p>Notice to support this you have to allow PUT for Products. And this has some real issues:</p>
<ul>
<li>People can now make changes that we don’t necessarily want to allow, i.e. modifying the Name &amp; Cost or changing the Price too much.
<ul>
<li>Basically “Update Product” is NOT the same as “Discount Product”. </li>
</ul>
</li>
<li>When a change comes through we don’t actually know it is a Discount. It just looks like an attempt to update a Product. </li>
<li>If you need information that is not part of Product to perform a Discount (perhaps a justification) there is no where to put that information. </li>
</ul>
<p>More generally the CRUD model is painful because:</p>
<ul>
<li>If you want to update lots of resources simultaneously, imagine for example that you want to discount every product in a particular category, you first have to retrieve every product in that category, and then you have to do a PUT for each of them. This of course introduces a lot of unnecessary latency and introduces consistency challenges (it is hard to maintain a transaction boundary across requests &amp; it the longer the ‘transaction’ lasts the more likely a concurrency check will fail). </li>
<li>If you want to update something you have to allow it to be read somewhere. </li>
</ul>
<p>Back to our scenario, it would be much better to disable PUT completely and create a Discount action, and advertise it’s availability in the Marmite resource (to keep your system as Hypermedia driven as possible):</p>
<p>{      <br />&#160; “__metadata”: {       <br />&#160;&#160;&#160;&#160; // abbreviated for simplicity       <br />&#160;&#160;&#160;&#160; “Actions”: {       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; “#MyActions.Discount”: [{ “title”: “Discount Marmite”, “target”: “Products(15)/Discount”}]       <br />&#160;&#160;&#160;&#160; }       <br />&#160; },&#160; <br />&#160; “ID”: 15,       <br />&#160; “Name”: “Marmite”,       <br />&#160; “Cost”: 3.50,       <br />&#160; “Price”: 5.00       <br />}</p>
<p>The name of the Action (i.e. #MyActions.Discount) is an ‘anchor’ into the metadata document that can be found at ~/$metadata that says you need to provide a percentage.</p>
<p>POST ~/Products(15)/Discount HTTP/1.1      <br />Content-Type: application/json</p>
<p>{      <br />&#160;&#160;&#160; “percentage”: 15       <br />}</p>
<p>This is much better. Notice this doesn’t allow me to modify the Cost or the Name, and indeed can easily be validated to make sure the percentage is within an acceptable range, and it is semantically much clearer what is happening.</p>
<p>In fact by moving from a CRUD style architecture to one inspired by CQRS but based on actions you can:</p>
<ul>
<li>Give targeted update capabilities that:
<ul>
<li>Allow only certain parts of the ‘Read’ model to be modified. </li>
<li>Allow things that are not even in the ‘Read’ model to be modified or provided if needed. </li>
</ul>
</li>
<li>Selectively give users permissions to only the ‘Actions’ or Commands they need. </li>
<li>Log every Action and replay them at a later date to rebuild your data (i.e. Event Sourcing). </li>
<li>Capture what is requested (i.e. Discount the product) and respond immediately before the change has actually been made, safe in the knowledge you will eventually process the request and achieve “Eventual Consistency”. </li>
<li>Capture more information about what is happening (i.e. User X discounted Marmite by 15% is much better than User X updated Marmite). </li>
<li>Create Actions that manipulate a lot of entities simultaneously (i.e. POST ~/Categories(‘Yeast Spreads’)/Products/Discount…) </li>
</ul>
<p>Of course simply separating the read/write models in OData doesn’t give you all of these advantages immediately, but at least it creates a foundation that can scale to support things like Event Sourcing or Eventual Consistency later if required. </p>
<p>Some of you may be thinking you can achieve many of these goals by having a more granular model that makes things like “Discount” a resource, and that would be true. However for most people using OData that way of thinking is foreign and more importantly the EDM foundations of OData get in the way a little too. So for me Actions seems like the right approach in OData.</p>
<p>I love this.    <br />But what do you think?     <br />-<a href="http://twitter.com/adjames">Alex</a></p>
<div></div>
<p><img src="http://msdnrss.thecoderblogs.com/wp-content/plugins/wp-o-matic/cache/de946_aggbug.aspx?PostID=10263906" width="1" height="1" /></p>
]]></content:encoded>
			<wfw:commentRss>http://msdnrss.thecoderblogs.com/2012/02/cqrs-with-odata-and-actions-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

