﻿<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>Ayende @ Rahien</title><link>http://ayende.com/blog/</link><description>Ayende @ Rahien</description><copyright>Copyright (C) Ayende Rahien  2004 - 2012 (c) 2013</copyright><ttl>60</ttl><item><title>Unprofessional code</title><description>&lt;p&gt;This code bugs me. &lt;/p&gt; &lt;p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/Unprofessional-code_83E8/image_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/Unprofessional-code_83E8/image_thumb.png" width="864" height="611"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;It isn’t wrong, and it is going to produce the right result. But is ain’t pro code, in the sense that this code lacks an important *ities.&lt;/p&gt; &lt;p&gt;Just to cut down on the guessing, I marked the exact part that bugs me. Can you see the issue? &lt;/p&gt;</description><link>http://ayende.com/blog/156450/unprofessional-code?key=0e2e0b20-6b01-4afa-afc4-f97d9f78d665</link><guid>http://ayende.com/blog/156450/unprofessional-code?key=0e2e0b20-6b01-4afa-afc4-f97d9f78d665</guid><pubDate>Mon, 25 Jun 2012 09:00:00 GMT</pubDate></item><item><title>Explain this code: Answers</title><description>&lt;p&gt;The reason this code is useful?&lt;/p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/Explain-this-code-Answers_67F5/image_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/Explain-this-code-Answers_67F5/image_thumb.png" width="307" height="475"&gt;&lt;/a&gt; &lt;p&gt;Because it allows you to write this sort of code:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Program
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Collection&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; nums;

    &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
    {
        nums.Add(1);
        Console.WriteLine(nums.Count);
    }
}
&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;I was aiming for that, and still this code strikes me as &lt;em&gt;wrong&lt;/em&gt;.&lt;/p&gt;</description><link>http://ayende.com/blog/154882/explain-this-code-answers?key=941b81a7-8086-4c45-9406-2ef041ffa711</link><guid>http://ayende.com/blog/154882/explain-this-code-answers?key=941b81a7-8086-4c45-9406-2ef041ffa711</guid><pubDate>Fri, 13 Apr 2012 09:00:00 GMT</pubDate></item><item><title>Explain this code</title><description>&lt;p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/1aee26bcbcac_679D/image_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/1aee26bcbcac_679D/image_thumb.png" width="307" height="475"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Why was something like that created?&lt;/p&gt;</description><link>http://ayende.com/blog/154881/explain-this-code?key=12206bfd-c67c-496a-b744-e93486ea7332</link><guid>http://ayende.com/blog/154881/explain-this-code?key=12206bfd-c67c-496a-b744-e93486ea7332</guid><pubDate>Thu, 12 Apr 2012 10:00:00 GMT</pubDate></item><item><title>Challenge: Minimum number of round trips</title><description>&lt;p&gt;We are working on creating better experience for RavenDB &amp;amp; Sharding, and that led us to the following piece of code:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class="csharpcode"&gt;shardedSession.Load&amp;lt;Post&amp;gt;(&lt;span class="str"&gt;"posts/1234"&lt;/span&gt;, &lt;span class="str"&gt;"post/3214"&lt;/span&gt;, &lt;span class="str"&gt;"posts/1232"&lt;/span&gt;, &lt;span class="str"&gt;"posts/1238"&lt;/span&gt;, &lt;span class="str"&gt;"posts/1232"&lt;/span&gt;);&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;And the following Shard function:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] GetAppropriateUrls(&lt;span class="kwrd"&gt;string&lt;/span&gt; id)
{
    &lt;span class="kwrd"&gt;switch&lt;/span&gt; (id.Last())
    {
        &lt;span class="kwrd"&gt;case&lt;/span&gt; &lt;span class="str"&gt;'4'&lt;/span&gt;:
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { &lt;span class="str"&gt;"http://srv-4"&lt;/span&gt;, &lt;span class="str"&gt;"http://srv-backup-4"&lt;/span&gt; };

        &lt;span class="kwrd"&gt;case&lt;/span&gt; &lt;span class="str"&gt;'2'&lt;/span&gt;:
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { &lt;span class="str"&gt;"http://srv-2"&lt;/span&gt; };

        &lt;span class="kwrd"&gt;case&lt;/span&gt; &lt;span class="str"&gt;'8'&lt;/span&gt;:
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { &lt;span class="str"&gt;"http://srv-backup-4"&lt;/span&gt; };

        &lt;span class="kwrd"&gt;default&lt;/span&gt;:
            &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; InvalidOperationException();
    }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;Write a function that would make the minimum number of queries to load of all the posts from all of the servers.&lt;/p&gt;</description><link>http://ayende.com/blog/120833/challenge-minimum-number-of-round-trips?key=481ab9b2-7a3b-49db-bcc4-387d4590726d</link><guid>http://ayende.com/blog/120833/challenge-minimum-number-of-round-trips?key=481ab9b2-7a3b-49db-bcc4-387d4590726d</guid><pubDate>Mon, 17 Oct 2011 10:00:00 GMT</pubDate></item><item><title>The tax calculation challenge</title><description>&lt;p&gt;People seems to be more interested in answering the question than the code that solved it. Actually, people seemed to be more interested in outdoing one another in creating answers to that. What I found most interesting is that a large percentage of the answers (both in the blog post and in the interviews) got a lot of that wrong.&lt;/p&gt; &lt;p&gt;So here is the question in full. The following table is the current tax rates in Israel:&lt;/p&gt; &lt;table border="0" cellspacing="0" cellpadding="2" width="400"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;&amp;nbsp;&lt;/td&gt; &lt;td valign="top" width="200"&gt;Tax Rate&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;Up to 5,070&lt;/td&gt; &lt;td valign="top" width="200"&gt;10%&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;5,071 up to 8,660&lt;/td&gt; &lt;td valign="top" width="200"&gt;14%&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;8,661 up to 14,070&lt;/td&gt; &lt;td valign="top" width="200"&gt;23%&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;14,071 up to 21,240&lt;/td&gt; &lt;td valign="top" width="200"&gt;30%&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;21,241 up to 40,230&lt;/td&gt; &lt;td valign="top" width="200"&gt;33%&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="200"&gt;Higher than 40,230&lt;/td&gt; &lt;td valign="top" width="200"&gt;45%&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;Here are some example answers:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;5,000 –&amp;gt; 500&lt;/li&gt; &lt;li&gt;5,800 –&amp;gt; 609.2&lt;/li&gt; &lt;li&gt;9,000 –&amp;gt; 1087.8&lt;/li&gt; &lt;li&gt;15,000 –&amp;gt; 2532.9&lt;/li&gt; &lt;li&gt;50,000 –&amp;gt; 15,068.1&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;This problem is a bit tricky because the tax rate doesn’t apply to the whole sum, only to the part that is within the current rate.&lt;/p&gt;</description><link>http://ayende.com/blog/108545/the-tax-calculation-challenge?key=ad6b9667-4c27-473c-8805-f1d616733215</link><guid>http://ayende.com/blog/108545/the-tax-calculation-challenge?key=ad6b9667-4c27-473c-8805-f1d616733215</guid><pubDate>Fri, 23 Sep 2011 09:00:00 GMT</pubDate></item><item><title>Elegancy challenge: Cacheable Batches</title><description>&lt;p&gt;Let us say that we have the following server code:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public JsonDocument&lt;/span&gt;[] GetDocument(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids)
{
  &lt;font color="#0000ff"&gt;var&lt;/font&gt;  results = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;JsonDocument&amp;gt;();
  &lt;span class="kwrd"&gt;foreach&lt;/span&gt;(var id &lt;span class="kwrd"&gt;in&lt;/span&gt; ids)
  {
    results.Add(GetDocument(id));
  }
  &lt;span class="kwrd"&gt;return&lt;/span&gt; result.ToArray();  
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;This method is a classic example of batching requests to the server. For the purpose of our discussion, we have a client proxy that looks like this:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ClientProxy : IDisposable
{
  MemoryCache cache = &lt;span class="kwrd"&gt;new&lt;/span&gt; MemoryCache();
  
  &lt;span class="kwrd"&gt;public&lt;/span&gt; JsonDocument[] GetDocument(&lt;span class="kwrd"&gt;params string&lt;/span&gt;[] ids)
  {
    
    &lt;span class="rem"&gt;// make the request to the server, for example&lt;/span&gt;
    &lt;font color="#0000ff"&gt;var&lt;/font&gt; request = WebRequest.Create(&lt;span class="str"&gt;"http://server/get?id="&lt;/span&gt; + &lt;span class="kwrd"&gt;string&lt;/span&gt;.Join(&lt;span class="str"&gt;"&amp;amp;id="&lt;/span&gt;, ids));
    &lt;span class="kwrd"&gt;using&lt;/span&gt;(var stream = request.GetResponse().GetResposeStream())
    {
      &lt;font color="#0000ff"&gt;return  &lt;/font&gt;GetResults(stream);
    }
  }
  
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Dispose()
  {
    cache.Dispose();
  }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;Now, as you can probably guess from the title and from the code above, the question relates to caching. We need to make the following pass:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt;(var proxy = &lt;span class="kwrd"&gt;new&lt;/span&gt; ClientProxy())
{
  proxy.GetPopularity(&lt;span class="str"&gt;"ayende"&lt;/span&gt;, &lt;span class="str"&gt;"oren"&lt;/span&gt;); &lt;span class="rem"&gt;// nothing in the cahce, make request to server&lt;/span&gt;
  proxy.GetPopulairty(&lt;span class="str"&gt;"rhino"&lt;/span&gt;, &lt;span class="str"&gt;"hippo"&lt;/span&gt;); &lt;span class="rem"&gt;// nothing in the cahce, make request to server&lt;/span&gt;
  proxy.GetPopulairty(&lt;span class="str"&gt;"rhino"&lt;/span&gt;, &lt;span class="str"&gt;"aligator"&lt;/span&gt;); &lt;span class="rem"&gt;// only request aligator, 'rhino' is in the cache&lt;/span&gt;
  proxy.GetPopulairty(&lt;span class="str"&gt;"rhino"&lt;/span&gt;, &lt;span class="str"&gt;"hippo"&lt;/span&gt;);  &lt;span class="rem"&gt;// don't make any request, serve from cache&lt;/span&gt;
  proxy.GetPopulairty(&lt;span class="str"&gt;"rhino"&lt;/span&gt;, &lt;span class="str"&gt;"oren"&lt;/span&gt;);   &lt;span class="rem"&gt;// don't make any request, serve from cache&lt;/span&gt;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The tricky part, of course, is to make this &lt;em&gt;elegant&lt;/em&gt;. You can modify both server and client code.&lt;/p&gt;
&lt;p&gt;I simplified the problem drastically, but one of the major benefits in the real issue was reducing the size of data we have to fetch over the network even for partial cached queries. &lt;/p&gt;</description><link>http://ayende.com/blog/60417/elegancy-challenge-cacheable-batches?key=72b2ef7e-c5e0-444f-83b5-5921ac5354f9</link><guid>http://ayende.com/blog/60417/elegancy-challenge-cacheable-batches?key=72b2ef7e-c5e0-444f-83b5-5921ac5354f9</guid><pubDate>Wed, 24 Aug 2011 09:00:00 GMT</pubDate></item><item><title>Challenge: Recent Comments with Future Posts</title><description>&lt;p&gt;We were asked to implement comments RSS for this blog, and many people asked about the recent comments widget. That turned out to be quite a bit more complicated than it appeared on first try, and I thought it would make a great challenge. &lt;/p&gt; &lt;p&gt;On the face of it, it looks like a drop dead simple feature, right? Show me the last 5 comments in the blog.&lt;/p&gt; &lt;p&gt;The problem with that is that it ignores something that is very important to me, the notion of future posts. One of the major advantages of RaccoonBlog is that I am able to post stuff that would go on the queue (for example, this post would be scheduled for about a month from the date of writing it), but still share that post with other people. Moreover, those other people can also comment on the post. To make things interesting, it is quite common for me to re-schedule posts, moving them from one date to another.&lt;/p&gt; &lt;p&gt;Given that complication, let us try to define how we want the Recent Comments feature to behave with regards to future posts. The logic is fairly simple:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Until the post is public, do not show the post comments.&lt;/li&gt; &lt;li&gt;If a post had comments on it while it was a future post, when it becomes public, the comments that were already posted there, should also be included.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;The last requirement is a bit tricky. Allow me to explain. It would be easier to understand with an example, which luckily I have:&lt;/p&gt; &lt;p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/Challenge-Recent-Comments-with-Future-Po_17DA/image_thumb%5B2%5D_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image_thumb[2]" border="0" alt="image_thumb[2]" src="http://ayende.com/blog/Images/Windows-Live-Writer/Challenge-Recent-Comments-with-Future-Po_17DA/image_thumb%5B2%5D_thumb.png" width="771" height="558"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;As you can see, this is a post that was created on the 1st of July, but was published on the 12th. Mike and me have commented on the post shortly after it was published (while it was still hidden from the general public). Then, after it was published, grega_g and Jonty have commented on that.&lt;/p&gt; &lt;p&gt;Now, let us assume that we query at 12 Jul, 08:55 AM, we will &lt;em&gt;not&lt;/em&gt; get any comments from this post, but on 12 Jul, 09:01 AM, we should get both comments from this post. To make things &lt;em&gt;more&lt;/em&gt; interesting, those should come &lt;em&gt;after&lt;/em&gt; comments that were posted (chronologically) after them. Confusing, isn’t it? Again, let us go with a visual aid for explaining things.&lt;/p&gt; &lt;p&gt;In other words, let us say that we also have this as well:&lt;/p&gt; &lt;p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/Challenge-Recent-Comments-with-Future-Po_17DA/image_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/Challenge-Recent-Comments-with-Future-Po_17DA/image_thumb.png" width="781" height="437"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Here is what we should see in the Recent Comments:&lt;/p&gt; &lt;table border="0" cellspacing="0" cellpadding="2" width="600"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td valign="top" width="300"&gt;12 Jul, 2011 – 08:55 AM&lt;/td&gt; &lt;td valign="top" width="300"&gt;12 Jul, 2011 – 09:05 AM&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt; &lt;td valign="top" width="300"&gt; &lt;ol&gt; &lt;li&gt;07/07/2011 07:42 PM – jdn&lt;/li&gt; &lt;li&gt;07/08/2011 07:34 PM – Matt Warren &lt;/li&gt;&lt;/ol&gt;&lt;/td&gt; &lt;td valign="top" width="300"&gt; &lt;ol&gt; &lt;li&gt;07/03/2011 05:26 PM – Ayende Rahien &lt;li&gt;07/03/2011 05:07 PM - Mike Minutillo &lt;li&gt;07/07/2011 07:42 PM – jdn&lt;/li&gt; &lt;li&gt;07/08/2011 07:34 PM – Matt Warren &lt;/li&gt;&lt;/ol&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;Note that the 1st and 2snd location on 9:05 are should sort after 3rd and 4th, but are sorted before them, because of the post publish date, which we also take into account.&lt;/p&gt; &lt;p&gt;Given all of that, and regardless of the actual technology that you use, how would you implement this feature?&lt;/p&gt;</description><link>http://ayende.com/blog/68609/challenge-recent-comments-with-future-posts?key=83c01180-7bbf-4f47-a71c-00de4800a226</link><guid>http://ayende.com/blog/68609/challenge-recent-comments-with-future-posts?key=83c01180-7bbf-4f47-a71c-00de4800a226</guid><pubDate>Tue, 23 Aug 2011 09:00:00 GMT</pubDate></item><item><title>Answer: Modifying execution approaches</title><description>&lt;p&gt;In RavenDB, we had this piece of code:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;        internal&lt;/span&gt; T[] LoadInternal&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids, &lt;span class="kwrd"&gt;string&lt;/span&gt;[] includes)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt;(ids.Length == 0)
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; T[0];

            IncrementRequestCount();
            Debug.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Bulk loading ids [{0}] from {1}"&lt;/span&gt;, &lt;span class="kwrd"&gt;string&lt;/span&gt;.Join(&lt;span class="str"&gt;", "&lt;/span&gt;, ids), StoreIdentifier));
            MultiLoadResult multiLoadResult;
            JsonDocument[] includeResults;
            JsonDocument[] results;
&lt;span class="preproc"&gt;#if&lt;/span&gt; !SILVERLIGHT
            var sp = Stopwatch.StartNew();
&lt;span class="preproc"&gt;#else&lt;/span&gt;
            var startTime = DateTime.Now;
&lt;span class="preproc"&gt;#endif&lt;/span&gt;
            &lt;span class="kwrd"&gt;bool&lt;/span&gt; firstRequest = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
            &lt;span class="kwrd"&gt;do&lt;/span&gt;
            {
                IDisposable disposable = &lt;span class="kwrd"&gt;null&lt;/span&gt;;
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (firstRequest == &lt;span class="kwrd"&gt;false&lt;/span&gt;) &lt;span class="rem"&gt;// if this is a repeated request, we mustn't use the cached result, but have to re-query the server&lt;/span&gt;
                    disposable = DatabaseCommands.DisableAllCaching();
                &lt;span class="kwrd"&gt;using&lt;/span&gt; (disposable)
&lt;font style="background-color: #ffff00"&gt;                    multiLoadResult = DatabaseCommands.Get(ids, includes);
&lt;/font&gt;
                firstRequest = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
                includeResults = SerializationHelper.RavenJObjectsToJsonDocuments(multiLoadResult.Includes).ToArray();
                results = SerializationHelper.RavenJObjectsToJsonDocuments(multiLoadResult.Results).ToArray();
            } &lt;span class="kwrd"&gt;while&lt;/span&gt; (
                AllowNonAuthoritiveInformation == &lt;span class="kwrd"&gt;false&lt;/span&gt; &amp;amp;&amp;amp;
                results.Any(x =&amp;gt; x.NonAuthoritiveInformation ?? &lt;span class="kwrd"&gt;false&lt;/span&gt;) &amp;amp;&amp;amp;
&lt;span class="preproc"&gt;#if&lt;/span&gt; !SILVERLIGHT
                sp.Elapsed &amp;lt; NonAuthoritiveInformationTimeout
&lt;span class="preproc"&gt;#else&lt;/span&gt; 
                (DateTime.Now - startTime) &amp;lt; NonAuthoritiveInformationTimeout
&lt;span class="preproc"&gt;#endif&lt;/span&gt;
                );

            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var include &lt;span class="kwrd"&gt;in&lt;/span&gt; includeResults)
            {
                TrackEntity&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt;(include);
            }

            &lt;span class="kwrd"&gt;return&lt;/span&gt; results
                .Select(TrackEntity&amp;lt;T&amp;gt;)
                .ToArray();
        }&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;And we needed to take this same piece of code and execute it in:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Async fashion 
&lt;li&gt;As part of a batch of queries (sending multiple requests to RavenDB in a single HTTP call).&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Everything else is the same, but in each case the marked line is completely different.&lt;/p&gt;
&lt;p&gt;I chose to address this by doing a Method Object refactoring. I create a new class, and moved all the local variables to fields, and moved each part of the method to its own method. I also explicitly gave up control on executing, deferring that to whoever it calling us. We ended up with this:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MultiLoadOperation
    {
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; Logger log = LogManager.GetCurrentClassLogger();

        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; InMemoryDocumentSessionOperations sessionOperations;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; Func&amp;lt;IDisposable&amp;gt; disableAllCaching;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] includes;
        &lt;span class="kwrd"&gt;bool&lt;/span&gt; firstRequest = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
        IDisposable disposable = &lt;span class="kwrd"&gt;null&lt;/span&gt;;
        JsonDocument[] results;
        JsonDocument[] includeResults;
                
&lt;span class="preproc"&gt;#if&lt;/span&gt; !SILVERLIGHT
        &lt;span class="kwrd"&gt;private&lt;/span&gt; Stopwatch sp;
&lt;span class="preproc"&gt;#else&lt;/span&gt;
        &lt;span class="kwrd"&gt;private&lt;/span&gt;    DateTime startTime;
&lt;span class="preproc"&gt;#endif&lt;/span&gt;

        &lt;span class="kwrd"&gt;public&lt;/span&gt; MultiLoadOperation(InMemoryDocumentSessionOperations sessionOperations, 
            Func&amp;lt;IDisposable&amp;gt; disableAllCaching,
            &lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids, &lt;span class="kwrd"&gt;string&lt;/span&gt;[] includes)
        {
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.sessionOperations = sessionOperations;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.disableAllCaching = disableAllCaching;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.ids = ids;
            &lt;span class="kwrd"&gt;this&lt;/span&gt;.includes = includes;
        
            sessionOperations.IncrementRequestCount();
            log.Debug(&lt;span class="str"&gt;"Bulk loading ids [{0}] from {1}"&lt;/span&gt;, &lt;span class="kwrd"&gt;string&lt;/span&gt;.Join(&lt;span class="str"&gt;", "&lt;/span&gt;, ids), sessionOperations.StoreIdentifier);

&lt;span class="preproc"&gt;#if&lt;/span&gt; !SILVERLIGHT
            sp = Stopwatch.StartNew();
&lt;span class="preproc"&gt;#else&lt;/span&gt;
            startTime = DateTime.Now;
&lt;span class="preproc"&gt;#endif&lt;/span&gt;
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable EnterMultiLoadContext()
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (firstRequest == &lt;span class="kwrd"&gt;false&lt;/span&gt;) &lt;span class="rem"&gt;// if this is a repeated request, we mustn't use the cached result, but have to re-query the server&lt;/span&gt;
                disposable = disableAllCaching();
            &lt;span class="kwrd"&gt;return&lt;/span&gt; disposable;
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; SetResult(MultiLoadResult multiLoadResult)
        {
            firstRequest = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
            includeResults = SerializationHelper.RavenJObjectsToJsonDocuments(multiLoadResult.Includes).ToArray();
            results = SerializationHelper.RavenJObjectsToJsonDocuments(multiLoadResult.Results).ToArray();

            &lt;span class="kwrd"&gt;return&lt;/span&gt;    sessionOperations.AllowNonAuthoritiveInformation == &lt;span class="kwrd"&gt;false&lt;/span&gt; &amp;amp;&amp;amp;
                    results.Any(x =&amp;gt; x.NonAuthoritiveInformation ?? &lt;span class="kwrd"&gt;false&lt;/span&gt;) &amp;amp;&amp;amp;
&lt;span class="preproc"&gt;#if&lt;/span&gt; !SILVERLIGHT
                    sp.Elapsed &amp;lt; sessionOperations.NonAuthoritiveInformationTimeout
&lt;span class="preproc"&gt;#else&lt;/span&gt; 
                    (DateTime.Now - startTime) &amp;lt; sessionOperations.NonAuthoritiveInformationTimeout
&lt;span class="preproc"&gt;#endif&lt;/span&gt;
                ;
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; T[] Complete&amp;lt;T&amp;gt;()
        {
            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var include &lt;span class="kwrd"&gt;in&lt;/span&gt; includeResults)
            {
                sessionOperations.TrackEntity&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt;(include);
            }

            &lt;span class="kwrd"&gt;return&lt;/span&gt; results
                .Select(sessionOperations.TrackEntity&amp;lt;T&amp;gt;)
                .ToArray();
        }
    }&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;Note that this class doesn’t contain two very important things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The actual call to the database, we gave up control on that. 
&lt;li&gt;The execution order for the methods, we don’t control that either.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;That was &lt;em&gt;ugly&lt;/em&gt;, and I decided that since I have to write another implementation as well, I might as well do the right thing and have a shared implementation. The key was to extract everything away except for the call to get the actual value. So I did just that, and we got a new class, that does all of the functionality above, &lt;em&gt;except&lt;/em&gt; control where the actual call to the server is made and how.&lt;/p&gt;
&lt;p&gt;Now, for the sync version, we have this code:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal&lt;/span&gt; T[] LoadInternal&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids, &lt;span class="kwrd"&gt;string&lt;/span&gt;[] includes)
{
    &lt;span class="kwrd"&gt;if&lt;/span&gt;(ids.Length == 0)
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; T[0];

    var multiLoadOperation = &lt;span class="kwrd"&gt;new&lt;/span&gt; MultiLoadOperation(&lt;span class="kwrd"&gt;this&lt;/span&gt;, DatabaseCommands.DisableAllCaching, ids, includes);
    MultiLoadResult multiLoadResult;
    &lt;span class="kwrd"&gt;do&lt;/span&gt;
    {
        &lt;span class="kwrd"&gt;using&lt;/span&gt;(multiLoadOperation.EnterMultiLoadContext())
        {
            multiLoadResult = DatabaseCommands.Get(ids, includes);
        }
    } &lt;span class="kwrd"&gt;while&lt;/span&gt; (multiLoadOperation.SetResult(multiLoadResult));

    &lt;span class="kwrd"&gt;return&lt;/span&gt; multiLoadOperation.Complete&amp;lt;T&amp;gt;();
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;

&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;This isn’t the most trivial of methods, I’ll admit, but it is ever so much better than the alternative, especially since now the async version looks like:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
&lt;span class="rem"&gt;/// Begins the async multi load operation&lt;/span&gt;
&lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;public&lt;/span&gt; Task&amp;lt;T[]&amp;gt; LoadAsyncInternal&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids, &lt;span class="kwrd"&gt;string&lt;/span&gt;[] includes)
{
    var multiLoadOperation = &lt;span class="kwrd"&gt;new&lt;/span&gt; MultiLoadOperation(&lt;span class="kwrd"&gt;this&lt;/span&gt;,AsyncDatabaseCommands.DisableAllCaching, ids, includes);
    &lt;span class="kwrd"&gt;return&lt;/span&gt; LoadAsyncInternal&amp;lt;T&amp;gt;(ids, includes, multiLoadOperation);
}

&lt;span class="kwrd"&gt;private&lt;/span&gt; Task&amp;lt;T[]&amp;gt; LoadAsyncInternal&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids, &lt;span class="kwrd"&gt;string&lt;/span&gt;[] includes, MultiLoadOperation multiLoadOperation)
{
    &lt;span class="kwrd"&gt;using&lt;/span&gt; (multiLoadOperation.EnterMultiLoadContext())
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; AsyncDatabaseCommands.MultiGetAsync(ids, includes)
            .ContinueWith(t =&amp;gt;
            {
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (multiLoadOperation.SetResult(t.Result) == &lt;span class="kwrd"&gt;false&lt;/span&gt;)
                    &lt;span class="kwrd"&gt;return&lt;/span&gt; Task.Factory.StartNew(() =&amp;gt; multiLoadOperation.Complete&amp;lt;T&amp;gt;());
                &lt;span class="kwrd"&gt;return&lt;/span&gt; LoadAsyncInternal&amp;lt;T&amp;gt;(ids, includes, multiLoadOperation);
            })
            .Unwrap();
    }
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;Again, it isn’t trivial, but at least the core stuff, the actual logic that isn’t related to how we execute the code is shared.&lt;/p&gt;</description><link>http://ayende.com/blog/63490/answer-modifying-execution-approaches?key=377fa661-49a3-417c-996b-1f6239c2cb94</link><guid>http://ayende.com/blog/63490/answer-modifying-execution-approaches?key=377fa661-49a3-417c-996b-1f6239c2cb94</guid><pubDate>Tue, 16 Aug 2011 09:00:00 GMT</pubDate></item><item><title>Challenge: Modifying execution approaches</title><description>&lt;p&gt;In RavenDB, we had this piece of code:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal&lt;/span&gt; T[] LoadInternal&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids, &lt;span class="kwrd"&gt;string&lt;/span&gt;[] includes)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt;(ids.Length == 0)
                &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; T[0];

            IncrementRequestCount();
            Debug.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Bulk loading ids [{0}] from {1}"&lt;/span&gt;, &lt;span class="kwrd"&gt;string&lt;/span&gt;.Join(&lt;span class="str"&gt;", "&lt;/span&gt;, ids), StoreIdentifier));
            MultiLoadResult multiLoadResult;
            JsonDocument[] includeResults;
            JsonDocument[] results;
