<?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"
	>

<channel>
	<title>Think In Geek</title>
	<atom:link href="http://thinkingeek.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://thinkingeek.com</link>
	<description>In geek we trust</description>
	<pubDate>Mon, 12 Oct 2009 18:34:11 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.2</generator>
	<language>en</language>
			<item>
		<title>C#, the &#8220;and&#8221; operators and lazy evaluation</title>
		<link>http://thinkingeek.com/2009/10/12/c-the-and-operators-and-lazy-evaluation/</link>
		<comments>http://thinkingeek.com/2009/10/12/c-the-and-operators-and-lazy-evaluation/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 15:00:11 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[programming tips]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=121</guid>
		<description><![CDATA[Today at work we found a bug. My workmate, not used to C#, usually uses the &#38; operator to compare boolean values. However, in C#, the &#38; operator does not use lazy evaluation.
One curious thing about C# is that it can use two different operators to calculate an and expression: the &#38; operator and the [...]]]></description>
			<content:encoded><![CDATA[<p>Today at work we found a bug. My workmate, not used to C#, usually uses the <i>&amp;</i> operator to compare boolean values. However, in C#, the <i>&amp;</i> operator does not use <a href="http://en.wikipedia.org/wiki/Lazy_evaluation" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Lazy_evaluation?referer=');">lazy evaluation</a>.</p>
<p>One curious thing about C# is that it can use two different operators to calculate an <i>and</i> expression: the <a href="http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/sbf85k1c.aspx?referer=');">&amp;</a> operator and the <a href="http://msdn.microsoft.com/en-us/library/2a723cdk.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/2a723cdk.aspx?referer=');">&amp;&amp;</a> operator. The difference between both is that the first one (<i>&amp;</i>) can be used both with integer types and boolean types. When used with integer types it will perform a bitwise comparison between the two, and when used with boolean values it will use the logical <i>and</i> operation between the two boolean values, <b>evaluating all the parts of the expression</b>. This means that using a code like this one:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>someObject <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;</span> someObject.<span style="color: #0000FF;">SomeProperty</span> <span style="color: #008000;">==</span> someValue<span style="color: #000000;">&#41;</span></pre></div></div>

<p>will throw a runtime error if <i>someObject</i> is null, because it will try to obtain the <i>SomeProperty</i> value.</p>
<p>However, the <i>&amp;&amp;</i> operator is only available to boolean expressions, and it uses lazy evaluation, this is, if the first condition evaluated is false, it will calculate false without evaluating the rest of the expression, because an <i>and</i> is only true if all the expressions are true.</p>
<p>Conclusion, be sure to always use <i>&#038;amp&amp;</i> when evaluating boolean values if you want to avoid run time surprises :).</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=C%23%2C%20the%20%26%238220%3Band%26%238221%3B%20operators%20and%20lazy%20evaluation&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2009%2F10%2F12%2Fc-the-and-operators-and-lazy-evaluation%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=C_23_2C_20the_20_26_238220_3Band_26_238221_3B_20operators_20and_20lazy_20evaluation_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2009_2F10_2F12_2Fc-the-and-operators-and-lazy-evaluation_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2009/10/12/c-the-and-operators-and-lazy-evaluation/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Creating and testing a Linked List based Queue in C# using Nunit</title>
		<link>http://thinkingeek.com/2009/07/09/creating-and-testing-a-linked-list-based-queue-in-c-using-nunit/</link>
		<comments>http://thinkingeek.com/2009/07/09/creating-and-testing-a-linked-list-based-queue-in-c-using-nunit/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 16:23:22 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[nunit]]></category>

		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=108</guid>
		<description><![CDATA[The Queue&#60;T&#62; class (and Stack&#60;T&#62; too) of the .NET Framework from Microsoft is implemented using an array. While this is a perfectly good approach, I think that a Linked List based implementation could be desired in some situations (specifically when the size of the queue is not fixed).
Since the implementation alone would be rather simple [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/7977ey2c.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/7977ey2c.aspx?referer=');">Queue&lt;T&gt;</a> class (and <a href="http://msdn.microsoft.com/en-us/library/3278tedw.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/3278tedw.aspx?referer=');">Stack&lt;T&gt;</a> too) of the .NET Framework from Microsoft is implemented using an array. While this is a perfectly good approach, I think that a <a href="http://en.wikipedia.org/wiki/Linked_list" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Linked_list?referer=');">Linked List</a> based implementation could be desired in some situations (specifically when the size of the queue is not fixed).</p>
<p>Since the implementation alone would be rather simple for a post, I&#8217;ll show you how to implement <a href="http://en.wikipedia.org/wiki/Unit_testing" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Unit_testing?referer=');">Unit Testing</a> with the class using <a href="http://www.nunit.org/" onclick="pageTracker._trackPageview('/outgoing/www.nunit.org/?referer=');">Nunit</a>. Although this is a rather simple class to test I think it will show the basic concepts behind unit testing.<br />
<span id="more-108"></span><br />
First of all let&#8217;s begin with the interface of the class. We will call it <em>LinkedListQueue&lt;T&gt;</em>. We basically need the typical operations of a queue.</p>
<p>The interface (without the implementation) is going to be something similar to this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LinkedListQueue
<span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #008080;">#region LinkedListQueue Members</span>
&nbsp;
    <span style="color: #0600FF;">public</span> T Dequeue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">NotImplementedException</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Enqueue<span style="color: #000000;">&#40;</span>T item<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">NotImplementedException</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> T Peek<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">NotImplementedException</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Clear<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">NotImplementedException</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Count
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">NotImplementedException</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080;">#endregion</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The thing about unit testing is to first write the different tests so we know <strong>what we want to test</strong> and then we have to write the code so the tests are passed. Following this convention, now is the time to write some tests using Nunit. To do so, we have to create a new project of type <em>Class Library</em> in Visual Studio (we could have the tests on the same code but it&#8217;s better to have it separately so we don&#8217;t bloat the real production code). For more information about how to install and set up Nunit I suggest you visit <a href="http://www.nunit.org/" onclick="pageTracker._trackPageview('/outgoing/www.nunit.org/?referer=');">the site</a> for more information. I called the project <em>LinkedListQueueTest</em></p>
<p>Once we have the code, we can start writing tests in a special class which will have this modifier:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>TestFixture<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LinkedListQueueTest
<span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span></pre></div></div>

<p>Inside this class we have to write one method for each test we want to perform. It&#8217;s usually a good practice to have one test per method on the class you&#8217;re testing. In our case, we will begin testing the <em>Enqueue</em> method. To mark a method as a test, we have to add a modifier to it like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Dequeue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span></pre></div></div>

<p>And in the body of the method, we have to perform the test we need. Usually the tests have a structure: creating an object on which to test, executing the method, and confirm that the result is the same as we expected. Let&#8217;s do a simple code for our test:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Dequeue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    LinkedListQueue queue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> LinkedListQueue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #008080; font-style: italic;">//We enqueue some items to test</span>
    queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
    queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
    queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
    queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
    queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #008080; font-style: italic;">//For each number enqueued we check that is removed properly and in the</span>
    <span style="color: #008080; font-style: italic;">//queue order (FIFO)</span>
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, 0<span style="color: #000000;">&#41;</span>;
    Assert.<span style="color: #0000FF;">Throws</span><span style="color: #000000;">&#40;</span>
        <span style="color: #FF0000;">delegate</span>
        <span style="color: #000000;">&#123;</span>
            queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>I suggest you read the Nunit documentation to see the different assertions you have available.</p>
<p>Now that we wrote our first test, we should start thinking and writing the rest of the tests. To simplify the post, here&#8217;s a full class showing some tests that you may have wanted to perform:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">NUnit.Framework</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> ThinkInGeek.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>.<span style="color: #0000FF;">Testing</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>TestFixture<span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LinkedListQueueTest
    <span style="color: #000000;">&#123;</span>
        <span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Dequeue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            LinkedListQueue queue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> LinkedListQueue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">//We enqueue some items to test</span>
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">//For each number enqueued we check that is removed properly and in the</span>
            <span style="color: #008080; font-style: italic;">//queue order (FIFO)</span>
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, 0<span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">Throws</span><span style="color: #000000;">&#40;</span>
                <span style="color: #FF0000;">delegate</span>
                <span style="color: #000000;">&#123;</span>
                    queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Enqueue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            LinkedListQueue queue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> LinkedListQueue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">//We enqueue some items to test and check that the items are inserted correctly</span>
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Peek<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            LinkedListQueue queue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> LinkedListQueue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">//We enqueue some items to test</span>
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">//We check that after a peeking we have the correct value but the item</span>
            <span style="color: #008080; font-style: italic;">//is not deleted</span>
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Peek</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Peek</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Peek</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Peek</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Peek</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Dequeue</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">Throws</span><span style="color: #000000;">&#40;</span>
                <span style="color: #FF0000;">delegate</span>
                <span style="color: #000000;">&#123;</span>
                    queue.<span style="color: #0000FF;">Peek</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Clear<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            LinkedListQueue queue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> LinkedListQueue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">4</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Enqueue</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span><span style="color: #000000;">&#41;</span>;
            queue.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span>queue.<span style="color: #0000FF;">Count</span>, 0<span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>To see how our test behave, we have to open the resulting <em>LinkedListQueueTest.dll</em> in the Nunit tester program. As we have written no real code on the queue class, it&#8217;s obvious that our tests will fail. So let&#8217;s get our hands dirty and start programming our queue.</p>
<p>I will not go into the details because a linked list based queue is really easy to implement, so here&#8217;s the final code of the class:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> ThinkInGeek.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LinkedListQueue
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080;">#region Node inner class</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Node
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">public</span> K Element <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">public</span> Node NextElement <span style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Private members</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">int</span> m_count <span style="color: #008000;">=</span> 0;
        <span style="color: #0600FF;">private</span> Node m_head <span style="color: #008000;">=</span> null;
        <span style="color: #0600FF;">private</span> Node m_tail <span style="color: #008000;">=</span> null;
&nbsp;
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #0600FF;">public</span> T Dequeue<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>m_head <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> InvalidOperationException<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #008080; font-style: italic;">//We have to return the item on the head and update the new head</span>
            T currentItem <span style="color: #008000;">=</span> m_head.<span style="color: #0000FF;">Element</span>;
            m_head <span style="color: #008000;">=</span> m_head.<span style="color: #0000FF;">NextElement</span>;
            m_count--;
            <span style="color: #0600FF;">return</span> currentItem;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Enqueue<span style="color: #000000;">&#40;</span>T item<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//We need to add the item and update the tail</span>
            Node newNode <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Node<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            newNode.<span style="color: #0000FF;">Element</span> <span style="color: #008000;">=</span> item;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>m_tail <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                m_tail.<span style="color: #0000FF;">NextElement</span> <span style="color: #008000;">=</span> newNode;
            <span style="color: #000000;">&#125;</span>
            m_tail <span style="color: #008000;">=</span> newNode;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>m_head <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                m_head <span style="color: #008000;">=</span> newNode;
            <span style="color: #000000;">&#125;</span>
            m_count++;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> T Peek<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>m_head <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> InvalidOperationException<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">return</span> m_head.<span style="color: #0000FF;">Element</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Clear<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            m_head <span style="color: #008000;">=</span> null;
            m_tail <span style="color: #008000;">=</span> null;
            m_count <span style="color: #008000;">=</span> 0;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Count
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> m_count; <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The advantage of unit testing is that now the testing is going to be done automatically. The only thing we have to do is open the testing dll file into Nunit and see how&#8217;s the outcome. As we&#8217;re really good programmers, using the code I showed you, all the tests will pass <img src='http://thinkingeek.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div id="attachment_115" class="wp-caption aligncenter" style="width: 310px"><a href="http://thinkingeek.com/wp-content/uploads/2009/07/unittesting.png"  rel="lightbox[roadtrip]"><img class="size-medium wp-image-115" title="UnitTesting" src="http://thinkingeek.com/wp-content/uploads/2009/07/unittesting-300x227.png" alt="Unit Testing results window" width="300" height="227" /></a><p class="wp-caption-text">Unit Testing results window</p></div>
<p>This is a really simple example of how things should be done with unit testing using C# and Nunit, but I hope it can get you started and you can grasp the philosophy of it. For more information I really recommend reading the book <a href="http://www.amazon.com/Pragmatic-Unit-Testing-NUnit-2nd/dp/0977616673/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1247156448&amp;sr=8-1" onclick="pageTracker._trackPageview('/outgoing/www.amazon.com/Pragmatic-Unit-Testing-NUnit-2nd/dp/0977616673/ref=sr_1_1?ie=UTF8_amp_s=books_amp_qid=1247156448_amp_sr=8-1&amp;referer=');">Pragmatic Unit Testing in C# with NUnit</a>.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=Creating%20and%20testing%20a%20Linked%20List%20based%20Queue%20in%20C%23%20using%20Nunit&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2009%2F07%2F09%2Fcreating-and-testing-a-linked-list-based-queue-in-c-using-nunit%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=Creating_20and_20testing_20a_20Linked_20List_20based_20Queue_20in_20C_23_20using_20Nunit_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2009_2F07_2F09_2Fcreating-and-testing-a-linked-list-based-queue-in-c-using-nunit_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2009/07/09/creating-and-testing-a-linked-list-based-queue-in-c-using-nunit/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Disabling UpdatePanels when an asynchronous postback in progress</title>
		<link>http://thinkingeek.com/2009/06/08/disabling-updatepanels-when-an-asynchronous-postback-is-done/</link>
		<comments>http://thinkingeek.com/2009/06/08/disabling-updatepanels-when-an-asynchronous-postback-is-done/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 11:32:16 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[ajax]]></category>

		<category><![CDATA[asp]]></category>

		<category><![CDATA[javascript]]></category>

		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=104</guid>
		<description><![CDATA[If you&#8217;ve ever worked with relatively large UpdatePanels maybe you&#8217;ll have had a problem: blocking the user some elements while the asynchronous postback is running. When working with local or LAN environments, the async responses might be fast, but over the internet, or on large calculations the async postback may take a while. During this [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve ever worked with relatively large UpdatePanels maybe you&#8217;ll have had a problem: blocking the user some elements while the asynchronous postback is running. When working with local or LAN environments, the async responses might be fast, but over the internet, or on large calculations the async postback may take a while. During this period, you may want to block the UpdatePanel controls so the user can&#8217;t trigger another postback or do any other operations on that UpdatePanel. I&#8217;ll show you an easy way to do so by using the AJAX framework for .NET and <a href="http://jquery.com" onclick="pageTracker._trackPageview('/outgoing/jquery.com?referer=');">jQuery</a> and one of its plugins: <a href="http://malsup.com/jquery/block/" onclick="pageTracker._trackPageview('/outgoing/malsup.com/jquery/block/?referer=');">blockUI</a>.</p>
<p>
For those who don&#8217;t know jQuery, it&#8217;s an opensource Javascript framework that <a href="http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx" onclick="pageTracker._trackPageview('/outgoing/weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx?referer=');">is going to be embedded on future versions of Visual Studio</a>. It&#8217;s a very good framework because of its simplicity and its extensibility, having lots of plugins. One of those plugins is the blockUI plugin, which allows you to block and unlock any part of the DOM at will.
</p>
<p><span id="more-104"></span></p>
<p>
Let&#8217;s try this with a simple example. Imagine you have an UpdatePanel with various buttons, and you want that when a user clicks on any of it, all the interactive controls of the UpdatePanel become disabled until the asynchronous response has come back and the html has been updated. To do this, we need to know when the UpdatePanel is being updated. The best way to do this is to listen to an event of the <a href="http://msdn.microsoft.com/en-us/library/bb311028.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/bb311028.aspx?referer=');">PageRequestManager</a> object of our web page. The event is called <i>beginRequest</i> and the way we can attach to it is as follows.
</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">Sys.<span style="color: #660066;">WebForms</span>.<span style="color: #660066;">PageRequestManager</span>.<span style="color: #660066;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">add_beginRequest</span><span style="color: #009900;">&#40;</span>BeginRequestHandler<span style="color: #009900;">&#41;</span>;</pre></div></div>

</p>
<p>
This will get the instance of the PageRequestManager object and add a listener to the event, pointed at the javascript function called <i>BeginRequestHandler</i>.
</p>
<p>
The next step is to actually write this function. One option here would be to manually disable all the controls inside the UpdatePanel that can trigger a postback, but that would be very tedious. Instead, I propose you a way to directly disable all the UpdatePanel. We can do so by using the blockUI plugin from jQuery.<br />
The method will look like this.
</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> BeginRequestHandler<span style="color: #009900;">&#40;</span>sender<span style="color: #339933;">,</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#&lt;%= UpdatePanel1.ClientID %&gt;'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">block</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span></pre></div></div>

</p>
<p>
This might need a bit of explanation. In jQuery, when using <i>$(&#8217;#element&#8217;) we select the element of the DOM that has the id <i>&#8216;element&#8217;</i>. This returns a jQuery object upon which we can execute a series of commands (more on jQuery selectors on the jQuery website). Of those operations we can perform, there&#8217;s one that is provided with the blockUI plugin, and it&#8217;s called <i>block()</i>. This operation will simply block the DOM element that the jQuery selector has selected. With this simple line of code, then, we can disable an entire UpdatePanel. Since the UpdatePanel will be redrawn when the asynchronous postback comes back, it will be redrawn enabled again, so we don&#8217;t have to worry about enabling it again.
</p>
<p>
I suggest you visit the documentation of the blockUI plugin for more information and blocking options. In this example we simply disable the controls, but using some nice CSS you could use messages and html elements to notice the user that something is going to happen, like a nice <i>Loading</i> meassage or something similar.
</p>
<p>
Note that this will only work if you have only one UpdatePanel on the web page and all the controls that cause an asynchronous postback are inside the UpdatePanel. However, playing with the <i>sender</i> and <i>args</i> parameters of the <i>BeginRequestHandler</i> method, you can add some logic to decide which controls and UpdatePanels to block. I recommend visiting the <a href="http://msdn.microsoft.com/en-us/library/bb311028.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/bb311028.aspx?referer=');">PageRequestManager</a> page documentation for more information.
</p>
<p>
Finally, here&#8217;s a fully working example of a very simple web page. Notice that you&#8217;ll have to download <i>jquery.js</i> and <i>jquery.blockUI.js</i> from both websites I mentioned earlier.
</p>
<p>
Default.aspx.
</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="asp asp" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold">@</span> Page Language<span style="color: #006600; font-weight: bold">=</span><span style="color: #cc0000;">&quot;C#&quot;</span> AutoEventWireup<span style="color: #006600; font-weight: bold">=</span><span style="color: #cc0000;">&quot;true&quot;</span> CodeBehind<span style="color: #006600; font-weight: bold">=</span><span style="color: #cc0000;">&quot;Default.aspx.cs&quot;</span> Inherits<span style="color: #006600; font-weight: bold">=</span><span style="color: #cc0000;">&quot;UpdatePanelBlockExample._Default&quot;</span> <span style="color: #0000ff; font-weight: bold;">%&gt;</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold">@</span> Register Assembly<span style="color: #006600; font-weight: bold">=</span><span style="color: #cc0000;">&quot;System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;</span>
    Namespace<span style="color: #006600; font-weight: bold">=</span><span style="color: #cc0000;">&quot;System.Web.UI&quot;</span> TagPrefix<span style="color: #006600; font-weight: bold">=</span><span style="color: #cc0000;">&quot;asp&quot;</span> <span style="color: #0000ff; font-weight: bold;">%&gt;</span>
&nbsp;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&nbsp;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt;
&lt;head runat=&quot;server&quot;&gt;
    &lt;title&gt;&lt;/title&gt;
    &lt;script src=&quot;jquery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;jquery.blockUI.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id=&quot;form1&quot; runat=&quot;server&quot;&gt;
    &lt;div&gt;
        &lt;asp:ScriptManager ID=&quot;ScriptManager1&quot; runat=&quot;server&quot;&gt;
        &lt;/asp:ScriptManager&gt;
        &lt;asp:UpdatePanel ID=&quot;UpdatePanel1&quot; runat=&quot;server&quot;&gt;
        &lt;ContentTemplate&gt;
            &lt;asp:Button ID=&quot;Button1&quot; runat=&quot;server&quot; Text=&quot;Button1&quot; onclick=&quot;Button1_Click&quot; /&gt;&lt;asp:Button ID=&quot;Button2&quot;
                runat=&quot;server&quot; Text=&quot;Button2&quot; /&gt;&lt;asp:Label ID=&quot;Label1&quot; runat=&quot;server&quot; Text=&quot;&quot;&gt;&lt;/asp:Label&gt;
        &lt;/ContentTemplate&gt;
        &lt;/asp:UpdatePanel&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
        function BeginRequestHandler(sender, args) {
            $('#<span style="color: #0000ff; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold">=</span> UpdatePanel1.<span style="color: #9900cc;">ClientID</span> <span style="color: #0000ff; font-weight: bold;">%&gt;</span>').block();
        }
    &lt;/script&gt;        
    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

</p>
<p>
Default.aspx.cs.
</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web.UI</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web.UI.WebControls</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Threading</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> UpdatePanelBlockExample
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> partial <span style="color: #FF0000;">class</span> _Default <span style="color: #008000;">:</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">UI</span></span>.<span style="color: #0000FF;">Page</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Page_Load<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3000</span><span style="color: #000000;">&#41;</span>;
            Label1.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">ToLongDateString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Button1_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Thread.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3000</span><span style="color: #000000;">&#41;</span>;
            Label1.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">ToShortDateString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>
</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=Disabling%20UpdatePanels%20when%20an%20asynchronous%20postback%20in%20progress&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2009%2F06%2F08%2Fdisabling-updatepanels-when-an-asynchronous-postback-is-done%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=Disabling_20UpdatePanels_20when_20an_20asynchronous_20postback_20in_20progress_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2009_2F06_2F08_2Fdisabling-updatepanels-when-an-asynchronous-postback-is-done_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2009/06/08/disabling-updatepanels-when-an-asynchronous-postback-is-done/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using IronPython to extend your .NET applications</title>
		<link>http://thinkingeek.com/2009/03/11/using-ironpython-to-extend-your-net-applications/</link>
		<comments>http://thinkingeek.com/2009/03/11/using-ironpython-to-extend-your-net-applications/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 15:44:32 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[.net]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[ironpython]]></category>

		<category><![CDATA[ironruby]]></category>

		<category><![CDATA[python]]></category>

		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=93</guid>
		<description><![CDATA[
One of the interesting new things on the .NET platform is the recent addition of Python and Ruby to the CLR. Both versions for .NET are called IronPython and IronRuby respectively, and they provide some new and good things to the platform.


Python and Ruby lovers will see now that they can use all the library [...]]]></description>
			<content:encoded><![CDATA[<p>
One of the interesting new things on the .NET platform is the recent addition of <a href="http://www.python.org/" onclick="pageTracker._trackPageview('/outgoing/www.python.org/?referer=');">Python</a> and <a href="http://ruby-lang.org/" onclick="pageTracker._trackPageview('/outgoing/ruby-lang.org/?referer=');">Ruby</a> to the CLR. Both versions for .NET are called <a href="http://www.codeplex.com/IronPython" onclick="pageTracker._trackPageview('/outgoing/www.codeplex.com/IronPython?referer=');">IronPython</a> and <a href="http://www.ironruby.net/" onclick="pageTracker._trackPageview('/outgoing/www.ironruby.net/?referer=');">IronRuby</a> respectively, and they provide some new and good things to the platform.
</p>
<p>
Python and Ruby lovers will see now that they can use all the library and features of the .NET platform programming in their favorite scripting language. Since both of them are object oriented, you can now write fully fledged apps using either of them.
</p>
<p>
However, there&#8217;s another interesting application for IronPython and IronRuby: adding scripting support for your existing .NET applications. This can be a very useful and powerful way to extend your applications and give the user freedom to program their own mini programs, scripts or whatever in your applications. It could be good for defining rules, assigning and calculating values, etc.
</p>
<p>
I&#8217;ll provide a simple class you can use to add scripting to your application. I&#8217;ll use IronPython in this example.
</p>
<p>
First of all, you have to download IronPython and install it, and add the references to the assemblies on your project references.
</p>
<p>
The usual way to proceed in those cases is to provide the user of some local variables you give them access to, execute the script, and then recover the values of those or new variables. To do so, You can use a class similar to this one:
</p>
<p>
<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">IronPython.Hosting</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.Scripting.Hosting</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.Scripting</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Scripting
<span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">class</span> PythonEngine
	<span style="color: #000000;">&#123;</span>
        ScriptEngine m_engine;
        ExceptionOperations m_exceptionOperations;
        SortedDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> m_inputVariables;
        <span style="color: #FF0000;">string</span> m_script;
&nbsp;
        <span style="color: #0600FF;">internal</span> PythonEngine<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            m_engine <span style="color: #008000;">=</span> Python.<span style="color: #0000FF;">CreateEngine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            m_exceptionOperations <span style="color: #008000;">=</span> m_engine.<span style="color: #0000FF;">GetService</span><span style="color: #008000;">&lt;</span>ExceptionOperations<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">internal</span> SortedDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> ScriptVariables
        <span style="color: #000000;">&#123;</span>
            set <span style="color: #000000;">&#123;</span> m_inputVariables <span style="color: #008000;">=</span> value; <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">string</span> Script
        <span style="color: #000000;">&#123;</span>
            set <span style="color: #000000;">&#123;</span> m_script <span style="color: #008000;">=</span> value; <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">internal</span> ExceptionOperations ExceptionOperations
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> m_exceptionOperations; <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">internal</span> SortedDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> Execute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//Create structures</span>
            SourceCodeKind sc <span style="color: #008000;">=</span> SourceCodeKind.<span style="color: #0000FF;">Statements</span>;
            ScriptSource source <span style="color: #008000;">=</span> m_engine.<span style="color: #0000FF;">CreateScriptSourceFromString</span><span style="color: #000000;">&#40;</span>m_script, sc<span style="color: #000000;">&#41;</span>;
            ScriptScope scope <span style="color: #008000;">=</span> m_engine.<span style="color: #0000FF;">CreateScope</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">//Fill input variables</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>KeyValuePair<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> variable <span style="color: #0600FF;">in</span> m_inputVariables<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                scope.<span style="color: #0000FF;">SetVariable</span><span style="color: #000000;">&#40;</span>variable.<span style="color: #0000FF;">Key</span>, variable.<span style="color: #0000FF;">Value</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
            SortedDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> outputVariables <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SortedDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">//Execute the script</span>
            <span style="color: #0600FF;">try</span>
            <span style="color: #000000;">&#123;</span>
                source.<span style="color: #0000FF;">Execute</span><span style="color: #000000;">&#40;</span>scope<span style="color: #000000;">&#41;</span>;
                <span style="color: #008080; font-style: italic;">//Recover variables</span>
                <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> variable <span style="color: #0600FF;">in</span> scope.<span style="color: #0000FF;">GetVariableNames</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    outputVariables.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>variable, scope.<span style="color: #0000FF;">GetVariable</span><span style="color: #000000;">&#40;</span>variable<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception e<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">string</span> error <span style="color: #008000;">=</span> m_exceptionOperations.<span style="color: #0000FF;">FormatException</span><span style="color: #000000;">&#40;</span>e<span style="color: #000000;">&#41;</span>;
                <span style="color: #008080; font-style: italic;">//Do something with the pretty printed error</span>
                throw;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">return</span> outputVariables;
        <span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</p>
<p>
Usage of this class is pretty simple. You have to provide the object the script you want to execute and the input variables the script will have available as local variables. Once this is done, you have to call the Execute method, and this method will either return the output variables of the execution of the resulting script, or throw an exception.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=Using%20IronPython%20to%20extend%20your%20.NET%20applications&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2009%2F03%2F11%2Fusing-ironpython-to-extend-your-net-applications%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=Using_20IronPython_20to_20extend_20your_20.NET_20applications_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2009_2F03_2F11_2Fusing-ironpython-to-extend-your-net-applications_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2009/03/11/using-ironpython-to-extend-your-net-applications/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Full view of ComboBox drop-down list components in C# 3.0</title>
		<link>http://thinkingeek.com/2008/11/18/full-view-of-combobox-drop-down-list-components-in-c-30/</link>
		<comments>http://thinkingeek.com/2008/11/18/full-view-of-combobox-drop-down-list-components-in-c-30/#comments</comments>
		<pubDate>Tue, 18 Nov 2008 12:43:02 +0000</pubDate>
		<dc:creator>alopez</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[.net]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[programming tips]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=88</guid>
		<description><![CDATA[By default in C# 3.0 ComboBox controls don’t provide support for showing drop-down list items if they exceed the width of their parent ComboBox, like this one:


This is annoying because users cannot read properly the information. To solve that problem, all we have to do is derive the ComboBox class and override the DropDown event [...]]]></description>
			<content:encoded><![CDATA[<p>By default in C# 3.0 ComboBox controls don’t provide support for showing drop-down list items if they exceed the width of their parent ComboBox, like this one:
</p>
<div id="attachment_89" class="wp-caption aligncenter" style="width: 246px"><a href="http://thinkingeek.com/wp-content/uploads/2008/11/image001.png"  rel="lightbox[roadtrip]"><img src="http://thinkingeek.com/wp-content/uploads/2008/11/image001.png" alt="Cropped ComboBox" title="Cropped ComboBox" width="236" height="123" class="size-medium wp-image-89" /></a><p class="wp-caption-text">Cropped ComboBox</p></div>
<p>
This is annoying because users cannot read properly the information. To solve that problem, all we have to do is derive the ComboBox class and override the DropDown event as follows:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ComboBoxEx <span style="color: #008000;">:</span> ComboBox
<span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> ComboBoxEx<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		<span style="color: #008000;">:</span> <span style="color: #0600FF;">base</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span>
		DropDown <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> EventHandler<span style="color: #000000;">&#40;</span>event_DropDown<span style="color: #000000;">&#41;</span>;
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">void</span> event_DropDown<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">try</span>
		<span style="color: #000000;">&#123;</span>
			ComboBox comboBox <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>ComboBox<span style="color: #000000;">&#41;</span>sender; <span style="color: #008080; font-style: italic;">// Catch the combo firing this event</span>
			<span style="color: #FF0000;">int</span> width <span style="color: #008000;">=</span> comboBox.<span style="color: #0000FF;">Width</span>; <span style="color: #008080; font-style: italic;">// Current width for ComboBox</span>
			Graphics g <span style="color: #008000;">=</span> comboBox.<span style="color: #0000FF;">CreateGraphics</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>; <span style="color: #008080; font-style: italic;">// Get graphics for ComboBox</span>
			Font font <span style="color: #008000;">=</span> comboBox.<span style="color: #0000FF;">Font</span>; <span style="color: #008080; font-style: italic;">// Doesn't change original font</span>
&nbsp;
			<span style="color: #008080; font-style: italic;">//checks if a scrollbar will be displayed.</span>
			<span style="color: #FF0000;">int</span> vertScrollBarWidth;
			<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>comboBox.<span style="color: #0000FF;">Items</span>.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> comboBox.<span style="color: #0000FF;">MaxDropDownItems</span><span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#125;</span>
				<span style="color: #008080; font-style: italic;">//If yes, then get its width to adjust the size of the drop down list.</span>
				vertScrollBarWidth <span style="color: #008000;">=</span> SystemInformation.<span style="color: #0000FF;">VerticalScrollBarWidth</span>;
			<span style="color: #000000;">&#125;</span>
			<span style="color: #0600FF;">else</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #008080; font-style: italic;">//Otherwise set to 0</span>
				vertScrollBarWidth <span style="color: #008000;">=</span> 0;
			<span style="color: #000000;">&#125;</span>
			<span style="color: #008080; font-style: italic;">//Loop through list items and check size of each items.</span>
			<span style="color: #008080; font-style: italic;">//set the width of the drop down list to the width of the largest item.</span>
			<span style="color: #FF0000;">int</span> newWidth;
			<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> s <span style="color: #0600FF;">in</span> comboBox.<span style="color: #0000FF;">Items</span><span style="color: #000000;">&#41;</span>
			<span style="color: #000000;">&#123;</span>
				<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>s <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
				<span style="color: #000000;">&#123;</span>
					newWidth <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span>g.<span style="color: #0000FF;">MeasureString</span><span style="color: #000000;">&#40;</span>s.<span style="color: #0000FF;">Trim</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, font<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Width</span> <span style="color: #008000;">+</span> vertScrollBarWidth;
					<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>width <span style="color: #008000;">&lt;</span> newWidth<span style="color: #000000;">&#41;</span>
						width <span style="color: #008000;">=</span> newWidth;
				<span style="color: #000000;">&#125;</span>
			<span style="color: #000000;">&#125;</span>
			<span style="color: #008080; font-style: italic;">// Finally, adjust the new width</span>
			comboBox.<span style="color: #0000FF;">DropDownWidth</span> <span style="color: #008000;">=</span> width;
		<span style="color: #000000;">&#125;</span>
		<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#123;</span>  <span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>   
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The following picture shows the results of using the above control instead of the default one:
</p>
<div id="attachment_90" class="wp-caption aligncenter" style="width: 246px"><a href="http://thinkingeek.com/wp-content/uploads/2008/11/image003.png"  rel="lightbox[roadtrip]"><img src="http://thinkingeek.com/wp-content/uploads/2008/11/image003.png" alt="Non Cropped ComboBox" title="Non Cropped ComboBox" width="236" height="123" class="size-medium wp-image-90" /></a><p class="wp-caption-text">Non Cropped ComboBox</p></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=Full%20view%20of%20ComboBox%20drop-down%20list%20components%20in%20C%23%203.0&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2008%2F11%2F18%2Ffull-view-of-combobox-drop-down-list-components-in-c-30%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=Full_20view_20of_20ComboBox_20drop-down_20list_20components_20in_20C_23_203.0_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2008_2F11_2F18_2Ffull-view-of-combobox-drop-down-list-components-in-c-30_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2008/11/18/full-view-of-combobox-drop-down-list-components-in-c-30/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Controlling the commands executed with xp_cmdshell on SQL Server 2005</title>
		<link>http://thinkingeek.com/2008/11/13/controlling-the-commands-executed-with-xp_cmdshell-on-sql-server-2005/</link>
		<comments>http://thinkingeek.com/2008/11/13/controlling-the-commands-executed-with-xp_cmdshell-on-sql-server-2005/#comments</comments>
		<pubDate>Thu, 13 Nov 2008 17:04:44 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[security]]></category>

		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=81</guid>
		<description><![CDATA[
SQL Server has a special extended stored procedure called xp_cmdshell. This procedure has a lot of power: it allows to execute any command line code on the machine hosting the SQL Server.


Imagine you want to list all the files on C: on the SQL Server Windows host: you could write a T-SQL statement like this [...]]]></description>
			<content:encoded><![CDATA[<p>
SQL Server has a special extended stored procedure called <em>xp_cmdshell</em>. This procedure has a lot of power: it allows to execute any command line code on the machine hosting the SQL Server.
</p>
<p>
Imagine you want to list all the files on <em>C:</em> on the SQL Server Windows host: you could write a T-SQL statement like this one:
</p>

<div class="wp_syntax"><div class="code"><pre class="sql sql" style="font-family:monospace;">EXECUTE master<span style="color: #66cc66;">..</span>xp_cmdshell <span style="color: #ff0000;">'dir c:'</span></pre></div></div>

<p>
This stored procedure, however, is a very dangerous one, as it would allow to execute harmful code. This is the reason why it&#8217;s disabled by default. Even when enabled, only users on the <em>sysadmin</em> role can use it.
</p>
<p>
If you ever need some users the ability to run only some specific commands with xp_cmdshell, you can use the method I&#8217;ll explain below, making use of the <em>EXECUTE AS</em> modifier of the stored procedure definitions in T-SQL.
</p>
<p><span id="more-81"></span></p>
<p>
The proposed solution involves five steps:</p>
<ul>
<li>Enabling the <em>xp_cmdshell</em> extended procedure.</li>
<li>Adding a procedure on the database with the <em>EXECUTE AS</em> modifier as an administrator, controlling which commands are allowed to be executed.</li>
<li>Modifying or creating the <em>xp_cmdshell_proxy_account</em>, associating it to a user with <em>sysadmin</em> privileges.</li>
<li>Giving the user(s) you want the <em>EXECUTE</em> privileges to the procedure.</li>
<li>Grant the proxy account user the privilege to log on as a batch in the Windows server.</li>
</ul>
<p>
The execution of <em>xp_cmdshell</em> must be enabled on the SQL Server. This can be done through the SQL Surface Area Configuration utility or by code. Refer to Figure below on how to activate xp_cmdshell through the SQL Surface Area Configuration.
</p>
<div id="attachment_82" class="wp-caption aligncenter" style="width: 310px"><a href="http://thinkingeek.com/wp-content/uploads/2008/11/sql1.gif"  rel="lightbox[roadtrip]"><img src="http://thinkingeek.com/wp-content/uploads/2008/11/sql1-300x226.gif" alt="SQL Surface Area" title="sqlsurface" width="300" height="226" class="size-medium wp-image-82" /></a><p class="wp-caption-text">SQL Surface Area</p></div>
<p>
To enable <em>xp_cmdshell</em> using SQL code, use the sentences below:</p>

<div class="wp_syntax"><div class="code"><pre class="sql sql" style="font-family:monospace;">EXEC master<span style="color: #66cc66;">.</span>dbo<span style="color: #66cc66;">.</span>sp_configure <span style="color: #ff0000;">'show advanced options'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span>
RECONFIGURE
EXEC master<span style="color: #66cc66;">.</span>dbo<span style="color: #66cc66;">.</span>sp_configure <span style="color: #ff0000;">'xp_cmdshell'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span>
RECONFIGURE</pre></div></div>

</p>
<p>
<b>This will allow users of the <em>sysadmin</em> role, and no one else, to execute <em>xp_cmdshell</em>.</b>
</p>
<p>
Now we have to create a special stored procedure that will control the actions used as parameters to <em>xp_cmdshell</em>. This will allow the administrators of the database to have control over which commands they allow to be executed on their servers. The most important part of this procedure is the <em>EXECUTE AS OWNER</em> modifier. By using this modifier, everyone that runs that procedure will be able to run it as if it was the owner of the database, thus having execute permissions to <em>xp_cmdshell</em> (we&#8217;re assuming the procedure will be created in the <em>master</em> schema. By granting execute permissions on that procedure, you will allow specific users an indirect way to call the <em>xp_cmdshell</em>.
</p>
<p>
Using this method, only the users of the <em>sysadmin</em> role will be able to execute <em>xp_cmdshell</em>, and only the users you grant <em>EXECUTE</em> permissions on the stored procedure will be able to execute the specific commands that you allow.
</p>
<p>
To insert the store procedure, log in as a <em>sysadmin</em> on the database and create it with the <a href="http://msdn.microsoft.com/en-us/library/ms188354.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/ms188354.aspx?referer=');"><em>EXECUTE AS OWNER</em></a> modifier on it.
</p>
<p>
For the above procedure to work on non <em>sysadmin</em> accounts there is another step that has to be done. By default, even if you have permissions on the store procedure, you won’t be able to execute it if you’re not on the <em>sysadmin</em> role. This is because those users need a proxy account that is used as the account in which the <em>xp_cmdshell</em> is executed.
</p>
<p>
So, for this procedure to work, you must create or modify the <em>xp_cmdshell_proxy_account</em> with a user within the <em>sysadmin</em> role. To setup this account, proceed with the code below:</p>

<div class="wp_syntax"><div class="code"><pre class="sql sql" style="font-family:monospace;">EXEC sp_xp_cmdshell_proxy_account <span style="color: #ff0000;">'MyDomain<span style="color: #000099; font-weight: bold;">\M</span>yUserName'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'myDomainPassword'</span></pre></div></div>

</p>
<p>
If the above code does not work, try this one:</p>

<div class="wp_syntax"><div class="code"><pre class="sql sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> credential <span style="color: #808080; font-style: italic;">##xp_cmdshell_proxy_account## with identity = 'Domain\DomainUser', secret =  password'</span></pre></div></div>

</p>
<p>
After the procedure and the proxy account have been set, the users we want to be able to execute the procedure must be granted <em>EXECUTE</em> permission on it. To do so, execute this statement for every user you want to grant permissions:</p>

<div class="wp_syntax"><div class="code"><pre class="sql sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">GRANT</span> EXECUTE <span style="color: #993333; font-weight: bold;">ON</span> Tango_xp_cmdshell <span style="color: #993333; font-weight: bold;">TO</span> <span style="color: #66cc66;">&lt;</span>username<span style="color: #66cc66;">&gt;</span>;
GO</pre></div></div>

</p>
<p>
To grant this permission, use the <em>Local Security Settings</em> on the <em>Administrative Tools</em> interface of the <em>Windows Control Panel</em>. Once there locate the property shown on the screenshot and add the user you gave permissions to the user list.
</p>
<div id="attachment_83" class="wp-caption aligncenter" style="width: 310px"><a href="http://thinkingeek.com/wp-content/uploads/2008/11/sql2.png"  rel="lightbox[roadtrip]"><img src="http://thinkingeek.com/wp-content/uploads/2008/11/sql2-300x211.png" alt="Local Security Policy" title="LocalSecurityPolicies" width="300" height="211" class="size-medium wp-image-83" /></a><p class="wp-caption-text">Local Security Policy</p></div>
<p>
<b>Note that enabling the <em>xp_cmdshell</em> command may still have some security implications, so try to avoid it when possible.</b></p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=Controlling%20the%20commands%20executed%20with%20xp_cmdshell%20on%20SQL%20Server%202005&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2008%2F11%2F13%2Fcontrolling-the-commands-executed-with-xp_cmdshell-on-sql-server-2005%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=Controlling_20the_20commands_20executed_20with_20xp_cmdshell_20on_20SQL_20Server_202005_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2008_2F11_2F13_2Fcontrolling-the-commands-executed-with-xp_cmdshell-on-sql-server-2005_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2008/11/13/controlling-the-commands-executed-with-xp_cmdshell-on-sql-server-2005/feed/</wfw:commentRss>
		</item>
		<item>
		<title>C# and the StringBuilder class</title>
		<link>http://thinkingeek.com/2008/07/16/c-and-the-stringbuilder-class/</link>
		<comments>http://thinkingeek.com/2008/07/16/c-and-the-stringbuilder-class/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 17:07:37 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[.net]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[Java]]></category>

		<category><![CDATA[programming tips]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=67</guid>
		<description><![CDATA[This morning I was working on a project at work. It&#8217;s a Web Application using the ASP .NET 2.0 framework and C# as a code behind language. My friend Ioannis came over to see what was I doing and when he saw I was appending some strings together he asked me this question: &#8220;are you [...]]]></description>
			<content:encoded><![CDATA[<p>This morning I was working on a project at work. It&#8217;s a Web Application using the ASP .NET 2.0 framework and C# as a code behind language. My friend Ioannis came over to see what was I doing and when he saw I was appending some strings together he asked me this question: &#8220;<em>are you using a StringBuilder to use those strings?</em>&#8220;. And I replied with this answer: &#8220;<em>no, I am not</em>&#8220;. This kind of stupid dialog came over because last week we were discussing about using StringBuilders instead of the default String class operators to append strings each other in Java. It seemed using the StringBuilder class resulted in an overall performance gain. It was then when I asked: &#8220;<em>don&#8217;t tell me this happens with C#, too?</em>&#8220;. And he answered: &#8220;<em>yes, it does!</em>&#8220;.</p>
<p>So, what&#8217;s the matter with StringBuilders in C#?</p>
<p><span id="more-67"></span></p>
<p>It seems the same thing happens with Strings, C# and Java. Here is a copy paste from the <a href="http://msdn2.microsoft.com/en-us/library/2839d5h5%28vs.80%29.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn2.microsoft.com/en-us/library/2839d5h5_28vs.80_29.aspx?referer=');">MSDN web page</a> about the StringBuilder usage:</p>
<blockquote><p>
The <strong>String</strong> object is immutable. Every time you use one of the methods in the <strong>System.String</strong> class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new <strong>String</strong> object can be costly. The <a href="http://msdn2.microsoft.com/en-us/library/system.text.stringbuilder%28VS.80%29.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn2.microsoft.com/en-us/library/system.text.stringbuilder_28VS.80_29.aspx?referer=');">System.Text.StringBuilder</a> class can be used when you want to modify a string without creating a new object. For example, using the <strong>StringBuilder</strong> class can boost performance when concatenating many strings together in a loop.
</p></blockquote>
<p>
So I decided to run some tests to see how much it was worth to change my code to use the StringBuilder class, because I use the string &#8216;+&#8217; operator a lot in my program, and the results are simply amazing. Here you can find a chart comparing the times it took to concatenate a given number of strings using both methods. See for yourself and then&#8230; use StringBuilders from now on!
</p>
<div id="attachment_68" class="wp-caption aligncenter" style="width: 310px"><a href="http://thinkingeek.com/wp-content/uploads/2008/11/string.png"  rel="lightbox[roadtrip]"><img src="http://thinkingeek.com/wp-content/uploads/2008/11/string-300x180.png" alt="String usage" title="String usage" width="300" height="180" class="size-medium wp-image-68" /></a><p class="wp-caption-text">String usage</p></div>
<div id="attachment_69" class="wp-caption aligncenter" style="width: 310px"><a href="http://thinkingeek.com/wp-content/uploads/2008/11/stringbuilder.png"  rel="lightbox[roadtrip]"><img src="http://thinkingeek.com/wp-content/uploads/2008/11/stringbuilder-300x180.png" alt="StringBuilder usage" title="StringBuilder usage" width="300" height="180" class="size-medium wp-image-69" /></a><p class="wp-caption-text">StringBuilder usage</p></div>
<p>
Here&#8217;s the source code i used if you want to try it for yourself:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span>;
&nbsp;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Adapdev.Diagnostics</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> SBuilder
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            HiPerfTimer timer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> HiPerfTimer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> 0; i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">100</span>; i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                StringBuilder sb <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                timer.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> j <span style="color: #008000;">=</span> 0; j <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">1000</span> <span style="color: #008000;">&lt;</span>strong<span style="color: #008000;">&gt;</span> i; j<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    sb.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>j<span style="color: #000000;">&#41;</span>;
                <span style="color: #000000;">&#125;</span>
                timer.<span style="color: #0000FF;">Stop</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #FF0000;">double</span> timeStringBuilder <span style="color: #008000;">=</span> timer.<span style="color: #0000FF;">Duration</span>;
&nbsp;
                <span style="color: #FF0000;">string</span> s <span style="color: #008000;">=</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Empty</span>;
                timer.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> j <span style="color: #008000;">=</span> 0; j <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">1000</span> <span style="color: #008000;">&lt;/</span>strong<span style="color: #008000;">&gt;</span> i; j<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    s <span style="color: #008000;">+=</span> j;
                <span style="color: #000000;">&#125;</span>
                timer.<span style="color: #0000FF;">Stop</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #FF0000;">double</span> timeString <span style="color: #008000;">=</span> timer.<span style="color: #0000FF;">Duration</span>;
&nbsp;
                StringBuilder line <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                line.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1000</span> <span style="color: #008000;">*</span> i<span style="color: #000000;">&#41;</span>;
                line.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;;&quot;</span><span style="color: #000000;">&#41;</span>;
                line.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>timeStringBuilder<span style="color: #000000;">&#41;</span>;
                line.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;;&quot;</span><span style="color: #000000;">&#41;</span>;
                line.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>timeString<span style="color: #000000;">&#41;</span>;
                <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Console</span>.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>line.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
You can download the external timer classes from <a href="http://www.codeproject.com/csharp/highperformancetimercshar.asp" onclick="pageTracker._trackPageview('/outgoing/www.codeproject.com/csharp/highperformancetimercshar.asp?referer=');">The Code Project</a>.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=C%23%20and%20the%20StringBuilder%20class&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2008%2F07%2F16%2Fc-and-the-stringbuilder-class%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=C_23_20and_20the_20StringBuilder_20class_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2008_2F07_2F16_2Fc-and-the-stringbuilder-class_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2008/07/16/c-and-the-stringbuilder-class/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Repeatable read and deadlocks in SQL Server</title>
		<link>http://thinkingeek.com/2007/09/23/repeatable-read-and-deadlocks-in-sql-server/</link>
		<comments>http://thinkingeek.com/2007/09/23/repeatable-read-and-deadlocks-in-sql-server/#comments</comments>
		<pubDate>Sun, 23 Sep 2007 17:32:01 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[sql server]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=78</guid>
		<description><![CDATA[This week we had a bug report of one of our products regarding some strange deadlocks in our database access. For those of you who don&#8217;t know what a deadlock is, I&#8217;ll try to summarize here what a transaction is in a relational database environment and why those transactions might lead to those nasty errors, [...]]]></description>
			<content:encoded><![CDATA[<p>This week we had a bug report of one of our products regarding some strange deadlocks in our database access. For those of you who don&#8217;t know what a deadlock is, I&#8217;ll try to summarize here what a transaction is in a relational database environment and why those transactions might lead to those nasty errors, and try to explain what was causing this deadlock in our SQL Server 2005 engine.</p>
<p><span id="more-78"></span></p>
<p>
One of the most interesting features of any good database engine is what we call concurrency. Concurrency means than the database engine should be able to perform a lot of data operations at the same time. This leads to some interesting problems that have a critical impact on another of the features that any database engine must ensure: data consistency.
</p>
<p>
Sometimes you need to perform more than one non atomic operation in a database that only make sense in a block. This is, all those operations should be executed from the start to the end without any other interference from other operations, because those other operations may have a non desired impact in your operations. The simulation of the atomic execution of more than one operation in databases is done by transactions. When you embrace a set of operations in a transaction, you are telling the database engine that you want those operations to be executed as if they were executed in an isolated mode, this is, with no interference from other operations.
</p>
<p>
While this might seem easy to accomplish, it can also have a big negative performance impact, because you can&#8217;t plan on executing all the transactions that arrive at the same time in a sequential way, at least not if you want your database engine to be slow, very slow.
</p>
<p>
This is where locks ans isolation levels intervene. Locks are protections made to some resources to allow or forbid further access to those resources by another processes. An exclusive lock, for example, done by a process, means that no other process should be able to access that resource until the first process has freed the lock. There are a lot of different locks in SQL Server, which you can review at <a href="http://msdn2.microsoft.com/en-us/library/ms175519.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn2.microsoft.com/en-us/library/ms175519.aspx?referer=');">http://msdn2.microsoft.com/en-us/library/ms175519.aspx</a>.
</p>
<p>
One of the problems we can face when working with transactions is the well known repeatable read. Suppose a process A starts a transaction and reads a registry with a select clause in a table. After that, another transaction comes in and modifies that data. The first transaction reads the same data again and gets a different value, becuase it was modified by the second transaction. This is inconsistent, because as we are executing a set of operations inside a transaction, we expect them to be executed as if no one else was modifying the data we need to use.
</p>
<p>
Because of that, there&#8217;s a special isolation level called, precisely, Repeatable Read, which has a locking policy to avoid those problems. But be careful with this, since this can cause a nasty deadlock in your SQL Server if used the wrong way.
</p>
<p>
A deadlock is a special situation where two or more transactions are waiting each other. Imagine trasaction A starts some operations and locks some resources. Later, transaction B comes in, locks another set of resources, and then tries to access resources locked by A, so it waits for A to free those resources. After that, A tries to lock resources locked by B and wait for B to free them. A is waiting for B to free its resources, and B is waiting for A to do the very same thing. We have a deadlock. One of the transactions must be killed by the database engine and rolled back so the other one can continue. Altough this is something you might be able to control by code and issue a relaunch of the killed transaction, this is something usually not desired.
</p>
<p>
I&#8217;m going to talk now about a deadlock you may face when using the Repeatable Read transaction isolation level with SQL Server 2005. Imagine you have two transactions that do the same thing: read a value, modify it, and read it again. Note that you will be modifying the value, but you set the isolation mode to Repeatable Read (this is, setting the wrong isolation mode by mistake or by ignorance). Transaction A starts and reads the value. SQL Server puts a shared lock on that resource. Transaction B starts and reads the value. Because the lock in A was shared, B can also read that value, gaining a shared lock too. Now transaction B tries to write that value. Because the shared lock put by A was read only, B has to wait for A to release its shared lock to be able to gain write acces to it, so it blocks. After that, A tries to write the value, and because now it&#8217;s transaction B that has a shared lock on the resource, it has to wait too. And there it is, the deadlock.
</p>
<p>
The key in avoiding this is that, although we perform a read-write-read operation, we don&#8217;t need the second read to be the same as the first, because we are modifying that resource. In this case, the lock our transactions should get is an update lock, which knows that we&#8217;ll be modifying that data after having read it. This way, when transaction A locks the resource, the lock will not be shared, so transaction B will have to wait for A to write the new value before B gets the lock, thus avoiding the deadlock. Another option is use an isolation level that frees the locks just after having read the value, and not maintaining it until the next update.
</p>
<p>
The conclusion to this is: be careful when working with transactions on which isolation level you use on them, and be sure you&#8217;re using the right one if you don&#8217;t want to have bug reports when a lof of concurrency starts to stress the database engine!</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=Repeatable%20read%20and%20deadlocks%20in%20SQL%20Server&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2007%2F09%2F23%2Frepeatable-read-and-deadlocks-in-sql-server%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=Repeatable_20read_20and_20deadlocks_20in_20SQL_20Server_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2007_2F09_2F23_2Frepeatable-read-and-deadlocks-in-sql-server_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2007/09/23/repeatable-read-and-deadlocks-in-sql-server/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Killing all rails logs with one Ctrl+C?</title>
		<link>http://thinkingeek.com/2007/09/08/killing-all-rails-logs-with-one-ctrlc/</link>
		<comments>http://thinkingeek.com/2007/09/08/killing-all-rails-logs-with-one-ctrlc/#comments</comments>
		<pubDate>Sat, 08 Sep 2007 17:28:12 +0000</pubDate>
		<dc:creator>jsegura</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[bash]]></category>

		<category><![CDATA[ruby]]></category>

		<category><![CDATA[ruby on rails]]></category>

		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=76</guid>
		<description><![CDATA[Well, this is my first post after holidays and it won&#8217;t be very long.
Imagine you are developing a rails application. Usually you have:

a terminal with the server to see what petitions are received.
 a terminal with a tail of development.log to see what happens with the database.
 a terminal with a tail of test.log if [...]]]></description>
			<content:encoded><![CDATA[<p>Well, this is my first post after holidays and it won&#8217;t be very long.</p>
<p>Imagine you are developing a rails application. Usually you have:</p>
<ul>
<li>a terminal with the server to see what petitions are received.</li>
<li> a terminal with a tail of development.log to see what happens with the database.</li>
<li> a terminal with a tail of test.log if you are testing something.</li>
</ul>
<p>
This are a <strong>lot</strong> of windows&#8230; And the other day one friends was very happy and after asking for a while I discovered that the reason was the simple line showed above&#8230; With only one <strong>Ctrl+C</strong> you can kill all this processes <img src='http://thinkingeek.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">script<span style="color: #000000; font-weight: bold;">/</span>server <span style="color: #000000; font-weight: bold;">&amp;</span> <span style="color: #c20cb9; font-weight: bold;">tail</span> <span style="color: #660033;">-f</span> log<span style="color: #000000; font-weight: bold;">/</span>development.log <span style="color: #000000; font-weight: bold;">&amp;</span> <span style="color: #c20cb9; font-weight: bold;">tail</span> <span style="color: #660033;">-f</span> log<span style="color: #000000; font-weight: bold;">/</span>test.log <span style="color: #000000; font-weight: bold;">&amp;</span> <span style="color: #c20cb9; font-weight: bold;">tail</span> <span style="color: #660033;">-f</span> ; <span style="color: #7a0874; font-weight: bold;">jobs</span> <span style="color: #660033;">-p</span> | <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{print &quot;kill -2 &quot; $0}'</span> | <span style="color: #c20cb9; font-weight: bold;">sh</span></pre></div></div>

<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=Killing%20all%20rails%20logs%20with%20one%20Ctrl%2BC%3F&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2007%2F09%2F08%2Fkilling-all-rails-logs-with-one-ctrlc%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=Killing_20all_20rails_20logs_20with_20one_20Ctrl_2BC_3F_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2007_2F09_2F08_2Fkilling-all-rails-logs-with-one-ctrlc_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2007/09/08/killing-all-rails-logs-with-one-ctrlc/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The Double Check Design Pattern</title>
		<link>http://thinkingeek.com/2007/07/29/the-double-check-design-pattern/</link>
		<comments>http://thinkingeek.com/2007/07/29/the-double-check-design-pattern/#comments</comments>
		<pubDate>Sun, 29 Jul 2007 17:21:37 +0000</pubDate>
		<dc:creator>brafales</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[design patterns]]></category>

		<category><![CDATA[programming tips]]></category>

		<guid isPermaLink="false">http://thinkingeek.com/?p=74</guid>
		<description><![CDATA[One of the deficiencies of actual programming languages, specially those ones still widely used that are old, such as C or C++, is that they were designed having in mind the sequential programming paradigm. This usually means that those languages don&#8217;t have standard ways to work with multithreading features, and you usually have to rely [...]]]></description>
			<content:encoded><![CDATA[<p>One of the deficiencies of actual programming languages, specially those ones still widely used that are old, such as C or C++, is that they were designed having in mind the sequential programming paradigm. This usually means that those languages don&#8217;t have standard ways to work with multithreading features, and you usually have to rely on third party libraries to develop thread safe software.</p>
<p>Today I&#8217;ll be discussing a design pattern called <em>Double Check</em>, which can be widely used to manage the resource access, elimination and initialization in a safe thread way.</p>
<p><span id="more-74"></span></p>
<p>Consider another common design pattern: the <a href="http://en.wikipedia.org/wiki/Singleton_pattern" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Singleton_pattern?referer=');">Singleton Pattern</a>. A singleton is a special class which is allowed to have one and only one instance in a program. This pattern can be used in a variety of ways, one of the most usual one is to store global program information, which, as its name states, is global and unique to the application, so having more than one instance of that class would have the burden to mantain them synchronized, or even more nasty consequences.</p>
<p>There are different ways to implement a singleton class. I will focus on C#, but the example shown here could be easily extended to other languages such as C++ or Java. The trick on the pattern consists on declaring the class constructor private. This way we can be sure no one will be creating new instances of that class at will. After having done this, we have to provide a public method, which usually has the name getInstance, that will be the one actually creating this item and returning it to the caller.</p>
<p>The code would look similar to this one:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">sealed</span> <span style="color: #FF0000;">class</span> Singleton
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> Singleton instance <span style="color: #008000;">=</span> null;
&nbsp;
    <span style="color: #0600FF;">private</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Singleton Instance
    <span style="color: #000000;">&#123;</span>
        get
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>instance <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                instance <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #0600FF;">return</span> instance;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Another way to create this singleton class would be doing the instantiation of the private variable on the class itself and not on the <em>getInstance</em> method, but this second way gives us a <em>lazy initialization</em>, so the variable is actually instantiated only when it&#8217;s needed, and never before (who knows, maybe we will never need it in some circumstances).</p>
<p>This implementation is perfect&#8230; as long as this method isn&#8217;t called twice (or more) at the same time. Consider what would happen if two threads requested an instance of the singleton class: both threads would check for the instance being null, and both threads would create the instance. That would sure lead to an unknown behaviour, and more than one instance of the class would be in the program, which is exactly what we wanted to avoid.</p>
<p>The first solution that comes in mind is to lock the method so multiple threads must wait to enter the method and get the singleton instance. It would look like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">sealed</span> <span style="color: #FF0000;">class</span> Singleton
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> Singleton instance <span style="color: #008000;">=</span> null;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">object</span> sempahore <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">Object</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #0600FF;">private</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Singleton Instance
    <span style="color: #000000;">&#123;</span>
        get
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">lock</span><span style="color: #000000;">&#40;</span>semaphore<span style="color: #000000;">&#41;</span>;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>instance <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                instance <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #0600FF;">return</span> instance;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This way we ensure that if n threads try to access the routine at the same time, only one will be initializing the singleton instance, since when the others gain the access to the method again, that instance won&#8217;t be null anymore. However, even if this solution is valid and works, it has a serious performance problem. Consider the situation where the instance has been already created. Then more than one thread access the routine again to get that instance. What will happen is that those threads will have to block and wait for other threads to finish, even if the instance is not null, so in any case will be created again. Conclusion: we are blocking threads that don&#8217;t need to be blocked. &#8220;<em>Ok, you may say, we will put the lock inside the if clause, and we&#8217;ll have the issue resolved</em>&#8220;. Let&#8217;s take a look at this solution:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">sealed</span> <span style="color: #FF0000;">class</span> Singleton
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> Singleton instance <span style="color: #008000;">=</span> null;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">object</span> sempahore <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">Object</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #0600FF;">private</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Singleton Instance
    <span style="color: #000000;">&#123;</span>
        get
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>instance <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">lock</span><span style="color: #000000;">&#40;</span>semaphore<span style="color: #000000;">&#41;</span>;
                instance <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">return</span> instance;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
You don&#8217;t have to be a genious to see that this is not working, either. It will work after the instance has been created, because the threads won&#8217;t be entering the if clause, and they won&#8217;t be blocked. But if we are in the same situation as the described in the first place &#8211;this is, more than one thread entering the method before the instance has been created&#8211;, we have the same problem we had before: the singleton will be created more than once.</p>
<p>
The final solution is simple: check again for the variable being null! This is why this pattern is called <em>Double Check</em>. The final code would look like this one:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">sealed</span> <span style="color: #FF0000;">class</span> Singleton
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> Singleton instance <span style="color: #008000;">=</span> null;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">object</span> sempahore <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">Object</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
    <span style="color: #0600FF;">private</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Singleton Instance
    <span style="color: #000000;">&#123;</span>
        get
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>instance <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">lock</span><span style="color: #000000;">&#40;</span>semaphore<span style="color: #000000;">&#41;</span>;
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>instance <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                    instance <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Singleton<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">return</span> instance;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This way, we allow the threads to pass by the if clause if the instance has been already instantiated, and if it has not, the threads will get blocked, and the first one to gain access to the method will do the instantiation. Further threads will check again against the instance being null or not, so it won&#8217;t be created again.
</p>
<p>
Altough this pattern may be implemented similarly in other languages, be aware that, as I said before, a lot of them were never intended to deal with multithreading, and that compiler optimizations may give you code which is not really thread safe, or that actually is not optimized. Here you have a link discussing this issue with Java and C++: <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html" onclick="pageTracker._trackPageview('/outgoing/www.cs.umd.edu/_pugh/java/memoryModel/DoubleCheckedLocking.html?referer=');">http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html</a>.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=Think%20In%20Geek&amp;siteurl=http%3A%2F%2Fthinkingeek.com%2F&amp;linkname=The%20Double%20Check%20Design%20Pattern&amp;linkurl=http%3A%2F%2Fthinkingeek.com%2F2007%2F07%2F29%2Fthe-double-check-design-pattern%2F" onclick="pageTracker._trackPageview('/outgoing/www.addtoany.com/share_save?sitename=Think_20In_20Geek_amp_siteurl=http_3A_2F_2Fthinkingeek.com_2F_amp_linkname=The_20Double_20Check_20Design_20Pattern_amp_linkurl=http_3A_2F_2Fthinkingeek.com_2F2007_2F07_2F29_2Fthe-double-check-design-pattern_2F&amp;referer=');"><img src="http://thinkingeek.com/wp-content/plugins/add-to-any/share_save_120_16.gif" width="120" height="16" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://thinkingeek.com/2007/07/29/the-double-check-design-pattern/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
