<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>George Mamaladze</title>
	<atom:link href="https://gmamaladze.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://gmamaladze.wordpress.com</link>
	<description>Just another WordPress.com site</description>
	<lastBuildDate>Sun, 12 Feb 2012 17:44:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='gmamaladze.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://s-ssl.wordpress.com/i/buttonw-com.png</url>
		<title>George Mamaladze</title>
		<link>https://gmamaladze.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://gmamaladze.wordpress.com/osd.xml" title="George Mamaladze" />
	<atom:link rel='hub' href='https://gmamaladze.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Just launched new open source project QrCode.Net at http://qrcodenet.codeplex.com</title>
		<link>https://gmamaladze.wordpress.com/2011/09/22/just-launched-new-open-source-project-qrcode-net-at-httpqrcodenet-codeplex-com/</link>
		<comments>https://gmamaladze.wordpress.com/2011/09/22/just-launched-new-open-source-project-qrcode-net-at-httpqrcodenet-codeplex-com/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 18:06:18 +0000</pubDate>
		<dc:creator>George Mamaladze</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Data Structures and Algorithms]]></category>

		<guid isPermaLink="false">http://gmamaladze.wordpress.com/?p=152</guid>
		<description><![CDATA[Download binaries and application &#8211; 32K Source code &#8211; 99K Background Recently I was looking for a .NET implementation of QR code generator. Most of components either use online services to generate and/or recognize QR code or the implementation was not &#8220;good enough&#8221; for my purposes. The most popular and very powerful Java implementation comes [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=152&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://qrcodenet.codeplex.com/releases/73746/download/284338">Download binaries and application &#8211; 32K</a><br />
<a href="http://qrcodenet.codeplex.com/releases/73746/download/284339">Source code &#8211; 99K</a></p>
<p><strong>Background</strong></p>
<p>Recently I was looking for a .NET implementation of QR code generator. Most of components either use online services to generate and/or recognize QR code or the implementation was not &#8220;good enough&#8221; for my purposes. The most popular and very powerful Java implementation comes from google&#8217;s open source project <a href="http://code.google.com/p/zxing/" target="_blank">code.google.com/p/zxing</a> called ZXing (Zebra Crossing =&gt; Z=Zebra + X=Cross + ing).</p>
<p>There I found a one-to-one c# port of earlier version. The project is focusing on additional features and further development in Java so it seems that no one is taking care of c# branch.</p>
<p>Thus I have decided to set-up this project <a href="http://qrcodenet.codeplex.com/" target="_blank">QRCode.Net</a> &#8211; <a href="http://qrcodenet.codeplex.com/" target="_blank">qrcodenet.codeplex.com</a>.</p>
<p>As a start point I took a straight forward c# port of google&#8217;s QR code implementation from ZXing project.<br />
I wrote a wrapper around and a demo application which is able to generate QR code from text as you type and save it to file.</p>
<p>In addition it contains a very naive and simple implementation of <strong>Artistic QR code</strong> generation. At the highest error correction level it is possible to create artistic QR codes that still scan correctly, but contain intentional errors to make them more readable or attractive to the human eye, as well as to incorporate colors, logos and other features into the QR code block.</p>
<p><img class="alignnone" title="Artistic QR code" src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Extreme_QR_code_to_Wikipedia_mobile_page.png/141px-Extreme_QR_code_to_Wikipedia_mobile_page.png" alt="" width="141" height="99" /></p>
<p><strong>Using the Library</strong></p>
<p><strong></strong>If you can not wait to try it out just download source or binaries and follow this short guide.</p>
<p><a href="http://qrcodenet.codeplex.com/releases/73746/download/284338">Download binaries and application &#8211; 32K</a><br />
<a href="http://qrcodenet.codeplex.com/releases/73746/download/284339">Source code &#8211; 99K</a></p>
<p>First of all add a reference to project or assembly _Gma.QrCodeNet.Encoding_ and import the namespace.</p>
<p><pre class="brush: csharp;">
using Gma.QrCodeNet.Encoding;
</pre></p>
<p><strong>Sample 1:</strong> Encoding text to QR code bit matrix and printing out the result to console:</p>
<p><pre class="brush: csharp;">
            Console.Write(@&quot;Type some text to QR code: &quot;);
            string sampleText = Console.ReadLine();
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode qrCode = qrEncoder.Encode(sampleText);
            for (int j = 0; j &lt; qrCode.Matrix.Width; j++)
            {
                for (int i = 0; i &lt; qrCode.Matrix.Width; i++)
                {

                    char charToPrint = qrCode.Matrix[i, j] ? '█' : ' ';
                    Console.Write(charToPrint);
                }
                Console.WriteLine();
            }
            Console.WriteLine(@&quot;Press any key to quit.&quot;);
            Console.ReadKey();
</pre></p>
<p><em><strong>Tada !</strong></em></p>
<p><a href="http://gmamaladze.files.wordpress.com/2011/09/consoleoutput1.png"><img class="alignnone size-full wp-image-159" title="ConsoleOutput" src="http://gmamaladze.files.wordpress.com/2011/09/consoleoutput1.png?w=630" alt=""   /></a></p>
<p><strong>Sample 2:</strong> Rendering QR code to graphics, let&#8217;s say to panel control with segment size of 5 pixel, blue on yellow and 10 pixel padding:</p>
<p><pre class="brush: csharp;">
using Gma.QrCodeNet.Rendering;
</pre><br />
<pre class="brush: csharp;">&lt;/span&gt;
&lt;pre&gt;            const string helloWorld = &quot;Hello World!&quot;;

            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode qrCode = qrEncoder.Encode(helloWorld);

            const int moduleSizeInPixels = 5;
            Renderer renderer = new Renderer(moduleSizeInPixels, Brushes.Blue, Brushes.Yellow);

            Panel panel = new Panel();
            Point padding =  new Point(10,16);
            Size qrCodeSize = renderer.Measure(qrCode.Matrix.Width);
            panel.AutoSize = false;
            panel.Size = qrCodeSize + new Size(2 * padding.X, 2 * padding.Y);

            using (Graphics graphics = panel.CreateGraphics())
            {
                renderer.Draw(graphics, qrCode.Matrix, padding);
            }
</pre></p>
<p><strong>Sample 3:<strong> Using out-of-the-box WinForms control. Just drag &amp; drop it to your form an set Text and AutoSize property:</strong></strong></p>
<p><a href="http://gmamaladze.files.wordpress.com/2011/09/usingcontrolscreenshot1.jpg"><img class="alignnone size-full wp-image-160" title="UsingControlScreenshot" src="http://gmamaladze.files.wordpress.com/2011/09/usingcontrolscreenshot1.jpg?w=630&#038;h=257" alt="" width="630" height="257" /></a></p>
<p><strong>Sample 4:<strong> Saving QR code to file:</strong></strong></p>
<p><pre class="brush: csharp;">
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode qrCode = qrEncoder.Encode(&quot;Hello World!&quot;);

            Renderer renderer = new Renderer(5, Brushes.Black, Brushes.White);
            renderer.CreateImageFile(qrCode.Matrix, @&quot;c:\temp\HelloWorld.png&quot;, ImageFormat.Png);
</pre></p>
<p><strong>Project TODOs and Plans</strong></p>
<p>I think this project would be a good playground for:</p>
<ol>
<li>Understanding QR code form inside</li>
<li>Designing and implementing efficient and elegant data structures and algorithms. I have looked at the ZXing codebase, especially encoding. The code is good, but there are still many things ti improve. Furthermore the automated Java to c# converter produced a lot of mess.</li>
<li>Refactoring and rewriting code in a TDD manner &#8211; existing implementation can be used as an excellent refactoring initial point. In some cases I think I would prefer to rewrite and use old classes a reference implementations and run my test again both the old and the new code.</li>
</ol>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gmamaladze.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gmamaladze.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gmamaladze.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gmamaladze.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gmamaladze.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gmamaladze.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gmamaladze.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gmamaladze.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gmamaladze.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gmamaladze.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gmamaladze.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gmamaladze.wordpress.com/152/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gmamaladze.wordpress.com/152/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gmamaladze.wordpress.com/152/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=152&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gmamaladze.wordpress.com/2011/09/22/just-launched-new-open-source-project-qrcode-net-at-httpqrcodenet-codeplex-com/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/1167b1f3432b4c965179742187da54c5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gmamaladze</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Extreme_QR_code_to_Wikipedia_mobile_page.png/141px-Extreme_QR_code_to_Wikipedia_mobile_page.png" medium="image">
			<media:title type="html">Artistic QR code</media:title>
		</media:content>

		<media:content url="http://gmamaladze.files.wordpress.com/2011/09/consoleoutput1.png" medium="image">
			<media:title type="html">ConsoleOutput</media:title>
		</media:content>

		<media:content url="http://gmamaladze.files.wordpress.com/2011/09/usingcontrolscreenshot1.jpg" medium="image">
			<media:title type="html">UsingControlScreenshot</media:title>
		</media:content>
	</item>
		<item>
		<title>Parallel Programing, PLINQ and Globalization</title>
		<link>https://gmamaladze.wordpress.com/2011/08/09/parallel-programing-plinq-and-globalization/</link>
		<comments>https://gmamaladze.wordpress.com/2011/08/09/parallel-programing-plinq-and-globalization/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 18:08:32 +0000</pubDate>
		<dc:creator>George Mamaladze</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[PLINQ]]></category>

		<guid isPermaLink="false">http://gmamaladze.wordpress.com/?p=75</guid>
		<description><![CDATA[I&#8217;m going to start with a simple code snippet which sorts an array of strings using LINQ. The result might look like this: &#8230; or not. It depends on the thread culture the sorting is running in. The string order is culture aware (unlike char order which is culture invariant), so if we switch for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=75&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m going to start with a simple code snippet which sorts an array of strings using LINQ.<br />
<pre class="brush: csharp;">
IEnumerable&lt;string&gt; line = new[] {&quot;Z&quot;,&quot;A&quot;,&quot;Ä&quot;};
var result = line.OrderBy(letter =&gt; letter);
Console.WriteLine(&quot;{0}&quot;, string.Join(&quot; &quot;, result));
</pre> </p>
<p>The result might look like this:<br />
<pre class="brush: plain; light: true;">
A Ä Z
</pre><br />
&#8230; or not. It depends on the thread culture the sorting is running in. The string order is culture aware (unlike char order which is culture invariant), so if we switch for instance on one of the Norwegian cultures by adding this line <code>Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("nn-NO");</code> before calling sort, we will get following output instead:<br />
<pre class="brush: plain; light: true;">
A Z Ä
</pre></p>
<p>As next I extended my code snippet to create 4 arrays and sort each of them parallely.<br />
<pre class="brush: csharp;">
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(&quot;nn-NO&quot;);
Console.WriteLine(&quot;Main thread-{0} \t Culture-'{1}'&quot;, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.CurrentCulture);
Console.WriteLine(new string('-', 80));

List&lt;string[]&gt; list = new List&lt;string[]&gt;();
for (int i = 0; i &lt; 3; i++)
{
    list.Add(new[] { &quot;Ä&quot;, &quot;A&quot;, &quot;Z&quot; });
}

var result =
    list
        .Select(
            line =&gt; line
                .OrderBy(letter =&gt; letter));

Parallel.ForEach(result,
    line =&gt;
        Console.WriteLine(
            &quot;Thread-{0} \t Culture-'{1}' \t {2}&quot;,
            Thread.CurrentThread.ManagedThreadId,
            Thread.CurrentThread.CurrentCulture,
            string.Join(&quot; &quot;, line)));

Console.WriteLine();
Console.WriteLine(&quot;Press any key to quit&quot;);
Console.ReadKey();
</pre></p>
<p>The result looks like this:</p>
<p><pre class="brush: plain; highlight: [4,5]; light: true;">
Main thread-1    Culture-'nn-NO'
------------------------------------------------

Thread-1         Culture-'nn-NO'         A Z Ä
Thread-5         Culture-'de-DE'         A Ä Z
Thread-3         Culture-'de-DE'         A Ä Z
Thread-4         Culture-'de-DE'         A Ä Z

Press any key to quit
</pre> </p>
<p>Line 4 sorting order differs from line 5. The sorting was splited up into 4 threads one main and 3 new threads. </p>
<blockquote><p>All three newly created threads got the default culture of my system &#8211; not the culture of the main thread which was set manually.</p></blockquote>
<p>The culture is a property of the executing thread. When a thread is started, its culture is initially determined by using GetUserDefaultLCID from the Windows API. There is no way that I know manipulate this. See <a href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture(v=VS.100).aspx">CultureInfo.CurrentCulture property at MSDN</a>.</p>
<p>The same result if you use PLINQ syntax:<br />
<pre class="brush: csharp;">
    list
        .AsParallel()
        .Select(
            line =&gt; line
                .OrderBy(letter =&gt; letter))
        .ForAll(
            line =&gt;
                Console.WriteLine(
                    &quot;Thread-{0} \t Culture-'{1}' \t {2}&quot;,
                    Thread.CurrentThread.ManagedThreadId,
                    Thread.CurrentThread.CurrentCulture,
                    string.Join(&quot; &quot;, line)));
</pre></p>
<p>The same query without parallel execution delivers consistent output, all four sequences are sorted in the same order.</p>
<p>The solution is to pass a specific culture aware comparer across into the <code>OrderBy</code> method.<br />
<pre class="brush: csharp;">
var norvegianIgnoreCaseComparer = StringComparer.Create(CultureInfo.GetCultureInfo(&quot;nn-NO&quot;), false); 
list
    .AsParallel()
    .Select(
        line =&gt; line
            .OrderBy(letter =&gt; letter, norvegianIgnoreCaseComparer))
    .ForAll(
        line =&gt;
            Console.WriteLine(
                &quot;Thread-{0} \t Culture-'{1}' \t {2}&quot;,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.CurrentCulture,
                string.Join(&quot; &quot;, line)));
</pre></p>
<p>Well, but what about <code>foreach</code> and <code>LINQ</code> legacy code which can be paralelized with simple replacement of a single line by <code>Parallel.ForEach()</code> or adding <code>AsParallel()</code>. The result might be unpredictable and difficult to figure out. So if I would be the author of .NET or PLINQ I would take over the culture of the main thread into the child threads, thus the data come from the main thread, the split-up takes place implicitly and in most cases results are merged back into the main thread back to be consumed there.</p>
<p>Similar issues might occur in queries using any of culture aware calculations, for instance DateTime formatting and parsing.</p>
<blockquote><p><strong>So if you are targeting systems having different regional settings it is a good idea to pass <code>CultureInfo</code> or Culture specific staff (like comparers) into every PLINQ query and parallel call.</strong></p></blockquote>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gmamaladze.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gmamaladze.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gmamaladze.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gmamaladze.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gmamaladze.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gmamaladze.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gmamaladze.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gmamaladze.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gmamaladze.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gmamaladze.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gmamaladze.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gmamaladze.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gmamaladze.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gmamaladze.wordpress.com/75/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=75&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gmamaladze.wordpress.com/2011/08/09/parallel-programing-plinq-and-globalization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/1167b1f3432b4c965179742187da54c5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gmamaladze</media:title>
		</media:content>
	</item>
		<item>
		<title>Edulinq an excellent LINQ+TDD guide</title>
		<link>https://gmamaladze.wordpress.com/2011/08/09/edulinq-an-excellent-linqtdd-guide/</link>
		<comments>https://gmamaladze.wordpress.com/2011/08/09/edulinq-an-excellent-linqtdd-guide/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 10:00:10 +0000</pubDate>
		<dc:creator>George Mamaladze</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://gmamaladze.wordpress.com/?p=95</guid>
		<description><![CDATA[Recently I stumbled across a question on stackowerflow.com about Edulinq. Its a series of blog posts turned at the end into a free eBook. Downloaded to my eBook reader and had a lot of fun in subway. There where not to much to discover inside of LINQ for me, but it could help a novice [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=95&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently I stumbled across a question on stackowerflow.com about <a href="http://msmvps.com/blogs/jon_skeet/archive/tags/Edulinq/default.aspx" target="_blank">Edulinq</a>. Its a series of blog posts turned at the end into a <a href="http://code.google.com/p/edulinq/downloads/list" target="_blank">free eBook</a>. Downloaded to my eBook reader and had a lot of fun in subway.</p>
<p>There where not to much to discover inside of LINQ for me, but it could help a novice to understand the LINQ &#8220;magic&#8221; and use it efficiently.</p>
<p>Another very important point for me was the test driven approach. You could take this book as a guide for test driven <strong>design</strong> and development.</p>
<p>Reading this book chapter after chapter you will see how TDD helps you to come to a best API decision when working on a library. It demonstrates that on sometimes you should compromise functionality or performance to increase usability and maintain necessary level of protection.</p>
<p>Every chapter follows the same structure contains a lot of test and productive code, builds on top of the previous and makes a basement for the next one &#8211; remembers me the double linked list.</p>
<p>A must to read book for TDD + LINQ fans.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gmamaladze.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gmamaladze.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gmamaladze.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gmamaladze.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gmamaladze.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gmamaladze.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gmamaladze.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gmamaladze.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gmamaladze.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gmamaladze.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gmamaladze.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gmamaladze.wordpress.com/95/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gmamaladze.wordpress.com/95/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gmamaladze.wordpress.com/95/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=95&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gmamaladze.wordpress.com/2011/08/09/edulinq-an-excellent-linqtdd-guide/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/1167b1f3432b4c965179742187da54c5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gmamaladze</media:title>
		</media:content>
	</item>
		<item>
		<title>Why .NET LinkedList does not support Concat and Split operations?</title>
		<link>https://gmamaladze.wordpress.com/2011/08/06/why-net-linkedlist-does-not-support-concat-and-split-operations/</link>
		<comments>https://gmamaladze.wordpress.com/2011/08/06/why-net-linkedlist-does-not-support-concat-and-split-operations/#comments</comments>
		<pubDate>Sat, 06 Aug 2011 10:40:18 +0000</pubDate>
		<dc:creator>George Mamaladze</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Data Structures and Algorithms]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://gmamaladze.wordpress.com/?p=77</guid>
		<description><![CDATA[Download SimpleLinkedList source code Concat O(1) or O(n) ? The .NET LinkedList is a circular doubly linked list, where each node holds a reference to its previous and next nodes. The last node’s next is the head node and the head node’s previous is the last one. Linked lists are attractive because of O(1) insertion [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=77&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a title="Donwload SimpleLinkedList source code" href="http://sites.google.com/site/gmamaladze/SimpleLinkedList_src.zip" target="_blank">Download SimpleLinkedList source code</a></p>
<p><strong>Concat <em>O(1)</em> or<em> O(n)</em> ?</strong><br />
The .NET <code>LinkedList</code> is a circular doubly linked list, where each node holds a reference to its previous and next nodes. The last node’s next is the head node and the head node’s previous is the last one.</p>
<p><a href="http://gmamaladze.files.wordpress.com/2011/08/doubly_linked_list2.png"><img class="aligncenter size-medium wp-image-78" title="Doubly linked list" src="http://gmamaladze.files.wordpress.com/2011/08/doubly_linked_list2.png?w=300&#038;h=62" alt="" width="300" height="62" /></a></p>
<p>Linked lists are attractive because of <em>O(1)</em> insertion and removal operations. Instead of shifting elements in array you just chain nodes in appropriate order and that’s it.</p>
<p>Following this logic concatenation of two lists should be similar <em>O(1)</em> operation. You just bind the end of the first list with the head of the second and let the both ends of the resulting list point to each other.</p>
<p>Nevertheless if you look at .NET <em>LinkedList</em> implementation you will find out that the only way to join two linked lists is to add elements of the second list one by one to the first one. This is <em>O(n)</em> operation.</p>
<p><strong>Implementing Concat</strong><br />
So if you look at the implementation you will find out that the LinkedListNode has one more field except prev and next. This is a reference to the owner list. So with this implementation even if you implement concat in <em>O(1)</em> as described above, you will still need at least reparent all nodes which is again <em>O(n)</em> operation.</p>
<p>Can we avoid referencing list in every node? Yes we can. We can rewrite <code>Previous</code> and <code>Next</code> properties like this.</p>
<p>Before:</p>
<p><pre class="brush: csharp;">
        public LinkedListNode Next
        {
            get
            {
                if ((this.next != null) &amp;&amp; (this.next != this.list.head))
                {
                    return this.next;
                }
                return null;
            }
        }
</pre></p>
<p>After:</p>
<p><pre class="brush: csharp;">
        public SimpleLinkedListNode GetNext(SimpleLinkedList list)
        {
            if ((this.Next != null) &amp;&amp; (this.Next != list.First))
            {
                return this.Next;
            }
            return null;
        }
</pre></p>
<p>After removing parent checking exception handling code from <code>LinkeList</code> implementation you can implement contamination like this:</p>
<p><pre class="brush: csharp;">
        public void Concat(SimpleLinkedList secondList)
        {
            if (secondList.m_Head == null)
            {
                return;
            }

            if (this.m_Head == null)
            {
                this.m_Head = secondList.m_Head;
            }
            else
            {
                var seamLeft = this.Last;
                var seamRight = secondList.m_Head;
                var newEnd = secondList.Last;

                seamLeft.Next = seamRight;
                seamRight.Prev = seamLeft;
                newEnd.Next = this.m_Head;
                this.m_Head.Prev = newEnd;
            }
        }
</pre></p>
<p>You are even able to maintain <code>Count</code> property correctly by adding counts of both lists.</p>
<p><pre class="brush: csharp;">
this.m_Count += secondList.m_Count;
</pre></p>
<p><strong>Drawbacks</strong><br />
The major drawback of this solution is that the second list is will be left in an inconsistent state after this operation. Its last.prev does not point to its head anymore. Another point is that any active operation on one of the lists will modify both, thus they have shared nodes. These side effects violate fundamental principles of OO design. So I can imagine that Microsoft won’t compromise at that point and decided not to implement concatenation.</p>
<p><strong>What about Split?</strong><br />
Implementing Split is very similar, with the difference that you are not able to maintain Count property in O(1) time. You are splitting at certain node without knowing its index inside the list. So If you want to have a Split operation you should compromise Count property.</p>
<p><strong>Concat extension method</strong><br />
There is a Concat extension method on <code>IEnumarable</code> interface. You might think it’s as stupid as Count extension method on <code>IEnumarable</code> and spends <em>O(n)</em> on bringing all together.</p>
<p>In fact it executes in <em>O(1)</em> returning a new enumerator which enumerates first list and jumps to the second when the first list reaches its end.<br />
This might help if you are not going to continue working with concatenation result like with a <code>LinkedList</code>. Another point is that several subsequent concatenation operations cause nested enumerators. So you get a tree of enumerators over enumerators etc.</p>
<p><strong>My implementation</strong><br />
The actual goal of my implementation of double linked list supporting concat and split was to try out and demonstrate test driven refactoring approach.</p>
<p>The first implementation was just derived from common .NET <code>LinkedList</code>.</p>
<p><pre class="brush: csharp;">
    public class SimpleLinkedList : LinkedList
    {

        public SimpleLinkedList()
        {

        }

        public SimpleLinkedList(IEnumerable enumerable)
            : base(enumerable)
        {

        }

        internal SimpleLinkedList Split(LinkedListNode splitNode)
        {
            throw new NotImplementedException();
        }

        public LinkedListNode Find(T search, IEqualityComparer comparer)
        {
            return Find(search);
        }

        public void FindLast(T search, IEqualityComparer comparer)
        {
            return Find(search);
        }
    }
</pre></p>
<p>The second step was creating appropriate test set ensuring common <code>LinkedList</code> behaviour.</p>
<p>Example:</p>
<p><pre class="brush: csharp;">
        [TestCase(new string[] { }, &quot;A&quot;, new[] { &quot;A&quot; })]
        [TestCase(new string[] { }, null, new[] { (string)null })]
        [TestCase(new[] { &quot;A&quot; }, &quot;B&quot;, new[] { &quot;A&quot;, &quot;B&quot; })]
        [TestCase(new[] { &quot;A&quot;, &quot;B&quot;, &quot;C&quot; }, &quot;D&quot;, new[] { &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot; })]
        public void AddLast_one_element_occururs_at_the_end_of_the_list(string[] original, string element, string[] expected )
        {
            var target = new SimpleLinkedList(original);
            target.AddLast(element);
            CollectionAssert.AreEquivalent(expected, target);
        }
</pre></p>
<p>After I had a reasonable set I started implementing functionality successively.<br />
Here is the result &#8211; <code>SimpleLinkedList</code></p>
<p><strong>Advantages:</strong></p>
<ul>
<li>Less memory consumption, thus every node SimpleLinkedListNode has three pointers (prev, next, value) instead of four (prev, next, list, value) unlike original .NET implementation.</li>
<li>Supports Concat and Split operations in O(1)</li>
<li>Supports IEnumarable Reverse() enumerator in O(1) – by the way I do not see any reason why it’s not provided natively on the .NET LinkedList. Appropriate extension method requires O(n).</li>
</ul>
<p><strong>Disadvantages:</strong></p>
<ul>
<li>Does not support Count.</li>
<li>Concat operation leaves second list in an inconsistent state.</li>
<li>Split operation leaves original list in an inconsistent state.</li>
<li>You are able to share nodes between lists.</li>
</ul>
<p><strong>Other:</strong></p>
<ul>
<li>I have chosen an alternative strategy for implementing enumeration and find operations, rather than more verbose and purely readable original implementation. I hope the negative performance impact remains insignificant.</li>
</ul>
<p><em>So be careful using this list and use it only if you are aware of consequences.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gmamaladze.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gmamaladze.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gmamaladze.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gmamaladze.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gmamaladze.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gmamaladze.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gmamaladze.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gmamaladze.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gmamaladze.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gmamaladze.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gmamaladze.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gmamaladze.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gmamaladze.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gmamaladze.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=77&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gmamaladze.wordpress.com/2011/08/06/why-net-linkedlist-does-not-support-concat-and-split-operations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/1167b1f3432b4c965179742187da54c5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gmamaladze</media:title>
		</media:content>

		<media:content url="http://gmamaladze.files.wordpress.com/2011/08/doubly_linked_list2.png?w=300" medium="image">
			<media:title type="html">Doubly linked list</media:title>
		</media:content>
	</item>
		<item>
		<title>&#8220;Cancel me if you can&#8221; or PLINQ cancelability &amp; responsiveness in WinForms</title>
		<link>https://gmamaladze.wordpress.com/2011/07/31/cancel-me-if-you-can-or-plinq-cancelability-responsiveness-in-winforms/</link>
		<comments>https://gmamaladze.wordpress.com/2011/07/31/cancel-me-if-you-can-or-plinq-cancelability-responsiveness-in-winforms/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 17:37:45 +0000</pubDate>
		<dc:creator>George Mamaladze</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Data Structures and Algorithms]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[PLINQ]]></category>

		<guid isPermaLink="false">https://gmamaladze.wordpress.com/?p=46</guid>
		<description><![CDATA[Download Source Code Challenge Just had the first chance to apply PLINQ (Parallel LINQ) to the real task. When I am playing around with some new technology everything works fine, the real understanding comes along with challenges in a real use case. Currently I am working on application which processes large amount of text data [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=46&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong><a title="Download sorce files." href="http://sites.google.com/site/gmamaladze/CountWords.PLinq.zip">Download Source Code</a></strong></p>
<h2>Challenge</h2>
<p>Just had the first chance to apply PLINQ (<a title="Parallel LINQ" href="http://msdn.microsoft.com/en-us/library/dd460688.aspx" target="_blank">Parallel LINQ</a>) to the real task.<br />
When I am playing around with some new technology everything works fine, the real understanding comes along with challenges in a real use case. Currently I am working on application which processes large amount of text data gathering statistics on word occurrences (see: <a href="http://sourcecodecloud.codeplex.com" target="_blank">Source Code Word Cloud</a>).</p>
<p>Here what the simplified core of my code is doing.</p>
<ul>
<li>Enumerate through all files with *.txt extension.</li>
<li>Enumerate through words in each text files.</li>
<li>Group by word and count occurrences.</li>
<li>Sort by occurrences.</li>
<li>Output top 20.</li>
</ul>
<p>Everything worked fine with LINQ. I wrote a prototype console application with a single LINQ query. &#8230; and ta-daa! Just adding one line turned it into PLINQ.</p>
<p><pre class="brush: csharp; highlight: [4];">
public static void Main(string[] args) {
    var result = Directory
        .EnumerateFiles(@&quot;c:\temp&quot;, &quot;*.txt&quot;, SearchOption.AllDirectories)
        .AsParallel()
        //.WithDegreeOfParallelism(1..63)
        .SelectMany(File.ReadLines)
        .SelectMany(ReadWords)
        .GroupBy(word =&gt;; word, (word, words) =&gt;; new Tuple&lt;int, string&gt;(words.Count(), word))
        .OrderByDescending(occurrencesWordPair =&gt;; occurrencesWordPair.Item1)
        .Take(20);

    foreach (Tuple&lt;int, string&gt; tuple in result) {
        Console.WriteLine(tuple);
    }

    Console.Write(&quot;Press any key to quit.&quot;); Console.ReadKey();
}

private static IEnumerable&lt;string&gt; ReadWords(string line) {
    StringBuilder word = new StringBuilder();
    foreach (char ch in line) {
        if (char.IsLetter(ch)) { word.Append(ch); }
        else {
            if (word.Length == 0) continue;
            yield return word.ToString();
            word.Clear();
        }
    }
}
</pre></p>
<p>Finally all four cores of my PC and the fan where busy processing dozens of megabytes of free eBooks in my temp folder I have prepared for testing. Moving to PLINQ brought me significant performance boost. But adopting this one line into the WinForms application was a different challenge.</p>
<h2>Frustration</h2>
<p>&#8230; cancelability and responsiveness during long running queries were lost.</p>
<p>It seems that the OrderBy query was synchronizing data back into main thread and windows messages were not processed. In the examle below I am demonstrating my implementation of cancelation according to MSDN How to: <a href="http://msdn.microsoft.com/en-us/library/dd460707.aspx" target="_blank">Cancel a PLINQ Query</a> which does not worked <img src='https://s-ssl.wordpress.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p><pre class="brush: csharp; highlight: [14,33];">
public Form1()
{
    InitializeComponent();
    m_CancellationTokenSource = new CancellationTokenSource();
}

private readonly CancellationTokenSource m_CancellationTokenSource;

private void buttonStart_Click(object sender, EventArgs e)
{
    var result = Directory
        .EnumerateFiles(@&quot;c:\temp&quot;, &quot;*.txt&quot;, SearchOption.AllDirectories)
        .AsParallel()
        .WithCancellation(m_CancellationTokenSource.Token)
        .SelectMany(File.ReadLines)
        .SelectMany(ReadWords)
        .GroupBy(word =&gt; word, (word, words) =&gt; new Tuple&lt;int, string&gt;(words.Count(), word))
        .OrderByDescending(occurrencesWordPair =&gt; occurrencesWordPair.Item1)
        .Take(20);

    try {
       foreach (Tuple&lt;int, string&gt; tuple in result) {
            Console.WriteLine(tuple);
        }
    }
    catch (OperationCanceledException ex) {
        Console.WriteLine(ex.Message);
    }
}

private void buttonCancel_Click(object sender, EventArgs e)
{
   m_CancellationTokenSource.Cancel();
}

private static IEnumerable&lt;string&gt; ReadWords(string line) { ... }
</pre></p>
<p>I was not able to click Cancel button, move the form around, do anything at all until the whole query where finished. That&#8217;s was not the perfect cancelation behavior &#8211; &#8220;Yes you can cancel it but you can not click button which does that&#8221;. I have asked the question colleagues and posted at stackowerflow. Everyone gave me the same answer &#8211; call the query in another thread.<br />
That was not an option form me, if I wanted to c<strong>lutter my code with threading staff</strong> I would do it without PLINQ. PLINQ allows you to keep your logic free from parallelism / synchronization overhead keeping your code readable and closer to business not to techniques. (see proposed solutions at <a href="http://stackoverflow.com/questions/6916024/how-to-cancel-a-plinq-query-in-a-winforms-application" target="_blank">stackowerflow</a>)</p>
<h2>The Ahaa Moment</h2>
<p>While waiting for THE expert&#8217;s opinion from somewhere in cyberspace I came up with my own which I like pretty much. I wrote these two extension methods:</p>
<p><pre class="brush: csharp; highlight: [9,21];">
public static class CallbackExtensions
{
    public static ParallelQuery&lt;TSource&gt; ProcessWindowsMessages&lt;TSource&gt;(this ParallelQuery&lt;TSource&gt; source)
    {
        return source.Select(
            item =&gt;
                {
                    Application.DoEvents();
                    Thread.Yield();
                    return item;
                });
    }

    public static ParallelQuery&lt;TSource&gt; WithCallback&lt;TSource&gt;(this ParallelQuery&lt;TSource&gt; source, ISynchronizeInvoke target, Action&lt;TSource&gt; callback)
    {
        return source.Select(
            item =&gt;
                {
                    Application.DoEvents();
                    Thread.Yield();
                    target.Invoke(callback, new object[] {item});
                    return item;
                });
    }
}
</pre></p>
<p>The first one just passes control to the main theread allowing standard COM and SendMessage pumping. The second one allows to invoke any action <strong>into the main therad</strong> with item argument which is currently processed. You can put them anywhere in your query depending how responsive your query should be. The example below passes control back to main after processing each file.</p>
<p><pre class="brush: csharp; highlight: [4];">
var result = Directory
    .EnumerateFiles(@&quot;c:\temp&quot;, &quot;*.txt&quot;, SearchOption.AllDirectories)
    .AsParallel()
    .ProcessWindowsMessages()
    .WithCancellation(m_CancellationTokenSource.Token)
    .SelectMany(File.ReadLines)
    .SelectMany(ReadWords)
    .GroupBy(word =&gt; word, (word, words) =&gt; new Tuple&lt;int, string&gt;(words.Count(), word))
    .OrderByDescending(occurrencesWordPair =&gt; occurrencesWordPair.Item1)
    .Take(20);
</pre></p>
<p>You can even use the second extension method to perform progress indication and staff like that. In my example I am showing every word processed in caption. Yes I know &#8211; this is highly inefficient but for demo purposes is ok. You can download my solution and play with position of the line. For instance putting it beside file query will show files in caption and will have moderate responsiveness.</p>
<p><pre class="brush: csharp; highlight: [7];">
var result = Directory
    .EnumerateFiles(@&quot;c:\temp&quot;, &quot;*.txt&quot;, SearchOption.AllDirectories)
    .AsParallel()
    .WithCancellation(m_CancellationTokenSource.Token)
    .SelectMany(File.ReadLines)
    .SelectMany(ReadWords)
    .WithCallback(this, word =&gt; { this.Text = word; })
    .GroupBy(word =&gt; word, (word, words) =&gt; new Tuple&lt;int, string&gt;(words.Count(), word))
    .OrderByDescending(occurrencesWordPair =&gt; occurrencesWordPair.Item1)
    .Take(20);
</pre></p>
<h2>Negative effects</h2>
<p>Using one of my extension methods you are creating a bottleneck bringing all of your parallel treads back into the main just to paint one word into form&#8217;s title bar. So the best solution would be to <strong>slowdown</strong> callbacks invoking into the main thread as much as possible. Let&#8217;s say you need to update a progress bar. It would be enough to do it 10 times in a second so put the timer and do not invoke again until appropriate time is elapsed after the last invoke. All other calls will just trivially return. Or you may decide to pass only every 1000-Th word to display on the screen.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gmamaladze.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gmamaladze.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gmamaladze.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gmamaladze.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gmamaladze.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gmamaladze.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gmamaladze.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gmamaladze.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gmamaladze.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gmamaladze.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gmamaladze.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gmamaladze.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gmamaladze.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gmamaladze.wordpress.com/46/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=46&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gmamaladze.wordpress.com/2011/07/31/cancel-me-if-you-can-or-plinq-cancelability-responsiveness-in-winforms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/1167b1f3432b4c965179742187da54c5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gmamaladze</media:title>
		</media:content>
	</item>
		<item>
		<title>Back to the roots: .NET binary search and the meaning of the negative number of the Array.BinarySearch() return value</title>
		<link>https://gmamaladze.wordpress.com/2011/07/22/back-to-the-roots-net-binary-search-and-the-meaning-of-the-negative-number-of-the-array-binarysearch-return-value/</link>
		<comments>https://gmamaladze.wordpress.com/2011/07/22/back-to-the-roots-net-binary-search-and-the-meaning-of-the-negative-number-of-the-array-binarysearch-return-value/#comments</comments>
		<pubDate>Fri, 22 Jul 2011 10:02:21 +0000</pubDate>
		<dc:creator>George Mamaladze</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Data Structures and Algorithms]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://gmamaladze.wordpress.com/?p=39</guid>
		<description><![CDATA[Recently I gave a group of developers a task witch can be simplified to following simple problem: you have a sorted array of elements; find the index of a given element in this array. They came up with following solution: Of course it works fine but didn&#8217;t we do too much work? Can we probably [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=39&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently I gave a group of developers a task witch can be simplified to following simple problem: you have a sorted array of elements; find the index of a given element in this array. They came up with following solution:</p>
<p><pre class="brush: csharp;">
//given array
int[] sortedArray = new[] { 1, 5, 8, 12, 18, 20 };
//Create a list from the array
List&lt;int&gt; list = new List&lt;int&gt;(sortedArray);
//use IndexOf method to find the element
int result = list.IndexOf(8);
</pre></p>
<p>Of course it works fine but didn&#8217;t we do too much work? Can we probably use the fact that the given array is sorted? Do we need an additional data structure List?</p>
<p>If we read the Performance Considerations section at MSDN class documentation we see that to perform <code>IndexOf()</code> operation the list first sorts the content and then performs the binary search on it. See: <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx">List&lt;&gt; at MSDN</a></p>
<p>So we can simply use the <code>BinarySearch()</code> method of the Array static class.</p>
<p><pre class="brush: csharp;">
//perform binary search
int result = Array.BinarySearch(sortedArray, 8);
</pre></p>
<p>So the <code>BinarySearch()</code> does basically the same as the <code>IndexOf()</code> does, but quicker, sometimes it’s better to remember basic algorithms instead of using complex data structures to accomplish the very narrow task efficiently.</p>
<p>For more information on binary search algorithm see: <a title="Binary Search (Wikipedia)" href="http://en.wikipedia.org/wiki/Binary_search_algorithm" target="_blank">Binary Search (Wikipedia)</a></p>
<h2>Why does the <code>BinarySeacrh()</code> do more then <code>IndexOf()</code> does?</h2>
<p>Let’s search a non existing element using both methods and compare results.</p>
<p><pre class="brush: csharp;">
//given array
int[] sortedArray = new[] { 1, 5, 8, 12, 18, 20 };
//Create a list from the array
List&lt;int&gt; list = new List&lt;int&gt;(sortedArray);
//use IndexOf to find element
int result1 = list.IndexOf(17);
//Use Array.BinarySearch
int result2 = Array.BinarySearch(sortedArray, 17);
</pre></p>
<p>The result looks strange:</p>
<p><pre class="brush: csharp;">
IndexOf(17)==-1
BinarySearch(17)==-5
</pre></p>
<p>Both of them deliver a negative value which should be interpreted as element not found. However in opposite to <code>List.IndexOf()</code> which always delivers <strong><em>-1</em></strong> the <code>Array.BinarySearch()</code> returns some “magic” negative value. Following explanation can be found in class documentation:</p>
<blockquote><p>Return Value : The index of the specified value in the specified array, if value is found. If value is not found and value is less than one or more elements in array, a negative number which is the <strong>bitwise complement</strong> of the index of the first element that is larger than value. If value is not found and value is greater than any of the elements in array, a negative number which is the bitwise complement of (the index of the last element plus 1).</p></blockquote>
<p>For more information see: <a title="Array.BinarySearch Method (MSDDN)" href="http://msdn.microsoft.com/en-us/library/y15ef976.aspx" target="_blank">Array.BinarySearch Method (MSDDN)</a></p>
<p>Sounds complicated but means following: the binary search travels the binary tree, at some point it realizes that element can not be found and stops on a certain node. If you negate the result of the binary search and subtract 1 you will get the index of this element.</p>
<table>
<tbody>
<tr>
<td>Index</td>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>Element</td>
<td>1</td>
<td>5</td>
<td>8</td>
<td>12</td>
<td>18</td>
<td>20</td>
</tr>
</tbody>
</table>
<p>So if you search for 7 the result will be the negated index of element 8 minus 1, equals 2.</p>
<p>So if you search for 17 the result will be the negated index of element 18 minus 1, equals 4.</p>
<p>The formula is:<br />
<pre class="brush: csharp;">
 - Array.BinarySearch(sortedArray, 22) - 1
</pre><br />
<strong>Important:</strong> if you are searching for a value which is greater then the last element this formula gives you array length, which is a non existing index. So you should not use the result of this calculation to access an element of the array without checking if it’s less then length.</p>
<p>So if you search for 22 the result will be -7. -(-7) -1 = 6 = array length.</p>
<p>The return value of <code>BinarySearch()</code> can be used in wide range of algorithms. For instance when solving the problem of <strong>vertex collision detection</strong>. It might be useful also when working with text segments.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gmamaladze.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gmamaladze.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gmamaladze.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gmamaladze.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gmamaladze.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gmamaladze.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gmamaladze.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gmamaladze.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gmamaladze.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gmamaladze.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gmamaladze.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gmamaladze.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gmamaladze.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gmamaladze.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=39&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gmamaladze.wordpress.com/2011/07/22/back-to-the-roots-net-binary-search-and-the-meaning-of-the-negative-number-of-the-array-binarysearch-return-value/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/1167b1f3432b4c965179742187da54c5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gmamaladze</media:title>
		</media:content>
	</item>
		<item>
		<title>C# Tweaks &#8211; Why to use the sealed keyword on classes?</title>
		<link>https://gmamaladze.wordpress.com/2011/07/22/c-tweaks-why-to-use-the-sealed-keyword-on-classes-2/</link>
		<comments>https://gmamaladze.wordpress.com/2011/07/22/c-tweaks-why-to-use-the-sealed-keyword-on-classes-2/#comments</comments>
		<pubDate>Fri, 22 Jul 2011 08:36:27 +0000</pubDate>
		<dc:creator>George Mamaladze</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Clean Code]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Data Structures and Algorithms]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Testability]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://gmamaladze.wordpress.com/?p=31</guid>
		<description><![CDATA[The sealed keyword is one of the very seldom used modifiers in C#. Probably most of you know what it is for, but many developers have not ever used it. See C# Programmers Guide if you are not sure you remember what the keyword is good for: sealed keyword (MSDN) Why shall I use it? [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=31&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The sealed keyword is one of the very seldom used modifiers in C#. Probably most of you know what it is for, but many developers have not ever used it.</p>
<p>See C# Programmers Guide if you are not sure you remember what the keyword is good for: <a title="sealed keyword (MSDN)" href="http://msdn.microsoft.com/en-us/library/88c54tsw(VS.71).aspx" target="_blank">sealed keyword (MSDN)</a></p>
<h2>Why shall I use it?</h2>
<p>Most popular, but not really most important motivation is the performance &#8211; JIT compiler can produce more efficient code by calling the method non-virtually. I remember someone even made performance measurements, but I think that the real performance gain highly depends on algorithms in a specific use case.</p>
<p>The vast majority of .NET programmers let their classes “unsealed” without even considering making them sealed. If a class was not designedly made inheritable it is very probably even impossible to inherit from it and override members reasonably. On the other hand overriding members of the class which was not designed to be overridden might cause unpredictable results.</p>
<p>When a class is originally sealed, it can change to “unsealed” in the future without breaking compatibility.</p>
<h2>Something new I’ve discovered recently</h2>
<p>Recently I was refactoring some component with multiple classes making intensive use of inheritance. During cleanup I changed all leaf classes in inheritance tree, the classes which can not be inherited anymore, to be sealed. I was sure it will not break compatibility, but the next compile failed.</p>
<p><strong>The reason was a bug, which became visible only after I made some class sealed</strong> to compile time. Not being sealed it would throw an exception during execution. This sample demonstrates the simplified version of this situation:</p>
<p><pre class="brush: csharp; highlight: [3,13];">
interface IInterface1 {}

class Class1 {}

class Program
{
   static void Main(string[] args)
   {
     //Class1 does not implement IInterface1
     Class1 instanceOfClass1 = new Class1();

     //However this cast does not leads to compilation error
     IInterface1 someImplementer = (IInterface1)instanceOfClass1;
   }
}
</pre></p>
<p><code>Class1</code> does not implement <code>IInterface1</code>, however the cast of an instance of the <code>Class1</code> to <code>IInterface1</code> does not lead to compilation error. The reason is that theoretically some inherited class of the <code>Class1</code> might implement this interface.</p>
<p>Now let’s make <code>Class1</code> sealed. Now the compiler will see that <code>Class1</code> can be only <code>Class1</code> “itself” (and its base classes if applicable) and it does not implement interface <code>IInterface1</code>.</p>
<p><pre class="brush: csharp; highlight: [3,13];">
internal interface IInterface1 {}

sealed class Class1 {}

class Program
{
    static void Main(string[] args)
    {
        //Class1 does not implement IInterface1
        Class1 instanceOfClass1 = new Class1();

        //However this cast does not leads to compilation error
        IInterface1 someImplementer = (IInterface1)instanceOfClass1;
    }
}
</pre></p>
<p>Following compilation error will occur:</p>
<p><pre class="brush: plain;">Cannot convert type 'Class1' to 'IInterface1'</pre></p>
<blockquote><p>So using sealed keyword brings not only performance win and additional code access security but also helps to write bug free code, making better use of the .NET type safety.</p></blockquote>
<p>My recommendation: Always declare a new class as sealed until you are writing an abstract class or a class which must be inherited per design. Most classes in a real application (except you are writing a widely used library) can be made sealed.</p>
<p>P.S. You can apply the sealed keyword not only to classes but also to some members. I am going to post about that as well.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gmamaladze.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gmamaladze.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gmamaladze.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gmamaladze.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gmamaladze.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gmamaladze.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gmamaladze.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gmamaladze.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gmamaladze.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gmamaladze.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gmamaladze.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gmamaladze.wordpress.com/31/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gmamaladze.wordpress.com/31/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gmamaladze.wordpress.com/31/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gmamaladze.wordpress.com&amp;blog=25359189&amp;post=31&amp;subd=gmamaladze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>https://gmamaladze.wordpress.com/2011/07/22/c-tweaks-why-to-use-the-sealed-keyword-on-classes-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="https://secure.gravatar.com/avatar/1167b1f3432b4c965179742187da54c5?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gmamaladze</media:title>
		</media:content>
	</item>
	</channel>
</rss>