&lt;span class="preproc"&gt;#if&lt;/span&gt; !SILVERLIGHT
            var sp = Stopwatch.StartNew();
&lt;span class="preproc"&gt;#else&lt;/span&gt;
            var startTime = DateTime.Now;
&lt;span class="preproc"&gt;#endif&lt;/span&gt;
            &lt;span class="kwrd"&gt;bool&lt;/span&gt; firstRequest = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
            &lt;span class="kwrd"&gt;do&lt;/span&gt;
            {
                IDisposable disposable = &lt;span class="kwrd"&gt;null&lt;/span&gt;;
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (firstRequest == &lt;span class="kwrd"&gt;false&lt;/span&gt;) &lt;span class="rem"&gt;// if this is a repeated request, we mustn't use the cached result, but have to re-query the server&lt;/span&gt;
                    disposable = DatabaseCommands.DisableAllCaching();
                &lt;span class="kwrd"&gt;using&lt;/span&gt; (disposable)
&lt;font style="background-color: #ffff00"&gt;                    multiLoadResult = DatabaseCommands.Get(ids, includes);
&lt;/font&gt;
                firstRequest = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
                includeResults = SerializationHelper.RavenJObjectsToJsonDocuments(multiLoadResult.Includes).ToArray();
                results = SerializationHelper.RavenJObjectsToJsonDocuments(multiLoadResult.Results).ToArray();
            } &lt;span class="kwrd"&gt;while&lt;/span&gt; (
                AllowNonAuthoritiveInformation == &lt;span class="kwrd"&gt;false&lt;/span&gt; &amp;amp;&amp;amp;
                results.Any(x =&amp;gt; x.NonAuthoritiveInformation ?? &lt;span class="kwrd"&gt;false&lt;/span&gt;) &amp;amp;&amp;amp;
&lt;span class="preproc"&gt;#if&lt;/span&gt; !SILVERLIGHT
                sp.Elapsed &amp;lt; NonAuthoritiveInformationTimeout
&lt;span class="preproc"&gt;#else&lt;/span&gt; 
                (DateTime.Now - startTime) &amp;lt; NonAuthoritiveInformationTimeout
&lt;span class="preproc"&gt;#endif&lt;/span&gt;
                );

            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var include &lt;span class="kwrd"&gt;in&lt;/span&gt; includeResults)
            {
                TrackEntity&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt;(include);
            }

            &lt;span class="kwrd"&gt;return&lt;/span&gt; results
                .Select(TrackEntity&amp;lt;T&amp;gt;)
                .ToArray();
        }&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;And we needed to take this same piece of code and execute it in:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Async fashion&lt;/li&gt;
