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

<channel>
	<title>Cheraq.com</title>
	<atom:link href="http://cheraq.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://cheraq.com</link>
	<description>I innovate, then I am!</description>
	<lastBuildDate>Wed, 11 Jan 2012 02:03:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Yet Another JSON Parser for DotNet</title>
		<link>http://cheraq.com/902/yet-another-json-parser-for-dotnet/</link>
		<comments>http://cheraq.com/902/yet-another-json-parser-for-dotnet/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 08:52:32 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[ASP.NET Tips]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://cheraq.com/?p=902</guid>
		<description><![CDATA[JavaScript is everywhere. So why not using it on server side? Why not including it in our C# codes? Of course .Net cannot understand it, but using some tricks, we can make it understandable. This can save your day by removing all those codes that work as translator to make conversation between JS and .Net possible.  <a href="http://cheraq.com/902/yet-another-json-parser-for-dotnet/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Believe it or not, JavaScript is everywhere. All new websites are using it. And since people can see it everywhere, all customers are asking for it as well. JavaScript got a very nice data structure for passing data back and forth by using JSON (JavaScript Object Notation). Generating JSON objects in .Net is just so easy, either you can use built-in JavaScriptSerializer or if you are using Web Service, just enable the ScriptServices and your objects will be converted to JSON automatically (based on Context). But parsing JSON on server side could be tricky.</p>
<p>Since I needed this JSON Parser badly in my project, I started to searched and found a very clean solution for it (thanks to <a href="http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx">Shawn Weisfeld</a> for sharing it). The idea is, we can use Dynamic data type in order to deal with JSON strings, so you can use almost the same code that you have used in your JavaScript source, on the server side. The drawback is, you will lose intelliSense, and of course you have to use .Net 4.0. So if you are planing to use it in older versions, then you came to the wrong place.</p>
<h2>Using JSON Parser</h2>
<p>You can simply view the source code on <a href="https://github.com/mjfathinia/DotNetJSONParser">github</a> or <a href="https://github.com/mjfathinia/DotNetJSONParser/zipball/master">download</a> it.</p>
<p>Using it is so simple. I have added an <a href="https://github.com/mjfathinia/DotNetJSONParser/blob/master/StringExtensions.cs">extension</a> to string class that will do the trick. If you are not familiar with Extension Methods, I have <a title="Extension Methods in .NET" href="http://cheraq.com/5/extension-methods-in-net/">an article</a> for you.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> jsonStr<span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// it can be like { a:{b:1}, c:[] }</span>
dynamic parsedStr <span style="color: #008000;">=</span> jsonStr<span style="color: #008000;">.</span><span style="color: #0000FF;">ParseJSON</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// you need to add &quot;Using Cheraq.Extensions;&quot;</span>
<span style="color: #008080; font-style: italic;">// to access b, you can use</span>
<span style="color: #6666cc; font-weight: bold;">int</span> b <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>parsedStr<span style="color: #008000;">.</span><span style="color: #0000FF;">a</span><span style="color: #008000;">.</span><span style="color: #0000FF;">b</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// this can lead to error if a is null</span>
<span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">?</span> safeB <span style="color: #008000;">=</span> parsedStr<span style="color: #008000;">.</span><span style="color: #0000FF;">a</span> <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">?</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">?</span><span style="color: #008000;">&#41;</span>parsedStr<span style="color: #008000;">.</span><span style="color: #0000FF;">a</span><span style="color: #008000;">.</span><span style="color: #0000FF;">b</span> <span style="color: #008000;">:</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">?</span><span style="color: #008000;">&#41;</span><span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span></pre></div></div>

<p>Hope you will find it useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/902/yet-another-json-parser-for-dotnet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Common Javascript mistakes: Variable Scope</title>
		<link>http://cheraq.com/876/common-javascript-mistakes-variable-scope/</link>
		<comments>http://cheraq.com/876/common-javascript-mistakes-variable-scope/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 01:51:32 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[function closure]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[variable scope]]></category>

		<guid isPermaLink="false">http://cheraq.com/?p=876</guid>
		<description><![CDATA[If you are a person that JavaScript(JS) is not your first programming language, and you have a background in C, C++, Java, C#, Python or other well structured programming languages, then you might caught off-guard with some JS concepts. We usually don't like to start learning something from zero, so we usually try to guess how things work based on what we already learned in other programming languages. But some concepts in JS are totally different from other languages, and the one that recently I faced is: Variable Scope. <a href="http://cheraq.com/876/common-javascript-mistakes-variable-scope/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you are a person that JavaScript(JS) is not your first programming language, and you have a background in C, C++, Java, C#, Python or other well structured programming languages, then you might caught off-guard with some JS concepts. We usually don&#8217;t like to start learning something from zero, so we usually try to guess how things work based on what we already learned in other programming languages. But some concepts in JS are totally different from other languages, and the one that recently I faced is: Variable Scope.</p>
<h2>What is the Variable Scope in Javascript?</h2>
<p>Well, it might look strange, but it seems everything in Javascript has some sort of relationship with functions. The scope of Variables in Javascript is the <strong>function</strong> that the variable has been defined in it. If it is not inside any function, then it is <strong>global</strong>. Also functions have same scope as variables.</p>
<p>For a long time, I was <strong>assuming </strong> that the variable scope is somehow same as C++ or C# (on code block level which will be indicated by curly braces ({}) or based on indentation in Python), and this is because I didn&#8217;t spend enough time to check the basic concepts (it is really boring to read those lengthy books/documents) and it seems I am not alone and lots of web developers are on the same page.</p>
<h2>A Common Example: Infamous JavaScript Loop Variable</h2>
<p>This is very common case and there are plenty of discussions and solutions for this problem. Let&#8217;s say you have a look that generates some links and keep adding them to the document, and the functionality of the link is somehow dependent to the order link being added.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> addLinks <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> link<span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span><span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        link <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        link.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Link &quot;</span> <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>
        link.<span style="color: #660066;">onclick</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        document.<span style="color: #660066;">body</span>.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>link<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
addLinks<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you <a title="Result of sample code in JSFiddle" href="http://jsfiddle.net/mjfathinia/f789K/embedded/result/">run above code</a> you will see 5 links, but if you click on any of them, it will alert 5 rather than the proper index. The reason is, sine the anonymous function for onclick didn&#8217;t run yet, it will keep a reference to the variable <em>i</em>, that it&#8217;s value is 5 after the loop. For better understanding, you can simply move the &#8220;var <em>i&#8221;</em> to the first line of the function as below:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> addLinks <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">,</span> link<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span><span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        link <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        link.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Link &quot;</span> <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>
        link.<span style="color: #660066;">onclick</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        document.<span style="color: #660066;">body</span>.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>link<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
addLinks<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now you can see why the final result is always 5. There are different ways to solve this, one way is to make a new scope inside the loop, so rather than reference to the <em>i</em>, its value will be used. Below you can find the updated code.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> addLinks <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">,</span> link<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span><span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        link <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        link.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Link &quot;</span> <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>
        link.<span style="color: #660066;">onclick</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>linkIndex<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>linkIndex<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        document.<span style="color: #660066;">body</span>.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>link<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
addLinks<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here what we&#8217;ve done is, we defined new anonymous function which returns our on click handler, but notice we have called this anonymous function. Since during the loop, the function has been called, the value of the loop variable will be stored rather than its reference. This method called <strong>Function Closure</strong>. If you are using JS frameworks, such, as jQuery, then you might saw this before (on creating new plug-in).</p>
<p>Using closure is fine, but you have to consider efficiency as well and at least for this sample code, it is over kill. Another way to deal with this issue is using DOM to store the value for us. So we can update the above code to something like below:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> linkHandler<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>thisgetAttribute<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;data-i&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> addLinks <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">,</span> link<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&lt;</span><span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        link <span style="color: #339933;">=</span> document.<span style="color: #660066;">createElement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        link.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Link &quot;</span> <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>
        link.<span style="color: #660066;">setAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;data-i&quot;</span> <span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        link.<span style="color: #660066;">onclick</span> <span style="color: #339933;">=</span> linkHandler<span style="color: #339933;">;</span>
        document.<span style="color: #660066;">body</span>.<span style="color: #660066;">appendChild</span><span style="color: #009900;">&#40;</span>link<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
addLinks<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here we are simply storing the value in DOM object, and on the handler we will just use that value. This is easier and also debugging it is easier because you can see the value on the generated item as well.</p>
<p>This is what I&#8217;ve faced so many times from the time I have started using JS, but recently I dig into it. Hope you will find it useful as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/876/common-javascript-mistakes-variable-scope/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Code Jam: 2011 Euro Python</title>
		<link>http://cheraq.com/853/gcj-2011-euro-python/</link>
		<comments>http://cheraq.com/853/gcj-2011-euro-python/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 15:04:47 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[Problem Solving]]></category>
		<category><![CDATA[2011EuroPython]]></category>
		<category><![CDATA[Google Code Jam]]></category>

		<guid isPermaLink="false">http://cheraq.com/?p=853</guid>
		<description><![CDATA[In this Problem Solving session, we will have a look at Google Code Jam - Euro Python 2011 contest. Contest consists of four questions which are from easy to medium difficulty and contestants had more than 3 hours to solve the problems which is more than enough. Lets start solving problems rather than talking. <a href="http://cheraq.com/853/gcj-2011-euro-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In this Problem Solving session, we will have a look at <a title="Visit Contest Dashboard on Google Code Jam Website" href="http://code.google.com/codejam/contest/dashboard?c=1277486" target="_blank">Google Code Jam &#8211; Euro Python 2011</a> contest. Contest consists of four questions which are from easy to medium difficulty and contestants had more than 3 hours to solve the problems which is more than enough. Lets start solving problems rather than talking.</p>
<h2>Problem A: Centauri Prime</h2>
<p>This problem has 7 points for small data set and 8 points for large data set, which can result to 15 points total into your account <img src='http://cheraq.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Well the points shows that it is an easy problem. You can read the original problem statement <a title="Problem A" href="http://code.google.com/codejam/contest/dashboard?c=1277486" target="_blank">here</a>, But here we are going to keep it as simple as possible. Below you can find the problem in brief.</p>
<p>You are going to receive a list which contains name of kingdoms in a planet. For each kingdom name, you have to check it as per below conditions to find out the ruler of that kingdom:</p>
<ul>
<li>If the name ends with letter &#8220;y&#8221;, then nobody rules that kingdom.</li>
<li>If the name ends with any of following letters (&#8220;a&#8221;,&#8221;e&#8221;,&#8221;i&#8221;,&#8221;o&#8221;,&#8221;u&#8221;), then kingdom is ruled by a queen.</li>
<li>In any other cases, kingdom is rules by a king.</li>
</ul>
<p>I think the answer is also written in problem statement and you should just implement it. So what you are going to do? For small data set, nothing, but for large data set, you need to read the constraints properly. Then problem statement for large data set says each kingdom name can be at most 100 characters long, which means it can be an string with length &#8220;1&#8243;. This is important because the problem statement says the name of the kingdom starts with <strong>a capital letter</strong>, so you need to consider if the kingdom name is just one character, then you need to change the case to lowercase. Below you can find the code to return the ruler.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> findRuler<span style="color: black;">&#40;</span>country<span style="color: black;">&#41;</span>:
    lastChar = country.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span>-<span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> lastChar == <span style="color: #483d8b;">'y'</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">'nobody'</span>
    <span style="color: #ff7700;font-weight:bold;">elif</span> lastChar <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #483d8b;">'aieou'</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">'a queen'</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">'a king'</span></pre></div></div>

<p><a title="Problem A's solution" href="https://github.com/mjfathinia/GoogleCJ/blob/master/2011EuroPython/a.py" target="_blank">Here</a> you can find the complete code and sample input and output files could be found <a href="https://github.com/mjfathinia/GoogleCJ/tree/master/2011EuroPython" target="_blank">here</a> on GitHub.</p>
<h2>Problem B: Music Collection</h2>
<p>This is an interesting problem with 20 points (8 for small data set, and 12 for large data set). <a title="Problem B" href="http://code.google.com/codejam/contest/dashboard?c=1277486#s=p1" target="_blank">Here</a> you can read the original problem statement, but if you don&#8217;t want to spend time to read the whole story, here you can find the problem in brief.</p>
<p>Lets say you have lots of music files and they got different names (no duplicates). Your music player has a search option which is case insensitive and given any keyword, if the search result contains only one music, it will play it. Your job is, for each entry in the music list, try to find shortest keyword which returns only that item.</p>
<p>The key to solve this problem is, using some sort of indexing table. What we are going to do is, if there are only one item in the list, we will return empty string (this is an edge case, but we have to consider it). If there are more than one item, for each item first we will extract all the substrings (except empty string, can you guess why?). So if the input string is &#8220;abc&#8221;, we have to generate {&#8220;a&#8221;, &#8220;ab&#8221;, &#8220;abc&#8221;, &#8220;b&#8221;, &#8220;bc&#8221;, &#8220;c&#8221;}. We also need an empty hash table (dictionary). For each substring, we will check the hash table, if we don&#8217;t have this item in the hash table, then we will add this item as key and we will use the music name index as value (For music 1, we will add substring &#8220;ab&#8221; as {&#8220;ab&#8221;-&gt;1}). But if the substring already exists in the hash table, means this substring can return more than one music entry (we don&#8217;t need to know how many it will return), so we simply turn the value for that substring in the hash table to some value (like for substring &#8220;ab&#8221;, we will change the value to {&#8220;ab&#8221; -&gt; &#8220;1000&#8243;}). Below code snippet will do this.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">subsets = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> n <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>noEntries<span style="color: black;">&#41;</span>:
    entry = inputFile.<span style="color: #dc143c;">readline</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">strip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">upper</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    entryLength = <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>entry<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> startIndex <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>entryLength<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">for</span> subLength <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>entryLength-startIndex<span style="color: black;">&#41;</span>:
            subString = entry<span style="color: black;">&#91;</span>startIndex:startIndex+subLength+<span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>
            <span style="color: #ff7700;font-weight:bold;">if</span> subString <span style="color: #ff7700;font-weight:bold;">in</span> subsets:
                <span style="color: #ff7700;font-weight:bold;">if</span> subsets<span style="color: black;">&#91;</span>subString<span style="color: black;">&#93;</span> <span style="color: #66cc66;">!</span>= n:
                    subsets<span style="color: black;">&#91;</span>subString<span style="color: black;">&#93;</span> = <span style="color: #ff4500;">1000</span>
            <span style="color: #ff7700;font-weight:bold;">else</span>:
                subsets<span style="color: black;">&#91;</span>subString<span style="color: black;">&#93;</span> = n</pre></div></div>

<p>Once we prepared the subsets hash table, then we can simple select items that their value is less than 1000 (as per the limit definition, we will not have more than 100 entries, so 1000 is a safe value. You could also change it to any negative value, it doesn&#8217;t matter). Since the question is to find shortest string, then for each entry, we need to prepare list of strings which will uniquely identify them, and then sort them as per the problem statement.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">result = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> s <span style="color: #ff7700;font-weight:bold;">in</span> subsets:
    entryIndex = subsets<span style="color: black;">&#91;</span>s<span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> entryIndex <span style="color: #66cc66;">&amp;</span>lt<span style="color: #66cc66;">;</span> <span style="color: #ff4500;">1000</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> entryIndex <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #ff7700;font-weight:bold;">in</span> result:
            result<span style="color: black;">&#91;</span>entryIndex<span style="color: black;">&#93;</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        result<span style="color: black;">&#91;</span>entryIndex<span style="color: black;">&#93;</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span>s<span style="color: black;">&#41;</span></pre></div></div>

<p>Now that we have the result set, we can simply generate result. If you noticed, when we were indexing items (first step) we turned all of them to upper case, the reason is, as per problem statement, the upper case items should appear before lower case items, so we simply can ignore the lower case items. So what we need to do is, simply sort the items first based on the length, and then alphabetically. below code will do this and generates result.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>noEntries<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">if</span> i <span style="color: #ff7700;font-weight:bold;">in</span> result:
        vals = result<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span>
        vals = <span style="color: #008000;">sorted</span><span style="color: black;">&#40;</span>vals,key=<span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x: <span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>,x<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        outputFile.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&quot;%s&quot;<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>vals<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        outputFile.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">':(<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: black;">&#41;</span></pre></div></div>

<p><a title="Problem B's Solution" href="https://github.com/mjfathinia/GoogleCJ/blob/master/2011EuroPython/b.py" target="_blank">Here</a> you can find the complete code and sample input and output files could be found <a href="https://github.com/mjfathinia/GoogleCJ/tree/master/2011EuroPython" target="_blank">here</a> on GitHub.</p>
<h2>Problem C: Irregular Expression</h2>
<p>This is one of those magic games that usually you will see in Google Code Jam contests. This problem has 25 points (10 for small data set, 15 for large data set) and you can find the complete problem statement <a title="Problem C" href="http://code.google.com/codejam/contest/dashboard?c=1277486#s=p2" target="_blank">here</a>. The problem is about 2011 World Witch and Warlock tournament. If we ignore the story line, then problem in brief is as following: You will get a string from input, if you could find below pattern in it, then you will say this string contains some SPELL (be careful, the spell might turn you into frog!). The pattern is as below:</p>
<ul>
<li>A sentence which consists of 3 words</li>
<li>Each word consists of one or more syllables</li>
<li>Each syllable consists of any number of letters, including <strong>exactly</strong> one vowel (&#8216;a&#8217;, &#8216;e&#8217;, &#8216;i&#8217;, &#8216;o&#8217;, &#8216;u&#8217;)</li>
<li>First and third words are <strong>same</strong> and consists of <strong>exactly two syllables</strong></li>
<li>The string might start and end with gibberish characters and also there is no space to separate words</li>
</ul>
<p>Well, what do you think? If you are thinking about regular expressions, then it is better to look at the problem form different point of view. This is an irregular expression problem, so you cannot use regular expression (the name is somehow magical as well and invites people to use regular expressions or think about it, but NO! Don&#8217;t do that!!). Lets say the input string is &#8220;kajabbamajabbajab&#8221;. This string contains a spell. We can find three words as &#8220;jabba&#8221;, &#8220;ma&#8221; and &#8220;jabba&#8221; in it which satisfies the given pattern. &#8220;jabba&#8221; contains two syllables: &#8220;jab&#8221; and &#8220;ba&#8221; or even you can say &#8220;ja&#8221; and &#8220;bba&#8221;. But we can also find another pattern in input string like &#8220;abba&#8221;, &#8220;maj&#8221; and &#8220;abba&#8221; which still it is true. So there are more than one answer (Number of answers doesn&#8217;t matter! You should just be able to find one). Google guys are smart enough to not suggest the second answer, otherwise you could simple find the solution, because finding a pattern using the second answer is quiet simple.</p>
<p>In order to solve it, first we will extract the position of each vowel in the string (doesn&#8217;t matter which vowel it is). Below code simply does this.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> checkSpell<span style="color: black;">&#40;</span>entry<span style="color: black;">&#41;</span>:
    positions = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i,l <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">enumerate</span><span style="color: black;">&#40;</span>entry<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> l <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #483d8b;">'aoeiu'</span>:
            positions.<span style="color: black;">append</span><span style="color: black;">&#40;</span>i<span style="color: black;">&#41;</span></pre></div></div>

<p>This code for the given example string will generate a list like [1,3,6,8,10,13,15]. Now we start from 0, at each step (i), we get a substring that starts at position[i] and ends at position[i+1]. This will be our search term. Then we will check if we can find this string after position[i+2] or not. If we could find it, then we are done. Otherwise, we will advance i and check the next item, till we reach to n-2. What we are doing is, we are using vowels at position i and i+1 to form a two syllables word, and then we are searching for the same two syllables word from position i+2 to make sure we have enough space for the second word. If we could find the first word again anywhere in the string, then we can make sure the string is matching the given pattern and contains a spell. Below you can find code snippet which does the same.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span>positions<span style="color: black;">&#41;</span>-<span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>:
    startIndex = positions<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span>
    endIndex = positions<span style="color: black;">&#91;</span>i+<span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>+<span style="color: #ff4500;">1</span>
    startWord = entry<span style="color: black;">&#91;</span>startIndex:endIndex<span style="color: black;">&#93;</span>
    searchIndex = positions<span style="color: black;">&#91;</span>i+<span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span>+<span style="color: #ff4500;">1</span>
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        spell = entry.<span style="color: black;">index</span><span style="color: black;">&#40;</span>startWord,searchIndex<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">'Spell!'</span>
    <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">ValueError</span>:
        <span style="color: #ff7700;font-weight:bold;">continue</span></pre></div></div>

<p><a title="Problem C's Solution" href="https://github.com/mjfathinia/GoogleCJ/blob/master/2011EuroPython/c.py" target="_blank">Here</a> you can find the complete code and sample input and output files could be found <a href="https://github.com/mjfathinia/GoogleCJ/tree/master/2011EuroPython" target="_blank">here</a> on GitHub.</p>
<h2>Problem D: Twibet</h2>
<p>This problem has 40 points (15 for small data set and 25 for large data set) and believe it or not, it is super easy question. <a title="Problem D" href="http://code.google.com/codejam/contest/dashboard?c=1277486#s=p3" target="_blank">Here</a> you can find the problem statement, and as usual, below you can find it brief. Let&#8217;s say we have some people&#8217;s twitter account Id and we know who follows who. Accounts are stored in a list. At day <em>i</em>, <em>ith</em> person (P<em>i</em>) will tweet something, an all his/her followers will re-tweet it (if they didn&#8217;t already). Your task it to find at day <em>i</em>, how many times that message will be tweeted (or re-tweeted). As you can see, this problem could be solved easily using an stack. By considering the limits, you can even solve the problem without any optimization. At day <em>i</em>, you will add the followers of P<em>i</em> to the top of the stack, then for each item in the stack, you will add the followers of it to the stack (if it is not already there), once you have checked all the items, then you have the result. Below you can find code snippet which does the same.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">N = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>inputFile.<span style="color: #dc143c;">readline</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">strip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
fks = inputFile.<span style="color: #dc143c;">readline</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
monks = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> n <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>N<span style="color: black;">&#41;</span>:
    fk = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>fks<span style="color: black;">&#91;</span>n<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span> - <span style="color: #ff4500;">1</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> fk <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #ff7700;font-weight:bold;">in</span> monks:
        monks<span style="color: black;">&#91;</span>fk<span style="color: black;">&#93;</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    monks<span style="color: black;">&#91;</span>fk<span style="color: black;">&#93;</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>
outputFile.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Case #%d:<span style="color: #000099; font-weight: bold;">\n</span>'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>t+<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> d <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>N<span style="color: black;">&#41;</span>:
    stack = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    visited = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    visited.<span style="color: black;">append</span><span style="color: black;">&#40;</span>d<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> d <span style="color: #ff7700;font-weight:bold;">in</span> monks:
        stack = monks<span style="color: black;">&#91;</span>d<span style="color: black;">&#93;</span><span style="color: black;">&#91;</span>:<span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>stack<span style="color: black;">&#41;</span><span style="color: #66cc66;">&amp;</span>gt<span style="color: #66cc66;">;</span><span style="color: #ff4500;">0</span>:
            m = stack.<span style="color: black;">pop</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">if</span> m <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #ff7700;font-weight:bold;">in</span> visited:
                <span style="color: #ff7700;font-weight:bold;">if</span> m <span style="color: #ff7700;font-weight:bold;">in</span> monks:
                    stack += monks<span style="color: black;">&#91;</span>m<span style="color: black;">&#93;</span><span style="color: black;">&#91;</span>:<span style="color: black;">&#93;</span>
                visited.<span style="color: black;">append</span><span style="color: black;">&#40;</span>m<span style="color: black;">&#41;</span>
    outputFile.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'%d<span style="color: #000099; font-weight: bold;">\n</span>'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span>visited<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p><a title="Problem C's Solution" href="https://github.com/mjfathinia/GoogleCJ/blob/master/2011EuroPython/d.py" target="_blank">Here</a> you can find the complete code and sample input and output files could be found <a href="https://github.com/mjfathinia/GoogleCJ/tree/master/2011EuroPython" target="_blank">here</a> on GitHub.</p>
<p>This concludes the EuroPython2011 contest. As you can see, most of the questions doesn&#8217;t need any specific algorithm and they could be solved directly (usually what you expect to see in Google Code Jam contest is lots of Dynamic Programming questions).</p>
]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/853/gcj-2011-euro-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ and Inconsistency in pagination result</title>
		<link>http://cheraq.com/818/linq-and-inconsistency-in-pagination-result/</link>
		<comments>http://cheraq.com/818/linq-and-inconsistency-in-pagination-result/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 03:50:07 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[LINQ Tips]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://cheraq.com/?p=818</guid>
		<description><![CDATA[LINQ is one of the significant improvements of .Net and from the time it has been added till today I am always using it in all my projects (I forgot how I was using DB before!). But recently I have faced a weird issue. Did you ever faced an issue where you can see items have been stored properly in your database without any duplicates, but when you are using your grid view or listing feature to check pages, there are duplicates and missing items. If so, then don't panic! You are not alone! <a href="http://cheraq.com/818/linq-and-inconsistency-in-pagination-result/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>LINQ is one of the significant improvements of .Net and from the time it has been added till today I am always using it in all my projects (I forgot how I was using DB before!). But recently I have faced a weird issue. This is not a LINQ issue, but you need to keep it into consideration. Let&#8217;s say we have a table with below structure and data inside:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#40;</span>
<span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#91;</span><span style="color: #993333; font-weight: bold;">INT</span><span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">IDENTITY</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">,</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
<span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#91;</span>datetime<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
<span style="color: #993333; font-weight: bold;">CONSTRAINT</span> <span style="color: #66cc66;">&#91;</span>PK_Test<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span> CLUSTERED
<span style="color: #66cc66;">&#40;</span>
<span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">ASC</span>
<span style="color: #66cc66;">&#41;</span><span style="color: #993333; font-weight: bold;">WITH</span> <span style="color: #66cc66;">&#40;</span>PAD_INDEX  <span style="color: #66cc66;">=</span> OFF<span style="color: #66cc66;">,</span> STATISTICS_NORECOMPUTE  <span style="color: #66cc66;">=</span> OFF<span style="color: #66cc66;">,</span> IGNORE_DUP_KEY <span style="color: #66cc66;">=</span> OFF<span style="color: #66cc66;">,</span> ALLOW_ROW_LOCKS  <span style="color: #66cc66;">=</span> <span style="color: #993333; font-weight: bold;">ON</span><span style="color: #66cc66;">,</span> ALLOW_PAGE_LOCKS  <span style="color: #66cc66;">=</span> <span style="color: #993333; font-weight: bold;">ON</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">ON</span> <span style="color: #66cc66;">&#91;</span><span style="color: #993333; font-weight: bold;">PRIMARY</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">ON</span> <span style="color: #66cc66;">&#91;</span><span style="color: #993333; font-weight: bold;">PRIMARY</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #993333; font-weight: bold;">SET</span> IDENTITY_INSERT <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">ON</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-24 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-24 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">3</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-24 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">4</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-24 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">6</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">7</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">8</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">9</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">11</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">12</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">13</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">14</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">15</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">16</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2011-08-21 00:00:00.000'</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #993333; font-weight: bold;">SET</span> IDENTITY_INSERT <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> OFF</pre></div></div>

<p>Now if you want to run below LINQ operation for pagination, you will be surprised:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span><span style="color: #008000;">&#40;</span>var db <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TestDataContext<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	var page_1_items <span style="color: #008000;">=</span> db<span style="color: #008000;">.</span><span style="color: #0000FF;">Test</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OrderByDescending</span><span style="color: #008000;">&#40;</span>i<span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> i<span style="color: #008000;">.</span><span style="color: #0000FF;">NDate</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Take</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToList</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	var page_2_items <span style="color: #008000;">=</span> db<span style="color: #008000;">.</span><span style="color: #0000FF;">Test</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OrderByDescending</span><span style="color: #008000;">&#40;</span>i<span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> i<span style="color: #008000;">.</span><span style="color: #0000FF;">NDate</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Skip</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Take</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">10</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToList</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The page_1_items will be as following:</p>
<pre>Id  NDate
4   2011-08-24 00:00:00.000
3   2011-08-24 00:00:00.000
2   2011-08-24 00:00:00.000
1   2011-08-24 00:00:00.000
11  2011-08-21 00:00:00.000
10  2011-08-21 00:00:00.000
9   2011-08-21 00:00:00.000
8   2011-08-21 00:00:00.000
7   2011-08-21 00:00:00.000
6   2011-08-21 00:00:00.000</pre>
<p>And page_2_items will be:</p>
<pre>Id  NDate
11  2011-08-21 00:00:00.000
12  2011-08-21 00:00:00.000
13  2011-08-21 00:00:00.000
14  2011-08-21 00:00:00.000
15  2011-08-21 00:00:00.000
16  2011-08-21 00:00:00.000</pre>
<p>Did you noticed that some items are missing (item with ID 5)? and also item with ID equals to 11 will be repeated two times! Well, this was surprising me as well. The reason behind this is, generated query to load first page uses TOP X, but for other pages uses ROW_NUMBER(). This is for improving the performance, but this can make trouble for you as well. Below you can find generated queries:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* For first page */</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> TOP <span style="color: #cc66cc;">10</span> <span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">FROM</span> <span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> NDate <span style="color: #993333; font-weight: bold;">DESC</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/* For second page */</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">FROM</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #993333; font-weight: bold;">ROW_NUMBER</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">OVER</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> NDate <span style="color: #993333; font-weight: bold;">DESC</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> RNumber<span style="color: #66cc66;">,</span> Id<span style="color: #66cc66;">,</span>NDate
  <span style="color: #993333; font-weight: bold;">FROM</span> <span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> t
<span style="color: #993333; font-weight: bold;">WHERE</span> RNumber <span style="color: #993333; font-weight: bold;">BETWEEN</span> <span style="color: #cc66cc;">11</span> <span style="color: #993333; font-weight: bold;">AND</span> <span style="color: #cc66cc;">20</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/* Supposed to return same result as TOP 10, but it is different!! */</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">&#91;</span>Id<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">,</span><span style="color: #66cc66;">&#91;</span>NDate<span style="color: #66cc66;">&#93;</span> <span style="color: #993333; font-weight: bold;">FROM</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #993333; font-weight: bold;">ROW_NUMBER</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">OVER</span> <span style="color: #66cc66;">&#40;</span><span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> NDate <span style="color: #993333; font-weight: bold;">DESC</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> RNumber<span style="color: #66cc66;">,</span> Id<span style="color: #66cc66;">,</span>NDate
  <span style="color: #993333; font-weight: bold;">FROM</span> <span style="color: #66cc66;">&#91;</span>Test<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">AS</span> t
<span style="color: #993333; font-weight: bold;">WHERE</span> RNumber <span style="color: #993333; font-weight: bold;">BETWEEN</span> <span style="color: #cc66cc;">1</span> <span style="color: #993333; font-weight: bold;">AND</span> <span style="color: #cc66cc;">10</span></pre></div></div>

<p>To solve the issue, you need to add secondary ordering statement to ORDER BY statement (in this case we need to add Id as well). So whenever you are sorting your items and performing pagination, consider secondary ordering as well. This is not a perfect solution, because there are lots of cases where you want to allow user to choose ordering column (like when listing items in grid view, etc.). If you are wondering why LINQ is behaving like this, there might be some performance considerations in doing like this, since using TOP X does not require any other operation and it is more likely to be used (usually you want to show most viewed or commented or recent items, which can be addressed by TOP X easily).</p>
]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/818/linq-and-inconsistency-in-pagination-result/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Divide and Conquer is the new black!</title>
		<link>http://cheraq.com/772/divide-and-conquer-is-the-new-black/</link>
		<comments>http://cheraq.com/772/divide-and-conquer-is-the-new-black/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 00:31:04 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[Algorithms]]></category>

		<guid isPermaLink="false">http://cheraq.com/?p=772</guid>
		<description><![CDATA[Divide and conquer is an algorithm design paradigm that solves problem by dividing it to smaller sub-problems and solving them either by dividing them to smaller ones, or by any other algorithms. This is a very old way of solving problems. However, recent technology advancements did not make it off-fashion. There are two well-known and powerful algorithms based on this methodology: Binary Search and Merge Sort. What we are going to do is, have a look at the main idea behind it, discuss about algorithms based on it, and see how we can use it in our daily projects. <a href="http://cheraq.com/772/divide-and-conquer-is-the-new-black/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>Definition</h2>
<p>Divide &amp; Conquer (D&amp;C) is an important algorithm design paradigm based on multi-branched recursion [<a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" target="_blank">Wikipedia</a>]. In simple words, D&amp;C solves the problem by dividing it into smaller sub-problems. Usually this sub-problems are much more smaller than the original problems (like dividing it into half). If the sub-problem still is complicated, D&amp;C divides that sub-problem into smaller sub-problems and continues this until the sub-problem is simple enough to be solved directly. At this stage, you can solve problem easily and usually in constant time (i.e. <em><strong>O</strong></em>(<em>c</em>)). Then the result of this sub-problem will be sent upwards and merged with other sub-problems result and forms the final result.</p>
<p>Below image shows how a D&amp;C based algorithm works. At this example we want to sort a list of numbers. What we will do is, start to split the list into smaller sub-lists  until we have only one item in the list. Well a list with one item in it is already sorted!! So there is nothing special till here, but the key is how you will merge the result. That&#8217;s why this algorithm called Merge Sort. Check it out below. We will discuss it later.</p>
<div id="attachment_778" class="wp-caption aligncenter" style="width: 310px"><a href="http://cheraq.com/wp-content/uploads/2011/07/merge_sort_algorithm_diagram.png"><img class="size-medium wp-image-778" title="merge_sort_algorithm_diagram" src="http://cheraq.com/wp-content/uploads/2011/07/merge_sort_algorithm_diagram-300x288.png" alt="Merge Sort - A D&amp;C based algorithm sample" width="300" height="288" /></a><p class="wp-caption-text">Figure 1: Merge Sort - A D&amp;C based algorithm example</p></div>
<h2>Key Steps</h2>
<p>When you want to solve a problem using D&amp;C, the first step is, finding a good <strong>diving</strong> procedure. You have to decide how you are going to divide your problem into sub-problems. Diving should be done in a way that it will simplify the problem and reduce the problem size to half or close to half.</p>
<p>Also you should decide when you will stop division and start to solve, which is <strong>desired problem size</strong>. Choosing a good stop point is crucial, because D&amp;C usually leads to <strong>recursive</strong> procedures, and so many recursive calls can increase time/space complexity exponentially. It is possible to remove the recursion by using <strong>stack</strong>, but then again you will face a new problem which is determining proper <strong>stack size</strong>.</p>
<p>Another option you can consider when you are solving problems is: <strong>Parallel Programming</strong>. Since D&amp;C divides problem into distinct sub-problems, those problems could be easily solved in parallel, either using <strong>multi-processor machines</strong> or <strong>cloud computing</strong>. For example, if you want to search for specific term in a database with size of Google database, it might take ages to find items and sort them, but using cloud (like Google App Engine environment), you can get result in less than one second. Next you will see some powerful algorithms based on D&amp;C.</p>
<h2>Binary Search</h2>
<p>Binary Search is a fast searching algorithm that can find index of a value in a sorted array. For simplicity, lets say you have a sorted array that contains values in range [0..10] (see Figure 2). Now lets say we are searching for a number, (e.g. 2) in this list. What we can do is we can start from first number and check each and every number until we either find 2 or reach to the end of the list.  But like this if we want to search in a big list, it will take too much time. What we can do is, we can check the middle item (in this example, it is 5) with the value we are looking for (which is 2). if the value is smaller than middle value (2&lt;5), then we can consider the lower sub-array to middle item for our next step of the search and we can ignore the other part. As you can see, because our array is sorted, we can do this kind of prediction. At this step we have reduced our problem size to half and now we need to search to half of the array for the desired number. If we continue this process, at last step we will have this two conditions:</p>
<ul>
<li>Array size reduced to 1, and we can solve problem directly by checking the remaining number with sought value</li>
<li>Middle item is equals with number we were looking for (which is the answer)</li>
</ul>
<div>Figure 2 shows some examples of binary search in a sorted array of integer numbers.</div>
<div id="attachment_784" class="wp-caption aligncenter" style="width: 323px"><a href="http://cheraq.com/wp-content/uploads/2011/07/bins01.gif"><img class="size-full wp-image-784" title="Binary Search" src="http://cheraq.com/wp-content/uploads/2011/07/bins01.gif" alt="" width="313" height="290" /></a><p class="wp-caption-text">Figure 2: Binary Search in a sorted array of numbers</p></div>
<p>Below you can find python code for binary search. Most of the programming languages have built-in implementation for binary search and you usually don&#8217;t need to implement it again.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> binary_search<span style="color: black;">&#40;</span>seq, t<span style="color: black;">&#41;</span>:
    <span style="color: #008000;">min</span> = <span style="color: #ff4500;">0</span><span style="color: #66cc66;">;</span> <span style="color: #008000;">max</span> = <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>seq<span style="color: black;">&#41;</span> - <span style="color: #ff4500;">1</span>
    <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">max</span> <span style="color: #66cc66;">&amp;</span>lt<span style="color: #66cc66;">;</span> <span style="color: #008000;">min</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span> -<span style="color: #ff4500;">1</span>
        m = <span style="color: black;">&#40;</span><span style="color: #008000;">min</span> + <span style="color: #008000;">max</span><span style="color: black;">&#41;</span> / <span style="color: #ff4500;">2</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> seq<span style="color: black;">&#91;</span>m<span style="color: black;">&#93;</span> <span style="color: #66cc66;">&amp;</span>lt<span style="color: #66cc66;">;</span> t:
            <span style="color: #008000;">min</span> = m + <span style="color: #ff4500;">1</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> seq<span style="color: black;">&#91;</span>m<span style="color: black;">&#93;</span> <span style="color: #66cc66;">&amp;</span>gt<span style="color: #66cc66;">;</span> t:
            <span style="color: #008000;">max</span> = m - <span style="color: #ff4500;">1</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span> m</pre></div></div>

<p>As you can see in the code above, at each step, the list will be divided to half and then one half will be used for the next step, so your algorithm at worse case will be <em>O</em>(log2 <em>n</em>) or for simplicity <em>O</em>(log <em>n</em>). This means if you have a list which contains 1 billion items (1,000,000,000), using binary search at worse case you need to examine 30 items to find the result, but if you do normal search, you might need 1 billion examinations and at end you will find out it is not in the list.</p>
<p>There are some argue about Binary Search and some people are saying Binary Search is not a complete D&amp;C based algorithm because it is dividing the problem into two sub-problems, but it is only considering one of them for next step; and based on this, they are offering different name for it such as decrease and conquer, etc. No matter what we call it, Binary Search is a ROCK STAR.  If you check Wikipedia for binary search, you will find out that implementing Binary Search seems easy initially, but is tricky. I hope the code I&#8217;ve published above is correct <img src='http://cheraq.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<blockquote><p>Although the basic idea of binary search is comparatively straightforward, the details can be surprisingly tricky… <span style="white-space: nowrap;">— Professor <a title="Donald Knuth" href="http://en.wikipedia.org/wiki/Donald_Knuth">Donald Knuth</a></span></p></blockquote>
<h2>Merge Sort</h2>
<p>Merge sort is another D&amp;C based algorithm that we will have a look at it in this post. We have already discussed about this algorithm at the beginning of this post (see Figure 1), but below you can find the general idea behind it.</p>
<p>Let&#8217;s say we have a list (<em>L</em>) with size <em><strong>n</strong></em> and we want to sort it. Like any other D&amp;C algorithm, first step is to divide the problem into smaller sub-problems. In Merge Sort, at each step, we should divide the list into to sub-lists with size almost equal to <strong><em>n</em>/2</strong>. We will do this until we reach to a list with size equal to <strong>1</strong>. At this point, we will stop dividing and start solving the problem. Before we start next step, let&#8217;s see what we have right now, we have <strong><em>n</em></strong> lists with size <strong>1</strong>. Now we start to conquer the sub-problems and form final result. At each step we will merge two sorted lists, this can be done in <strong><em>O</em>(<em>n</em>)</strong>. At the worst case, the time complexity of merge sort will be <strong><em>O</em>(<em>n </em>log2<em> n</em>)</strong>.</p>
<p>Another issue that should be considered about Merge Sort is it&#8217;s space complexity. An iterative but non-recursive version of merge sort requires <strong>2<em>n</em></strong> space, which means if you have a list with size <strong>1GB</strong>, then you need <strong>2GB</strong> space in order to perform merge sort. This is because of the fact that merging two lists with size <em><strong>n</strong></em><strong>/2</strong> requires <strong><em>n</em><strong>/2 + <em>n</em>/2 + <em>n</em> = 2<em>n</em></strong></strong> space (two lists with size <strong><em>n</em><strong>/2</strong></strong> and one list with size <strong><strong><em>n</em></strong></strong> to save merged result). There are also some implementations which requires only <em><strong>n</strong></em><strong>/2</strong> extra space to perform the search, but for huge arrays where space is a key factor, other algorithms such as <strong>heap sort</strong> might be better option.</p>
<h2><span class="Apple-style-span" style="font-size: 20px; font-weight: bold;">Conclusion</span></h2>
<p>D&amp;C can be used to solve complicated problems in acceptable time/space complexity. This technique is the basis of efficient algorithms for all kinds of problems, such as searching, sorting,  multiplying large number, syntactic analysis and so on. Main idea behind D&amp;C is to reduce the problem into smaller sub-problems that could be solved independently and their result could form the main problem&#8217;s result. Since D&amp;C creates independent sub-problems, it can benefit from Parallel Programming and Cloud Computing more than other methodologies and that&#8217;s why D&amp;C is the new Black!</p>
]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/772/divide-and-conquer-is-the-new-black/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Algorithms: What? Why? When? How?</title>
		<link>http://cheraq.com/735/algorithms-what-why-when-how/</link>
		<comments>http://cheraq.com/735/algorithms-what-why-when-how/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 19:35:57 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[Algorithms]]></category>

		<guid isPermaLink="false">http://cheraq.com/wp/?p=735</guid>
		<description><![CDATA[In computer software, Algorithm is a very common term. Lots of people use this terms without even knowing the meaning or usage of them. Finding proper algorithm for a given problem could be challenging. Nowadays, hardware performance is improved a lot and this means we have faster CPUs and more memory to perform computations. This is a first article of Algorithms series, where we will discuss about algorithms and we will try to adapt the classic algorithms with our modern machines. <a href="http://cheraq.com/735/algorithms-what-why-when-how/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve heard about algorithms a lot. In this short article, I am going to a little bit talk about algorithms, their importance, etc. which will be the first post in my Algorithms series. If you follow the series, you will get familiar with different type of algorithms, old and classic ones, or new and heuristic ones. Just follow the series.</p>
<h2>What is an algorithm?</h2>
<p>An algorithm in simple language is a finite set of instructions for calculating a function. For example we are looking for a file in a folder, what we might do is, we start from beginning of the list, check each and every file until we find the file we want or reaching to the end of the list. This is an algorithm.</p>
<h2>Why we should learn them?</h2>
<p>Algorithms are actually ways to solve problems; but they are not the solution. By learning algorithms you will find methods that help you in solving problems. It is like <a href="http://en.wikipedia.org/wiki/Data_structure" target="_blank">Data Structure</a>. If we consider data structure as a tool, algorithms will be manual that helps us to learn how to use those tools to do desired task.</p>
<h2>When shall I use specific algorithm?</h2>
<p>The solution and algorithm you choose for any given problem, depends to:</p>
<ul>
<li>The way you are looking at the problem and visualizing it</li>
<li>Run Time/Space limits</li>
<li>Input Size</li>
</ul>
<p>These are only key factors. There are lots of other factors that might play a key role in selecting an algorithm, such as data structure, etc. Maybe the last two factors are obvious, but let&#8217;s see how the first factor might play a key role. Consider the classic 8-Queen problem. In this problem we want to place 8 queens in a 8&#215;8 chessboard in a way that none of them could attack others.</p>
<p>Let&#8217;s say we are going to solve it by placing one queen at a time in a way that it will not be able to attack previous queens we have placed. Once we reached to a place that we cannot find a place for this queen, we will return back and move the previous queen to another cell and then continue, until we reach to a result. In this way we are using <strong>backtracking</strong> to solve the issue.</p>
<p>But there is another way to look at the problem. Let&#8217;s say we will place 8 queens in 8 rows randomly. Then we start to move queens in a way to minimize the number of queens that can attach each other. Now we have turned the problem into <strong>optimization problem</strong>. So as you can see, they way you are understanding and visualizing a problem will play a key role in solving it and finding algorithm.</p>
<h2>How we can compare two algorithms?</h2>
<p>Well, if there are different algorithms to solve a problem, then there should be some ways to compare them (I&#8217;m genius). We usually compare two algorithms based on their <strong>time</strong> and <strong>space complexity</strong>. Time and space complexity are not displaying the exact amount of time/space are required to solve a problem; instead they indicate how the time/space requirements will grow when the problem size grows. Since we want to study how the time/space requirements will grow, then we don&#8217;t need to consider the exact equation of time/space complexity; We can just consider the biggest factor. Let&#8217;s see this in below simple example.</p>
<h4>Finding an item in an ordered list</h4>
<p>Let&#8217;s say we have an ordered list of numbers with size <strong><em>n </em></strong>and we want to see if this list contains number <em><strong>x</strong></em> or not. We can use below ways to search for <em><strong>x</strong></em>:</p>
<p><strong>Algorithm 1:</strong> We will start from first item and compare it with <em><strong>x</strong></em>: if it is equal, then list contains this number, otherwise, we will go to next item until we reach end of the list or find <em><strong>x</strong></em> in the list.</p>
<p><strong>Algorithm 2 (Binary Search):</strong> We compare <em><strong>x</strong></em> with the middle item of the list. If <em><strong>x</strong></em> is larger than middle item, then we should be able to find it in the second half of the list and we can ignore the first one and vice versa. Once we find out on which part of the list we have to search for <em><strong>x</strong></em>, then we repeat the same step, compare <em><strong>x</strong></em> with the middle item of this new list (first/second half). We continue this until we find <em><strong>x</strong></em> or reaching to a list with size 1.</p>
<p>As you can see, we usually using second algorithm to find items in ordered list. Now let&#8217;s see how we can compare the time complexity of these two algorithms. When we want to estimate time complexity, we count how many times a key action or block of actions will be repeated. Like in our example, how many times we should perform comparison to find out given list contains <em><strong>x</strong></em> or not. In order to eliminate role of <em><strong>x</strong></em> in our estimation, we consider the worth-case scenario such as list does not contain <em><strong>x</strong></em>.</p>
<p>In the algorithm 1, we need to do comparison <em><strong>n</strong></em> times in the worth-case (which is obvious). But what about algorithm 2? The answer is <strong>log <em>n </em></strong>(when we are using <strong>log</strong>, we usually mean <strong>log</strong> in base 2). If you check the algorithm, you will see at each step we will divide list into half, so the list size will change like: <strong><em>n</em></strong>, <em><strong>n</strong></em>/2, <em><strong>n</strong></em>/4, <em><strong>n</strong></em>/8, <em><strong>n</strong></em>/16, … . So in the worth-case we will continue up to <strong>log <em>n</em></strong>. When we want to denote the time/space complexity, we usually use big O, and we will show it as <strong>O(<em>n</em>)</strong> or <strong>O(log <em>n</em>)</strong>. This mean we are just considering the most significant factor and we are neglecting the others. For example if you algorithms time complexity is polynomial like (<em><strong>n</strong></em>²+<em><strong>n</strong></em>), then we can say the time complexity is equal to <strong>O(<em>n</em>²)</strong>.</p>
<h2> Conclusion</h2>
<p>Finding proper algorithm for a given problem could be challenging. Learning more algorithms will give us better vision and understanding, and we will be able to analyze problem from different aspects and find different algorithms to solve the problem. Time/space complexity enables us to compare algorithms and choose the best algorithm based on input size and other limitations.</p>
<p>This was an introduction about algorithms. In next articles we will see different type of algorithms and their pros and cons.  Also we will learn how to calculate time/space complexity and combine different algorithms with some heuristic functions in order to reduce complexity.</p>
]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/735/algorithms-what-why-when-how/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to resolve URL to absolute path when you don’t have access to page object?</title>
		<link>http://cheraq.com/22/how-to-resolve-url-to-absolute-path-when-you-don%e2%80%99t-have-access-to-page-object/</link>
		<comments>http://cheraq.com/22/how-to-resolve-url-to-absolute-path-when-you-don%e2%80%99t-have-access-to-page-object/#comments</comments>
		<pubDate>Thu, 26 May 2011 10:45:07 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[ASP.NET Tips]]></category>

		<guid isPermaLink="false">http://cheraq.com/wp/?p=22</guid>
		<description><![CDATA[Using Virtual Path will make web applications more portable. If you don't know what I mean by virtual path, it is simply URLs that start with "~/". But resolving this URLs to absolute path something might be tricky. ASP.NET's Page object provides a convenient function "ResolveUrl()" that does this for us, but what if we do not have access to this object?! For example Web Service or Generic Handlers do not provide this functionality. If you are wondering how to achieve this in such situations, then you are on right track.  <a href="http://cheraq.com/22/how-to-resolve-url-to-absolute-path-when-you-don%e2%80%99t-have-access-to-page-object/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>To find out the virtual path, you can use below property of <strong>HttpRuntime</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">HttpRuntime<span style="color: #008000;">.</span><span style="color: #0000FF;">AppDomainAppVirtualPath</span></pre></div></div>

<p>And in order to resolve the URL to absolute path, you can simply replace “~” with the value of HttpRuntime.AppDomainAppVirtualPath and you have your absolute path. Below you can find an extension class to HttpServerUtility that adds ResolveUrl method, and you can use ResolveUrl and MapPath of the HttpContext.Current.Server.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">class</span> HttpServerUtilityExtensions
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">string</span> ResolveUrl<span style="color: #008000;">&#40;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span> HttpServerUtility server,
        <span style="color: #6666cc; font-weight: bold;">string</span> virtualPath
        <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>virtualPath<span style="color: #008000;">.</span><span style="color: #0000FF;">StartsWith</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;~/&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;{0}/{1}&quot;</span>,
                HttpRuntime<span style="color: #008000;">.</span><span style="color: #0000FF;">AppDomainAppVirtualPath</span>,
                virtualPath<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> virtualPath<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/22/how-to-resolve-url-to-absolute-path-when-you-don%e2%80%99t-have-access-to-page-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extension Methods in .NET</title>
		<link>http://cheraq.com/5/extension-methods-in-net/</link>
		<comments>http://cheraq.com/5/extension-methods-in-net/#comments</comments>
		<pubDate>Thu, 26 May 2011 04:19:12 +0000</pubDate>
		<dc:creator>Mohammad J.</dc:creator>
				<category><![CDATA[C# Tips]]></category>

		<guid isPermaLink="false">http://cheraq.com/wp/?p=5</guid>
		<description><![CDATA[Making codes more semantic will help to reduce the maintenance efforts. Dot Net provides a way to add new functionality to existing class without defining new class/type. For example, you want to add HtmlEncode to string class so you could use it like "str.HtmlEncode()" or you want to make converting string to int so easier by adding ToInt32 function to string class and be able to use it like "textbox1.Text.ToInt32()". This is more convenient than using "Convert.ToInt32(textbox1.Text)". Here you will learn how to do it. <a href="http://cheraq.com/5/extension-methods-in-net/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Sometimes, you need to add new methods to a type, for example, when you are developing a website, you need to use <strong>HttpUtility.HtmlEncode()</strong> function to encode html and then dump it to screen. For example if you have a class called <strong>Post</strong> and this class has a property called <strong>PostTitle</strong>, then you need to do like below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Post p <span style="color: #008000;">=</span> Post<span style="color: #008000;">.</span><span style="color: #0000FF;">LoadPost</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
ltPostBody<span style="color: #008000;">.</span><span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span> HttpUtility<span style="color: #008000;">.</span><span style="color: #0000FF;">HtmlEncode</span><span style="color: #008000;">&#40;</span>p<span style="color: #008000;">.</span><span style="color: #0000FF;">PostTitle</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>But if we have a method in string class that does this for us, then life will be easier and we could use something like below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ltPostBody<span style="color: #008000;">.</span><span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span> p<span style="color: #008000;">.</span><span style="color: #0000FF;">PostTitle</span><span style="color: #008000;">.</span><span style="color: #0000FF;">HtmlEncode</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Once way to do this is to modify the <strong>Post</strong> class and change the type of <strong>PostTitle</strong> to a derived type that has HtmlEncode method. But this is not a solution. What if you couldn’t modify the <strong>Post</strong> class? Or what if you couldn’t create new derived type because it is sealed by author. Or lots of other scenarios.</p>
<p>The simple solution is, using extension methods. What is it? <a title="http://msdn.microsoft.com/en-us/library/bb383977.aspx" href="http://msdn.microsoft.com/en-us/library/bb383977.aspx" rel="nofollow" target="_blank">MSDN</a> says:</p>
<blockquote><p>Extension methods enable you to &#8220;add&#8221; methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.</p></blockquote>
<p>The advantage of extension methods are, they will be available on all objects derived from that type. So if you add an extension method to <strong>string</strong> class, then it will be available on all string objects. Let’s see how we will implement extension methods. Again <a title="http://msdn.microsoft.com/en-us/library/bb383977.aspx" href="http://msdn.microsoft.com/en-us/library/bb383977.aspx" rel="nofollow" target="_blank">MSDN</a> says:</p>
<blockquote><p>Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the <strong>this</strong> modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a <strong>using</strong> directive.</p></blockquote>
<p>Let write our own extension method. First we will add new class as below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">namespace</span> Cheraq<span style="color: #008000;">.</span><span style="color: #0000FF;">Extensions</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">class</span> StringExtensions
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// our methods will be defined here</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Now we will define our extension method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">string</span> HTMLEncode<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #6666cc; font-weight: bold;">string</span> phrase<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> HttpUtility<span style="color: #008000;">.</span><span style="color: #0000FF;">HtmlEncode</span><span style="color: #008000;">&#40;</span>phrase<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>First of all, our method should be <strong>static</strong>. Also if you see the parameter, it is so strange. The first parameter should be defined as below:</p>
<p><strong>this</strong> <em>type-that-you-want-to-add-extension-method-to-it</em> parameter-name</p>
<p>After that we will define our implementation of the function. When we want to use the function, we need to add <strong>using</strong> directive to import the namespace. When you import the namespace, the extension method will be available for all object derived from that type. Below image shows our extension method on the auto-complete window. You can see the icon of the extension method is different.</p>
<div id="attachment_769" class="wp-caption aligncenter" style="width: 146px"><a href="http://cheraq.com/wp-content/uploads/2011/05/ext-1.jpg"><img class="size-full wp-image-769" title="Sample Extension Method" src="http://cheraq.com/wp-content/uploads/2011/05/ext-1.jpg" alt="Drop down list with extension method" width="136" height="167" /></a><p class="wp-caption-text">HTMLEncode is an extension method, so it got a different icon.</p></div>
<p>The usage of extension method is same as normal method of that type. You can even add extension method to sealed class. But this will not violate the principal of encapsulation, because extended methods cannot access private variable and methods in the type they are extending. Below you can find summary of some facts about extension methods:</p>
<ol>
<li>Extension methods can only access private variable and methods in the type they are extending!</li>
<li>You cannot use them to override methods of a class or interface</li>
<li>They have lower priority than instance methods defined in the type itself. In other words, compiler first looks into the instance methods; if did not find any method with same signature, then it will search in extension methods.</li>
<li>Extension methods are brought into scope at the namespace level.</li>
<li>If you do not have access to the code of the type that you are extending, then it is better to keep in mind that changes in that type might break the extension method.</li>
<li>Do not make everything as extension method. Use it wisely.</li>
</ol>
<p>Bellow you can find a sample project that demonstrates the usage of extension methods.</p>
]]></content:encoded>
			<wfw:commentRss>http://cheraq.com/5/extension-methods-in-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