&lt;li&gt;As part of a batch of queries (sending multiple requests to RavenDB in a single HTTP call).&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Everything else is the same, but in each case the marked line is completely different.&lt;/p&gt;
&lt;p&gt;When we had only one additional option, I choose the direct approach, and implement it using;&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; Task&amp;lt;T[]&amp;gt; LoadAsync&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] ids)
{
    IncrementRequestCount();
    &lt;span class="kwrd"&gt;return&lt;/span&gt; AsyncDatabaseCommands.MultiGetAsync(ids)
        .ContinueWith(task =&amp;gt; task.Result.Select(TrackEntity&amp;lt;T&amp;gt;).ToArray());
}&lt;/pre&gt;
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
&lt;/style&gt;
&lt;/blockquote&gt;
&lt;p&gt;You might notice a few differences between those approaches. The implementation behave, most of the time, the same, but all the behavior for edge cases is wrong. The reason for that, by the way, is that initially the Load and LoadAsync impl was functionality the same, but the Load behavior kept getting more sophisticated, and I kept forgetting to also update the LoadAsync behavior. &lt;/p&gt;
&lt;p&gt;When I started building support for batches, this really stumped me. The last thing that I wanted to do is to either try to maintain complex logic in three different location or have different behaviors depending if you were using a direct call, a batch or async call. Just trying to document that gave me a headache.&lt;/p&gt;
&lt;p&gt;How would you approach solving this problem?&lt;/p&gt;</description><link>http://ayende.com/blog/59393/challenge-modifying-execution-approaches?key=2026567b-8948-4799-9225-7a9b060e2a36</link><guid>http://ayende.com/blog/59393/challenge-modifying-execution-approaches?key=2026567b-8948-4799-9225-7a9b060e2a36</guid><pubDate>Tue, 02 Aug 2011 09:00:00 GMT</pubDate></item><item><title>Caching, the funny way</title><description>&lt;p&gt;One of the most frustrating things in working with RavenDB is that the client API is compatible with the 3.5 framework. That means that for a lot of things we either have to use conditional compilation or we have to forgo using the new stuff in 4.0.&lt;/p&gt; &lt;p&gt;Case in point, we have the following issue:&lt;/p&gt; &lt;p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/Caching-the-funny-way_8638/image_2.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/Caching-the-funny-way_8638/image_thumb.png" width="944" height="199"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;The code in question currently looks like this:&lt;/p&gt; &lt;p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/Caching-the-funny-way_8638/image_4.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/Caching-the-funny-way_8638/image_thumb_1.png" width="505" height="66"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;This is the sort of code that simply &lt;em&gt;begs&lt;/em&gt; to be used with ConcurrentDictionary. Unfortunately, we can’t use that here, because of the 3.5 limitation. Instead, I went with the usual, non thread safe, dictionary approach. I wanted to avoid locking, so I ended up with:&lt;/p&gt; &lt;p&gt;&lt;a href="http://ayende.com/blog/Images/Windows-Live-Writer/Caching-the-funny-way_8638/image_6.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://ayende.com/blog/Images/Windows-Live-Writer/Caching-the-funny-way_8638/image_thumb_2.png" width="629" height="242"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Pretty neat, even if I say so myself. The fun part that without any locking, this is completely thread safe. The field itself is initialized to an empty dictionary in the constructor, of course, but that is the only thing that is happening outside this method. For that matter, I didn’t even bother to make the field volatile. The only thing that this relies on is that pointer writes are atomic.&lt;/p&gt; &lt;p&gt;How comes this works, and what assumptions am I making that makes this thing possible?&lt;/p&gt;</description><link>http://ayende.com/blog/17409/caching-the-funny-way?key=1cf3799b-a381-4d47-a3c8-71e35d315611</link><guid>http://ayende.com/blog/17409/caching-the-funny-way?key=1cf3799b-a381-4d47-a3c8-71e35d315611</guid><pubDate>Thu, 16 Jun 2011 09:00:00 GMT</pubDate></item><item><title>Rhino Mocks Challenge: Implement This Feature</title><description>&lt;p&gt;Okay, let us see if this approach works...&lt;/p&gt;
&lt;p&gt;Here is a description of a feature that I would like to have in Rhino Mocks (modeled after a new feature in Type Mock). I don't consider this a complicated feature, and I would like to get more involvement from the community in building Rhino Mocks (see the list of all the people that helped get Rhino Mocks 3.5 out the door).&lt;/p&gt;
&lt;p&gt;The feature is fluent mocks. The idea is that this code should work:&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;var mockService = MockRespository.GenerateMock&amp;lt;IMyService&amp;gt;();&lt;br /&gt;
  Expect.Call( mockService.Identity.Name ).Return("foo");&lt;br /&gt;&lt;/p&gt;

  &lt;p&gt;Assert.AreEqual("foo", mockService.Identity.Name);&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Where identity is an interface.&lt;/p&gt;
&lt;p&gt;The best place to capture such semantics is in the RecordMockState.&lt;/p&gt;
&lt;p&gt;Have fun, and send me the patch :-)&lt;/p&gt;
</description><link>http://ayende.com/blog/3636/rhino-mocks-challenge-implement-this-feature?key=9b116f24-ae1b-44e4-b01e-83959a75fdb3</link><guid>http://ayende.com/blog/3636/rhino-mocks-challenge-implement-this-feature?key=9b116f24-ae1b-44e4-b01e-83959a75fdb3</guid><pubDate>Tue, 07 Oct 2008 22:41:21 GMT</pubDate></item><item><title>Challenge: Don't stop with the first DSL abstraction</title><description>&lt;p&gt;I was having a discussion today about the way business rules are implemented. And large part of the discussion was focused on trying to get a specific behavior in a specific circumstance. As usual, I am going to use a totally different example, which might not be as brutal in its focus as the real one.&lt;/p&gt;  &lt;p&gt;We have a set of business rules that relate to what is going to happen to a customer in certain situations. For example, we might have the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;&lt;font color="#0000ff"&gt;upon&lt;/font&gt; bounced_check &lt;span style="color: #0000ff"&gt;or&lt;/span&gt; refused_credit:
	&lt;span style="color: #0000ff"&gt;if&lt;/span&gt; customer.TotalPurchases &amp;gt; 10000: # preferred
		ask_authorizatin_for_more_credit
	&lt;span style="color: #0000ff"&gt;else&lt;/span&gt;:
		call_the cops

&lt;font color="#0000ff"&gt;upon&lt;/font&gt; new_order:
	&lt;span style="color: #0000ff"&gt;if&lt;/span&gt; customer.TotalPurchases &amp;gt; 10000: # preferred
		apply_discount 5.precent&lt;/pre&gt;

  &lt;pre&gt;&lt;font color="#0000ff"&gt;upon&lt;/font&gt; order_shipped:&lt;br /&gt;     send_marketing_stuff &lt;font color="#0000ff"&gt;unless &lt;/font&gt;customer.RequestedNoSpam&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;What is this code crying for? Here is a hint, it is &lt;em&gt;not&lt;/em&gt; the introduction of IsPreferred, although that would be welcome. &lt;/p&gt;

&lt;p&gt;I am interested in hearing what you will have to say in this matter.&lt;/p&gt;

&lt;p&gt;And as a total non sequitur, cockroaches at Starbucks, yuck. &lt;/p&gt;</description><link>http://ayende.com/blog/3582/challenge-dont-stop-with-the-first-dsl-abstraction?key=408f7f3d-f32b-4665-8149-2181bc5e1301</link><guid>http://ayende.com/blog/3582/challenge-dont-stop-with-the-first-dsl-abstraction?key=408f7f3d-f32b-4665-8149-2181bc5e1301</guid><pubDate>Wed, 03 Sep 2008 23:46:52 GMT</pubDate></item><item><title>System.Reflection.Emit fun: Find the differences</title><description>&lt;p&gt;This is annoying, I am trying to make something like this works using SRE:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Foo(&lt;span style="color: #0000ff"&gt;out&lt;/span&gt; T blah)
{
    blah = (T)Arguments[0];
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;I created the SRE code to generate the appropriate values, but it is producing invalid code.&lt;/p&gt;

&lt;p&gt;Works, but not verified IL:&lt;/p&gt;

&lt;p&gt;    L_0089: stloc.2 
  &lt;br /&gt;    L_008a: ldarg.1 

  &lt;br /&gt;    L_008b: ldloc.2 

  &lt;br /&gt;    L_008c: ldc.i4 0

  &lt;br /&gt;    L_0091: ldelem.ref 

  &lt;br /&gt;    L_0092: unbox.any !!T

  &lt;br /&gt;    L_0097: stobj !!T

  &lt;br /&gt;    L_009c: ret 

  &lt;br /&gt;&lt;/p&gt;

&lt;p&gt;Works, valid (csc.exe output, of course):&lt;/p&gt;

&lt;p&gt;    L_000d: stloc.1 
  &lt;br /&gt;    L_000e: ldarg.1 

  &lt;br /&gt;    L_000f: ldloc.1 

  &lt;br /&gt;    L_0010: ldc.i4.0 

  &lt;br /&gt;    L_0011: ldelem.ref 

  &lt;br /&gt;    L_0012: unbox.any !!T

  &lt;br /&gt;    L_0017: stobj !!T

  &lt;br /&gt;    L_001c: ret 

  &lt;br /&gt;&lt;/p&gt;
And yes, the stloc.2, and stloc.1 are expected.</description><link>http://ayende.com/blog/3516/system-reflection-emit-fun-find-the-differences?key=c756c290-9f16-486b-bb0a-5683f07984d4</link><guid>http://ayende.com/blog/3516/system-reflection-emit-fun-find-the-differences?key=c756c290-9f16-486b-bb0a-5683f07984d4</guid><pubDate>Tue, 12 Aug 2008 23:23:54 GMT</pubDate></item><item><title>Challenge: What does this code do?</title><description>&lt;p&gt;Without compiling this, can you answer me whatever this piece of code will compile? And if so, what does it do? &lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; dummyVariable1 = 1;
&lt;font color="#0000ff"&gt;var&lt;/font&gt; dummyVariable2 = 3;
&lt;font color="#0000ff"&gt;var&lt;/font&gt; a = dummyVariable1&lt;br /&gt;+-+-+-+-+ + + + + + +-+-+-+-+-+ &lt;br /&gt;	dummyVariable2;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Oh, and I want to hear reasons, too.&lt;/p&gt;</description><link>http://ayende.com/blog/3457/challenge-what-does-this-code-do?key=e8416b6a-21ac-4496-bc07-a08f268e0e89</link><guid>http://ayende.com/blog/3457/challenge-what-does-this-code-do?key=e8416b6a-21ac-4496-bc07-a08f268e0e89</guid><pubDate>Sun, 27 Jul 2008 22:34:13 GMT</pubDate></item><item><title>Challenge: Find the bug fix</title><description>&lt;p&gt;Usually I tend to pose bugs as the challenges, and not the bug &lt;em&gt;fixes&lt;/em&gt;, but this is an interesting one. Take a look at the following code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;var handles = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; List&amp;lt;WaitHandle&amp;gt;();
&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (
	var stream = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 0x1000,
								 FileOptions.Asynchronous))
{
	&lt;span style="color: #0000ff"&gt;for&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; i = 0; i &amp;lt; 64; i++)
	{
		var handle = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; ManualResetEvent(&lt;span style="color: #0000ff"&gt;false&lt;/span&gt;);
		var bytes = Encoding.UTF8.GetBytes( i + Environment.NewLine);
		stream.BeginWrite(bytes, 0, bytes.Length, &lt;span style="color: #0000ff"&gt;delegate&lt;/span&gt;(IAsyncResult ar)
		{
			stream.EndWrite(ar);
			handle.Set();
		}, stream);
		handles.Add(handle);
	}
	WaitHandle.WaitAll(handles.ToArray());
	stream.Flush();

}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, tell me why I am creating a ManualResetEvent manually, instead of using the one that BeginWrite IAsyncResult will return?&lt;/p&gt;</description><link>http://ayende.com/blog/3449/challenge-find-the-bug-fix?key=02ed36dd-f353-41cf-b98f-7064dd36a32c</link><guid>http://ayende.com/blog/3449/challenge-find-the-bug-fix?key=02ed36dd-f353-41cf-b98f-7064dd36a32c</guid><pubDate>Sat, 26 Jul 2008 19:22:08 GMT</pubDate></item><item><title>[Unstable code] Why timeouts doesn't mean squat...</title><description>&lt;p&gt;Because they aren't helpful for the pathological cases. Let us take this simple example:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;[ServiceContract]
&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;interface&lt;/span&gt; IFoo
{
	[OperationContract]
	&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; GetMessage();
}

&lt;font color="#0000ff"&gt;var&lt;/font&gt; stopwatch = Stopwatch.StartNew();
&lt;font color="#0000ff"&gt;var&lt;/font&gt; channel = ChannelFactory&amp;lt;IFoo&amp;gt;.CreateChannel(
	&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; BasicHttpBinding
	{
		SendTimeout = TimeSpan.FromSeconds(1), 
		ReceiveTimeout = TimeSpan.FromSeconds(1),
		OpenTimeout = TimeSpan.FromSeconds(1),
                CloseTimeout = TimeSpan.FromSeconds(1)
	},
	&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; EndpointAddress("&lt;span style="color: #8b0000"&gt;http://localhost:6547/bar&lt;/span&gt;"));

&lt;font color="#0000ff"&gt;var&lt;/font&gt; message = channel.GetMessage();

stopwatch.Stop();
Console.WriteLine("&lt;span style="color: #8b0000"&gt;Got message in {0}ms&lt;/span&gt;", stopwatch.ElapsedMilliseconds);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;On the face of it, it looks like we are safe from the point of view of timeouts, right? We set all the timeout settings that are there. At most, we will spend a second waiting for the message, and get a time out exception if we fail there.&lt;/p&gt;

&lt;p&gt;Here is a simple way to make this code hang for a minute (more after the code):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;&lt;span style="color: #0000ff"&gt;namespace&lt;/span&gt; ConsoleApplication1
{
	&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System;
	&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Linq;
	&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Diagnostics;
	&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.IO;
	&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Net;
	&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.ServiceModel;
	&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; System.Threading;

	&lt;span style="color: #0000ff"&gt;class&lt;/span&gt; Program
	{
		&lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;[] args)
		{
			var host = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; ServiceHost(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(FooImpl), 
				&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Uri("&lt;span style="color: #8b0000"&gt;http://localhost/foo&lt;/span&gt;"));
			host.AddServiceEndpoint(&lt;span style="color: #0000ff"&gt;typeof&lt;/span&gt;(IFoo), 
				&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; BasicHttpBinding(), 
				&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Uri("&lt;span style="color: #8b0000"&gt;http://localhost/foo&lt;/span&gt;"));
			host.Open();

			&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SlowFirewall();

			var stopwatch = Stopwatch.StartNew();
			var channel = ChannelFactory&amp;lt;IFoo&amp;gt;.CreateChannel(
				&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; BasicHttpBinding
				{
					SendTimeout = TimeSpan.FromSeconds(1), 
					ReceiveTimeout = TimeSpan.FromSeconds(1),
					OpenTimeout = TimeSpan.FromSeconds(1),
                 			CloseTimeout = TimeSpan.FromSeconds(1)
				},
				&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; EndpointAddress("&lt;span style="color: #8b0000"&gt;http://localhost:6547/bar&lt;/span&gt;"));
			
			var message = channel.GetMessage();
			
			stopwatch.Stop();
			Console.WriteLine("&lt;span style="color: #8b0000"&gt;Got message in {0}ms&lt;/span&gt;", stopwatch.ElapsedMilliseconds);


			host.Close();
		}
	}

	[ServiceContract]
	&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;interface&lt;/span&gt; IFoo
	{
		[OperationContract]
		&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; GetMessage();
	}

	&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; FooImpl : IFoo
	{
		&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; GetMessage()
		{
			&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt;('*', 5000);
		}
	}

	&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; SlowFirewall
	{
		&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;readonly&lt;/span&gt; HttpListener listener;

		&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; SlowFirewall()
		{
			listener = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; HttpListener();
			listener.Prefixes.Add("&lt;span style="color: #8b0000"&gt;http://localhost:6547/bar/&lt;/span&gt;");
			listener.Start();
			listener.BeginGetContext(OnGetContext, &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;);
		}

		&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; OnGetContext(IAsyncResult ar)
		{
			var context = listener.EndGetContext(ar);
			var request = WebRequest.Create("&lt;span style="color: #8b0000"&gt;http://localhost/foo&lt;/span&gt;");
			request.Method = context.Request.HttpMethod;
			request.ContentType = context.Request.ContentType;
			var specialHeaders = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt;[] { "&lt;span style="color: #8b0000"&gt;Connection&lt;/span&gt;", "&lt;span style="color: #8b0000"&gt;Content-Length&lt;/span&gt;", &lt;br /&gt;                                                      "&lt;span style="color: #8b0000"&gt;Host&lt;/span&gt;", "&lt;span style="color: #8b0000"&gt;Content-Type&lt;/span&gt;", "&lt;span style="color: #8b0000"&gt;Expect&lt;/span&gt;" };
			&lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; header &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; context.Request.Headers)
			{
				&lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (specialHeaders.Contains(header))
					&lt;span style="color: #0000ff"&gt;continue&lt;/span&gt;;
				request.Headers[header] = context.Request.Headers[header];
			}
			var buffer = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[context.Request.ContentLength64];
			ReadAll(buffer, context.Request.InputStream);
			&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (var stream = request.GetRequestStream())
			{
				stream.Write(buffer, 0, buffer.Length);
			}
			&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (var response = request.GetResponse())
			&lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (var responseStream = response.GetResponseStream())
			{
				buffer = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[response.ContentLength];
				ReadAll(buffer, responseStream);
				&lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; header &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; response.Headers)
				{
					&lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (specialHeaders.Contains(header))
						&lt;span style="color: #0000ff"&gt;continue&lt;/span&gt;;
					context.Response.Headers[header] = response.Headers[header];
				}
				context.Response.ContentType = response.ContentType;
				&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; i = 0;
				&lt;span style="color: #0000ff"&gt;foreach&lt;/span&gt; (var b &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; buffer)
				{
					context.Response.OutputStream.WriteByte(b);
					context.Response.OutputStream.Flush();
					Thread.Sleep(10);
					Console.WriteLine(i++);
				}
				context.Response.Close();
			}
		}

		&lt;span style="color: #0000ff"&gt;private&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; ReadAll(&lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] buffer, Stream stream)
		{
			&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; current = 0;
			&lt;span style="color: #0000ff"&gt;while&lt;/span&gt; (current &amp;lt; buffer.Length)
			{
				&lt;span style="color: #0000ff"&gt;int&lt;/span&gt; read = stream.Read(buffer, current, buffer.Length - current);
				current += read;
			}
		}
	}
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This problem means that even supposedly safe code, which has taken care of specifying timeouts properly is not safe from blocking because of network issues. Exactly the thing we specified the timeouts to avoid. I should note that this sample code is still at a &lt;em&gt;very&lt;/em&gt; high level. There is a lot of things that you can do at all levels of the network stack to play havoc with your code.&lt;/p&gt;

&lt;p&gt;As an aside, what book am I re-reading?&lt;/p&gt;</description><link>http://ayende.com/blog/3435/unstable-code-why-timeouts-doesnt-mean-squat?key=b9810c51-e5d6-491f-b392-7c19ed513b52</link><guid>http://ayende.com/blog/3435/unstable-code-why-timeouts-doesnt-mean-squat?key=b9810c51-e5d6-491f-b392-7c19ed513b52</guid><pubDate>Mon, 21 Jul 2008 18:00:30 GMT</pubDate></item><item><title>[Unstable code] So you think you are safe...</title><description>&lt;p&gt;There is some interesting discussion on my previous post about unstable code.&lt;/p&gt;  &lt;p&gt;I thought that it would be good to give a concrete example of the issue. Given the following interface &amp;amp; client code, is there a way to make this code block for a long time?&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;[ServiceContract]
&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;interface&lt;/span&gt; IFoo
{
	[OperationContract]
	&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; GetMessage();
}

&lt;font color="#0000ff"&gt;var&lt;/font&gt; stopwatch = Stopwatch.StartNew();
&lt;font color="#0000ff"&gt;var&lt;/font&gt; channel = ChannelFactory&amp;lt;IFoo&amp;gt;.CreateChannel(
	&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; BasicHttpBinding
	{
		SendTimeout = TimeSpan.FromSeconds(1), 
		ReceiveTimeout = TimeSpan.FromSeconds(1),
		OpenTimeout = TimeSpan.FromSeconds(1),
                CloseTimeout = TimeSpan.FromSeconds(1)
	},
	&lt;span style="color: #0000ff"&gt;new&lt;/span&gt; EndpointAddress("&lt;span style="color: #8b0000"&gt;http://localhost:6547/bar&lt;/span&gt;"));

var message = channel.GetMessage();

stopwatch.Stop();
Console.WriteLine("&lt;span style="color: #8b0000"&gt;Got message in {0}ms&lt;/span&gt;", stopwatch.ElapsedMilliseconds);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;You are free to play around with the server implementation as well as the network topology.&lt;/p&gt;

&lt;p&gt;Have fun....&lt;/p&gt;</description><link>http://ayende.com/blog/3434/unstable-code-so-you-think-you-are-safe?key=95d8c5f1-1789-44c9-beec-887eb7bdd918</link><guid>http://ayende.com/blog/3434/unstable-code-so-you-think-you-are-safe?key=95d8c5f1-1789-44c9-beec-887eb7bdd918</guid><pubDate>Mon, 21 Jul 2008 16:45:21 GMT</pubDate></item><item><title>Challenge: Find the deadlock</title><description>&lt;p&gt;Okay, there isn't much of a challenge here, but it is worth point out nevertheless:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://ayende.com/Blog/images/ayende_com/Blog/WindowsLiveWriter/ChallengeFindthedeadlock_8720/image_2.png"&gt;&lt;img height="478" alt="image" src="http://ayende.com/Blog/images/ayende_com/Blog/WindowsLiveWriter/ChallengeFindthedeadlock_8720/image_thumb.png" width="688" border="0" /&gt;&lt;/a&gt; &lt;a href="http://ayende.com/Blog/images/ayende_com/Blog/WindowsLiveWriter/ChallengeFindthedeadlock_8720/image_4.png"&gt;&lt;img height="661" alt="image" src="http://ayende.com/Blog/images/ayende_com/Blog/WindowsLiveWriter/ChallengeFindthedeadlock_8720/image_thumb_1.png" width="726" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;</description><link>http://ayende.com/blog/3404/challenge-find-the-deadlock?key=25412e5d-efbc-4f35-9c0a-54035ede79da</link><guid>http://ayende.com/blog/3404/challenge-find-the-deadlock?key=25412e5d-efbc-4f35-9c0a-54035ede79da</guid><pubDate>Sat, 05 Jul 2008 06:36:45 GMT</pubDate></item><item><title>Challenge: What is wrong with this code</title><description>&lt;p&gt;Let us assume that we have the following piece of code. It has a big problem in it. The kind of problem that you get called at 2 AM to solve.&lt;/p&gt;  &lt;p&gt;Can you find it? (more below)&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Main()
{
	&lt;span style="color: #0000ff"&gt;while&lt;/span&gt;(&lt;span style="color: #0000ff"&gt;true&lt;/span&gt;)
	{
		srv.ProcessMessages();
		Thread.Sleep(5000);
	}
}

&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; ProcessMessages()
{
	&lt;span style="color: #0000ff"&gt;try&lt;/span&gt;
	{
	   var msgs = GetMessages();
	   &lt;span style="color: #0000ff"&gt;byte&lt;/span&gt;[] data = Serialize(msgs);
	   var req =  WebRequest.Create("&lt;span style="color: #8b0000"&gt;http://some.remote.server&lt;/span&gt;");
	   req.Method = "&lt;span style="color: #8b0000"&gt;PUT&lt;/span&gt;";
	   &lt;span style="color: #0000ff"&gt;using&lt;/span&gt;(var stream = req.GetRequestStream())
	   {
		   stream.Write(data,0,data.Length);
	   }
	   var resp = req.GetResponse();
	   resp.Close();&lt;span style="color: #008000"&gt;// we only care that no exception was thrown&lt;/span&gt;
	   
	   MarkMessagesAsHandled(msgs); &lt;span style="color: #008000"&gt;// assume this can't throw &lt;/span&gt;
	}
	&lt;span style="color: #0000ff"&gt;catch&lt;/span&gt;(Exception)
	{
		&lt;span style="color: #008000"&gt;// bummer, but never mind,&lt;/span&gt;
		&lt;span style="color: #008000"&gt;// we will get it the next time that ProcessMessages &lt;/span&gt;
		&lt;span style="color: #008000"&gt;// is called&lt;/span&gt;
	}
}

&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; Message[] GetMessages()
{
    List&amp;lt;Message&amp;gt; msgs = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; List&amp;lt;Message&amp;gt;();
    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt;(var reader = ExecuteReader("&lt;span style="color: #8b0000"&gt;SELECT * FROM Messages WHERE Handled = 0;&lt;/span&gt;"))
    &lt;span style="color: #0000ff"&gt;while&lt;/span&gt;(reader.Read())
    {
        msgs.Add( HydrateMessage(reader) );
    }
    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; msgs.ToArray();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This code is conceptual, just to make the point. It is not real code. Things that you don't have to worry about:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Multi threading&lt;/li&gt;

  &lt;li&gt;Transactions&lt;/li&gt;

  &lt;li&gt;Failed database&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The problem is both a bit subtle and horrifying. And just to make things interesting, for most scenarios, it will work just fine.&lt;/p&gt;</description><link>http://ayende.com/blog/3396/challenge-what-is-wrong-with-this-code?key=67407a45-dd77-40ac-8291-c169e79e8e4b</link><guid>http://ayende.com/blog/3396/challenge-what-is-wrong-with-this-code?key=67407a45-dd77-40ac-8291-c169e79e8e4b</guid><pubDate>Wed, 02 Jul 2008 03:31:48 GMT</pubDate></item><item><title>Challenge: why did the tests fail?</title><description>&lt;p&gt;For a few days, some (~4) of SvnBridge integration tests would fail. Not always the same ones (but usually the same group), and &lt;em&gt;only&lt;/em&gt; if I run them all as a group, never if I run each test individually, or if I run the entire test class (which rules out most of the test dependencies that causes this). This was incredibly annoying, but several attempts to track down this issue has been less than successful.&lt;/p&gt;  &lt;p&gt;Today I got annoyed enough to say that I am not leaving until I solve this. Considering that a full test run of all SvnBridge's tests is... lengthy, that took a while, but I finally tracked down what was going on. The fault was with this method:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre&gt;&lt;span style="color: #0000ff"&gt;protected&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Svn(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; command)
{
	StringBuilder output = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; StringBuilder();
	&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; err = &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;;
	ExecuteInternal(command, &lt;span style="color: #0000ff"&gt;delegate&lt;/span&gt;(Process svn)
	{
		ThreadPool.QueueUserWorkItem(&lt;span style="color: #0000ff"&gt;delegate&lt;/span&gt;

		{
			err = svn.StandardError.ReadToEnd();
		});
		ThreadPool.QueueUserWorkItem(&lt;span style="color: #0000ff"&gt;delegate&lt;/span&gt;
		{
			&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; line;
			&lt;span style="color: #0000ff"&gt;while&lt;/span&gt; ((line = svn.StandardOutput.ReadLine()) != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)
			{
				Console.WriteLine(line);
				output.AppendLine(line);
			}
		});
	});
	&lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;.IsNullOrEmpty(err) == &lt;span style="color: #0000ff"&gt;false&lt;/span&gt;)
	{
		&lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; InvalidOperationException("&lt;span style="color: #8b0000"&gt;Failed to execute command: &lt;/span&gt;" + err);
	}
	&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; output.ToString();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will execute svn.exe and gather its input. Only sometimes it would not do so.&lt;/p&gt;

&lt;p&gt;I fixed it by changing the implementation to:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre&gt;&lt;span style="color: #0000ff"&gt;protected&lt;/span&gt; &lt;span style="color: #0000ff"&gt;static&lt;/span&gt; &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; Svn(&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; command)
{
	var output = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; StringBuilder();
	var err = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; StringBuilder();
	var readFromStdError = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Thread(prc =&amp;gt;
	{
		&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; line;
		&lt;span style="color: #0000ff"&gt;while&lt;/span&gt; ((line = ((Process)prc).StandardError.ReadLine()) != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)
		{
			Console.WriteLine(line);
			err.AppendLine(line);
		}
	});
	var readFromStdOut = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; Thread(prc =&amp;gt;
	{
		&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; line;
		&lt;span style="color: #0000ff"&gt;while&lt;/span&gt; ((line = ((Process) prc).StandardOutput.ReadLine()) != &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;)
		{
			Console.WriteLine(line);
			output.AppendLine(line);
		}
	});
	ExecuteInternal(command, svn =&amp;gt;
	{
		readFromStdError.Start(svn);
		readFromStdOut.Start(svn);
	});

	readFromStdError.Join();
	readFromStdOut.Join();

	&lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (err.Length!=0)
	{
		&lt;span style="color: #0000ff"&gt;throw&lt;/span&gt; &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; InvalidOperationException("&lt;span style="color: #8b0000"&gt;Failed to execute command: &lt;/span&gt;" + err);
	}
	&lt;span style="color: #0000ff"&gt;return&lt;/span&gt; output.ToString();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;And that fixed the problem. What &lt;em&gt;was&lt;/em&gt; the problem?&lt;/p&gt;</description><link>http://ayende.com/blog/3352/challenge-why-did-the-tests-fail?key=bf6be55c-c6bf-4be4-b934-18139eb41400</link><guid>http://ayende.com/blog/3352/challenge-why-did-the-tests-fail?key=bf6be55c-c6bf-4be4-b934-18139eb41400</guid><pubDate>Thu, 05 Jun 2008 09:21:50 GMT</pubDate></item></channel></rss>