<?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>Coffee, Code and Chocolate &#187; .NET</title>
	<atom:link href="http://blog.ganeshzone.net/blog/index.php/category/dotnet/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ganeshzone.net/blog</link>
	<description>throw new Exception(&#34;#fail&#34;);</description>
	<lastBuildDate>Mon, 26 Jul 2010 19:45:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Lifting the .NET Hood – Part 2 &#8211; Back to basics</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/05/part-2-back-to-basics/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/05/part-2-back-to-basics/#comments</comments>
		<pubDate>Sat, 08 May 2010 17:59:03 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[Rotor]]></category>
		<category><![CDATA[SOS]]></category>
		<category><![CDATA[SSCLI]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=1134</guid>
		<description><![CDATA[<p style="text-align: justify;">When I looked at the first post in this series, I realized had jumped the gun a bit by going straight to generics and didn&#8217;t do enough justice to the fundamentals. So in this post, I have made an effort to go back to the basics.</p>
<p style="text-align: justify;">The CLR (Common Language Runtime) is [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">When I looked at the first <a style="color: blue;" href="http://blog.ganeshzone.net/blog/index.php/2010/03/lifting-the-net-hood-part-1-generics/">post </a>in this series, I realized had jumped the gun a bit by going straight to generics and didn&#8217;t do enough justice to the fundamentals. So in this post, I have made an effort to go back to the basics.</p>
<p style="text-align: justify;">The CLR (Common Language Runtime) is the heart of .NET. It&#8217;s the virtual execution system responsible for converting the platform neutral CIL (Common Intermediate Language) into platform specific and optimized code. The CLR provides services like memory management, garbage collection, exception handling and type verification. Thus it allows language designers to concentrate solely on outputting good CIL and provides a uniform API to allow language interoperability.</p>
<p style="text-align: justify;">The only truth in .NET is the <strong>assembly code</strong> which is the final product. All the rest are virtual constraints enforced by the execution system in a very robust manner. For e.g. A memory address declared as int cannot take a string value, not because the memory is not able to take the value, but rather the CLR makes sure the values conform to the types declared &#8211; a feature called type verification. Usually this happens at the compilation level, but still rechecked at runtime.</p>
<p style="text-align: justify;">Microsoft released the code of the CLI (Common Language Infrastructure) under the name SSCLI (Shared Source CLI). It can be downloaded <a style="color: blue;" href="http://www.microsoft.com/downloads/details.aspx?FamilyId=8C09FD61-3F26-4555-AE17-3121B4F51D4D&amp;displaylang=en">here</a>. Joel Pobar and others wrote a great <a style="color: blue;" href="http://www.amazon.com/exec/obidos/ASIN/059600351X/bluebytesoftw-20/">book </a>about it. Unfortunately the <a style="color: blue;" href="http://www.tedneward.com/files/SSCLI2Internals-DRAFT.pdf">2.0</a> version is still a draft.</p>
<p style="text-align: justify;">Type safety is the most important aspect of .NET programming and a lot of thought went into it. A type can be thought of as a contract which the objects need to conform to. For e.g. in the following code, the Person class is a type &#8211; which is supposed to have five public variables and one method. Any object that claims itself to be a person type must necessarily fulfill this contract &#8211; or the CLR will reject it during runtime. While working with the more mature compilers like C# and VC++, these checks are already done while converting the code to CIL.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> Person
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> _name<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> _ssn<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">char</span> _middleName<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">decimal</span> _phoneNumber<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">char</span> _bloodGroup<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Person<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> name, <span style="color: #FF0000;">int</span> ssn, <span style="color: #FF0000;">char</span> middleName, <span style="color: #FF0000;">decimal</span> phoneNumber, <span style="color: #FF0000;">char</span> bloodGroup<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>._name <span style="color: #008000;">=</span> name<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>._ssn <span style="color: #008000;">=</span> ssn<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>._middleName <span style="color: #008000;">=</span> middleName<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>._phoneNumber <span style="color: #008000;">=</span> phoneNumber<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>._bloodGroup <span style="color: #008000;">=</span> bloodGroup<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetSomeDetails<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">Empty</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Person _p <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;John Doe&quot;</span>, <span style="color: #FF0000;">4454353</span>, <span style="color: #666666;">'B'</span>, <span style="color: #FF0000;">324242432</span>, <span style="color: #666666;">'O'</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    _p.<span style="color: #0000FF;">GetSomeDetails</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The code for object class can be found at <em><strong>sscli20\clr\src\vm\object.h</strong></em> in the SSCLI code and the Type class at <em><strong>\sscli\clr\src\vm\typehandle.h</strong></em>. The Type class which is extensively used in Reflection for reading the type metadata is a wrapper for this TypeHandle class. Lets look at the underlying code for some familiar methods of the TypeHandle, some of which you see in Type Class. So every object that declares itself of this type, indirectly points to the data structure to define itself.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="cpp" style="font-family:monospace;">    BOOL IsEnum<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
    BOOL IsFnPtrType<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">inline</span> MethodTable<span style="color: #000040;">*</span> AsMethodTable<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">inline</span> TypeDesc<span style="color: #000040;">*</span> AsTypeDesc<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
    BOOL IsValueType<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
    BOOL IsInterface<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
    BOOL IsAbstract<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span>
    WORD GetNumVirtuals<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span><span style="color: #008080;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The MethodTable that you see is the datastructure which contains the frequently used fields needed to call the methods. Along with another structure called EEClass, it defines the type identity of an object in .NET. The difference is that the MethodTable contains data that is frequently accessed by the runtime while the EEClass is a larger store of type metadata. This metadata helps querying type information and dynamically invoking methods using the Reflection API. Using the <a style="color: blue;" href="http://etutorials.org/Programming/programming+microsoft+visual+c+sharp+2005/Part+IV+Debugging/Chapter+13+Advanced+Debugging/Son+of+Strike+SOS/">SOS</a> dll&#8217;s DumpHeap command, the address of all the types can be gotten and used to see the EEClass and MethodTables. Lets examine the Person type in the above example.</p>

<div class="wp_syntax"><div class="code"><pre class="cil" style="font-family:monospace;">.load SOS
extension C:\Windows\Microsoft.NET\Framework\v2.0.50727\SOS.dll loaded
&nbsp;
<span style="color: #006400;">!</span>DumpHeap -type Person
PDB symbol for mscorwks.dll <span style="color:blue;">not</span> loaded
 Address       MT     Size
020a34d4 001530f0       <span style="color: #00008B;">36</span>
total <span style="color: #00008B;">1</span> objects
Statistics:
      MT    Count    TotalSize Class Name
001530f0        <span style="color: #00008B;">1</span>           <span style="color: #00008B;">36</span> DebugApp.Person
Total <span style="color: #00008B;">1</span> objects
&nbsp;
<span style="color:gray;font-style:italic;">//Getting the address and using the DumpObj command</span>
&nbsp;
<span style="color: #006400;">!</span>DumpObj 020a34d4
Name: DebugApp.Person
MethodTable: 001530f0
EEClass: 001513d0
Size: <span style="color: #00008B;">36</span><span style="color: #006400;">&#40;</span>0x24<span style="color: #006400;">&#41;</span> bytes
 <span style="color: #006400;">&#40;</span>D:\Ganesh Ranganathan\Documents\Visual Studio <span style="color: #00008B;">2005</span>\Projects\DebugApp\DebugApp\bin\Debug\DebugApp.exe<span style="color: #006400;">&#41;</span>
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
70d00b68  <span style="color: #00008B;">4000001</span>        <span style="color: #00008B;">4</span>        System.String  <span style="color: #00008B;">0</span> <span style="color:blue;font-weight:bold;">instance</span> 020a34b0 _name
70d02db4  <span style="color: #00008B;">4000002</span>        <span style="color: #00008B;">8</span>         System.Int32  <span style="color: #00008B;">1</span> <span style="color:blue;font-weight:bold;">instance</span>  <span style="color: #00008B;">4454353</span> _ssn
70d01848  <span style="color: #00008B;">4000003</span>        c          System.Char  <span style="color: #00008B;">1</span> <span style="color:blue;font-weight:bold;">instance</span>       <span style="color: #00008B;">42</span> _middleName
70cd7f00  <span style="color: #00008B;">4000004</span>       <span style="color: #00008B;">10</span>       System.Decimal  <span style="color: #00008B;">1</span> <span style="color:blue;font-weight:bold;">instance</span> 020a34e4 _phoneNumber
70d01848  <span style="color: #00008B;">4000005</span>        e          System.Char  <span style="color: #00008B;">1</span> <span style="color:blue;font-weight:bold;">instance</span>       4f _bloodGroup</pre></div></div>

<p style="text-align: justify;">Lets dissect this output. First the DumpObj command lists both the MethodTable and the EEClass address and the proceeds to list the fields . See how the value column lists the direct value for the int and char fields while the address is listed for the reference type string. However the bigger decimal type, which actually is a struct and hence a value type, displays the reference. Though SOS displays the reference, we can observe that the address is actually an offset from the object header, which means that it is still stored by value and not the reference. Looking at the memory window for the string and decimal fields&#8217;s address gives their original values.
</p>
</p>
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/05/decimal.jpg"><img class="aligncenter size-full wp-image-1167" title="decimal" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/05/decimal.jpg" alt="" width="605" height="218" /></a><br />
<a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/05/string.jpg"><img class="aligncenter size-full wp-image-1169" title="string" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/05/string.jpg" alt="" width="575" height="132" /></a></p>
<p style="text-align: justify;">Viewing the object in the memory window shows a pattern of how the runtime stores the values in memory. The object starts with a reference to the MethodTable, then the fields are lined up. It can be observed that there is a difference in how the runtime stores the values of the fields and how we defined them. For e.g. The two character fields are pushed together in spite of not being declared sequentially. This is done to save memory and the runtime is able to manage this situation because all it stores is the memory offset of the fields from the header. To avoid this behavior, types can be decorated with the [StructLayout(LayoutKind.Sequential)] attribute, often used while marshalling data out of managed code, because unmanaged code cant deal with such vagaries. You should also pin your objects, especially references while passing them to unmanaged code, because the runtime keeps moving the memory blocks around.</p>
<p style="text-align: justify;"><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/05/object.jpg"><img class="aligncenter size-full wp-image-1174" title="object" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/05/object.jpg" alt="" width="587" height="175" /></a></p>
<p style="text-align: justify;">Now lets look at the MethodTable through SOS. As you can see, every type also inherits the methods from its parent, in this case System.Object. The MethodTable also contains a pointer to the EEClass. When it is laid out during type creation, the method points to a temporary piece of code called a <a style="color: blue;" href="http://en.wikipedia.org/wiki/Thunk">thunk</a>. The thunk in turn calls the JIT compiler and asks it to compile the method. This lazy compilation works wonders for performance and the memory footprint. Once the method is compiled the JIT updates the method to point to the compiled code instead of the thunk.</p>
</p>

<div class="wp_syntax"><div class="code"><pre class="cil" style="font-family:monospace;"><span style="color: #006400;">!</span>DumpMT -MD 001230f0
EEClass: 001213d0
Module: 00122c5c
Name: DebugApp.Person
mdToken: 02000005  <span style="color: #006400;">&#40;</span>D:\Ganesh Ranganathan\Documents\Visual Studio <span style="color: #00008B;">2005</span>\Projects\DebugApp\DebugApp\bin\Debug\DebugApp.exe<span style="color: #006400;">&#41;</span>
BaseSize: 0x24
ComponentSize: 0x0
Number of IFaces <span style="color:blue;font-weight:bold;">in</span> IFaceMap: <span style="color: #00008B;">0</span>
Slots <span style="color:blue;font-weight:bold;">in</span> VTable: <span style="color: #00008B;">6</span>
--------------------------------------
MethodDesc Table
   Entry MethodDesc      JIT Name
70c56aa0   70ad4a34   PreJIT System.Object.ToString<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
70c56ac0   70ad4a3c   PreJIT System.Object.Equals<span style="color: #006400;">&#40;</span>System.Object<span style="color: #006400;">&#41;</span>
70c56b30   70ad4a6c   PreJIT System.Object.GetHashCode<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
70cc7550   70ad4a90   PreJIT System.Object.Finalize<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
0012c030   001230c4      JIT DebugApp.Person.<span style="color:maroon;font-weight:bold;">.ctor</span><span style="color: #006400;">&#40;</span>System.String, Int32, Char, System.Decimal, Char<span style="color: #006400;">&#41;</span>
0012c038   001230d4     NONE DebugApp.Person.GetSomeDetails<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span></pre></div></div>

<p style="text-align: justify;">You can see the JIT column says none for the GetSomeDetails method and thats because it hasnt been called yet. After its called for the first time, the method is JIT compiled and the MethodDesc shows the code address where the compiled code can be found. Note however, that the MethodDesc is not the usual route for the runtime to execute methods, it is rather done directly. Only when the method is invoked by its name, is the MethodDesc required.</p>
</p>

<div class="wp_syntax"><div class="code"><pre class="cil" style="font-family:monospace;"><span style="color: #006400;">!</span>DumpMT -MD 001230f0
EEClass: 001213d0
Module: 00122c5c
Name: DebugApp.Person
mdToken: 02000005  <span style="color: #006400;">&#40;</span>D:\Ganesh Ranganathan\Documents\Visual Studio <span style="color: #00008B;">2005</span>\Projects\DebugApp\DebugApp\bin\Debug\DebugApp.exe<span style="color: #006400;">&#41;</span>
BaseSize: 0x24
ComponentSize: 0x0
Number of IFaces <span style="color:blue;font-weight:bold;">in</span> IFaceMap: <span style="color: #00008B;">0</span>
Slots <span style="color:blue;font-weight:bold;">in</span> VTable: <span style="color: #00008B;">6</span>
--------------------------------------
MethodDesc Table
   Entry MethodDesc      JIT Name
70c56aa0   70ad4a34   PreJIT System.Object.ToString<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
70c56ac0   70ad4a3c   PreJIT System.Object.Equals<span style="color: #006400;">&#40;</span>System.Object<span style="color: #006400;">&#41;</span>
70c56b30   70ad4a6c   PreJIT System.Object.GetHashCode<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
70cc7550   70ad4a90   PreJIT System.Object.Finalize<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
0012c030   001230c4      JIT DebugApp.Person.<span style="color:maroon;font-weight:bold;">.ctor</span><span style="color: #006400;">&#40;</span>System.String, Int32, Char, System.Decimal, Char<span style="color: #006400;">&#41;</span>
0012c038   001230d4      JIT DebugApp.Person.GetSomeDetails<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
&nbsp;
<span style="color: #006400;">!</span>DumpMD 001230d4
Method Name: DebugApp.Person.GetSomeDetails<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
Class: 001213d0
MethodTable: 001230f0
mdToken: 06000007
Module: 00122c5c
IsJitted: yes
CodeAddr: 009f01c8</pre></div></div>

</p>
<p style="text-align: justify;">In this post we saw basic functioning of the CLR and how it creates and stores internal data structures to facilitate code execution at the same time abstracting away all the gory details from the developer and allowing him to solely concentrate on his applications. Below the hood everything is simply memory addresses pointing to each other and a bunch of assembly code. To give it such a high degree of structure and definition is  by no means an easy task. Hats off to the developers in the .NET and Java teams!! Hope I am able to reach their skill levels one day. <img src='http://blog.ganeshzone.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/05/part-2-back-to-basics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to save your application from getting trashed</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/05/how-to-save-your-application-from-getting-trashed/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/05/how-to-save-your-application-from-getting-trashed/#comments</comments>
		<pubDate>Mon, 03 May 2010 21:36:42 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Best practices]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=1116</guid>
		<description><![CDATA[<p style="text-align: justify;">You spend a lot of time in creating an application, starting with abstractions and slowly moving to the specifics,  hours of heated debate to painstakingly design each and every intricate detail, working on all possibilities for  extensibility, even going through every line of code other developers write to make sure they stick to [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">You spend a lot of time in creating an application, starting with abstractions and slowly moving to the specifics,  hours of heated debate to painstakingly design each and every intricate detail, working on all possibilities for  extensibility, even going through every line of code other developers write to make sure they stick to the design.  Yes, a lot of effort goes into creating and delivering a production quality application which satisfies all the  stakeholders.</p>
<p style="text-align: justify;">Ideally, thats when a developer should say goodbye to the application vowing never to see the code again. Coz, if  he does, he&#8217;d end up mighty disappointed. Future developers would have literally pillaged the application to  systematically eliminate any traces of the original design, the code would be littered with dirty bug fixes and so -called enhancements that don&#8217;t &#8220;enhance&#8221; anything. The customer doesn&#8217;t care because the application still works,  the managers don&#8217;t care because they meet their revenue targets and the timelines, and the developers never cared  in the first place.</p>
<p>Keeping that in mind, I listed down a few ways which might help save your application from meeting the same fate.</p>
<ul>
<li style="text-align: justify;"> <span style="size: 30px"><strong>Keep it Simple</strong></span>:  The oft repeated rule in software design is<strong><em> &#8220;Keep everything as simple as possible, but not  simpler&#8221;</em></strong>. If the design is too complex, then in all probability no developer would take the pains to go through it  and understand the whole thing. Many software engineers are guilty of trying to force fit their code to use a certain design pattern. Instead,look for the pattern which best fits your requirement</li>
</ul>
<ul>
<li style="text-align: justify;"><strong>Keep it Modular</strong>: Dividing your application into logically seperated projects makes it easier to identify the right  places to make the changes. Proper namespaces help too. For e.g. an assembly with the namespace  <em>ABCApplication.HelperObjects.FileIOOperations</em> leaves no space for doubt about what it does.</li>
</ul>
<ul>
<li style="text-align: justify;"><strong>Keep it Visual</strong>: Sure, you might find the 1000 page SMTD an interesting read, but not everyone else will. Remember a  bored developer would be the most likely to introduce a dirty fix in the code. So, to keep things interesting, go  for easy to understand graphics and images. MS Visio is a great tool to model your application, and it supports  automatic code generation as well (Enterprise Architect version). And after creating the model, dont leave it in a  random location that even you would forget in 2 weeks. My advice is to check it in the Source control along with  the code and add it to the Visual Studio Solution.</li>
</ul>
<ul>
<li style="text-align: justify;"><strong>Keep it Commented</strong>: Good commenting is the most potent weapon in your arsenal to guide/warn/ prohibit future  developers from making changes they shouldnt be doing. XML comments are a great way to maintain uniform commenting  standards across the application and can also be used to generate comment documentation automatically (using the  /doc switch while compiling) . A good way to convey how you intended the code to be used is to include a sample code block in the xml comments itself. Keep it mind though, that the comments are stripped out by the compiler, so  if you want comments to appear in the intellisense while using the assemblies, then the generated documentation  file must be packaged along with the assembly.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/05/how-to-save-your-application-from-getting-trashed/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JQuery &#8211; The javascript magic bullet</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/04/jquery-the-javascript-magic-bullet/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/04/jquery-the-javascript-magic-bullet/#comments</comments>
		<pubDate>Sun, 11 Apr 2010 16:24:31 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Web Programming]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=1053</guid>
		<description><![CDATA[<p style="text-align: justify;">Anyone who has written a fairly complex web application would have experienced the quirks of JavaScript. Though immensely powerful and probably the only way to write good client side code, JavaScript code can get difficult especially while doing complex DOM navigation and including cross browser support (Many browsers see the DOM differently).</p>
<p style="text-align: [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Anyone who has written a fairly complex web application would have experienced the quirks of JavaScript. Though immensely powerful and probably the only way to write good client side code, JavaScript code can get difficult especially while doing complex DOM navigation and including cross browser support (Many browsers see the DOM differently).</p>
<p style="text-align: justify;">The best possible solution to harness the power of JavaScript and making the code fun to write is to use client side libraries which do the dirty work for you. Arguably the most popular one available today is JQuery. It makes code both easy to read and write. Here are some cool things you can do with JQuery. To get started download jQuery at <a href="http://jquery.com/">jquery.com</a>, and reference the script file before any your custom scripts.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; &gt;
&lt;head&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;Scripts/jquery.js&quot; language=&quot;javascript&quot; &gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;Scripts/myscript.js&quot; language=&quot;javascript&quot; &gt;&lt;/script&gt;
&lt;/head&gt;</pre></td></tr></table></div>

<ul>
<li style="text-align: justify;"><strong>Code which runs on page load</strong>: The classic way to do this was using the window.onload event. However, the onload event waits for all of the page to get loaded, including images. This can make the user wait for a long time before the events fire. jquery has an alternative &#8211; document.ready which fires as soon as the DOM gets loaded. In heavy pages, this can dramatically increase user experience</li>
</ul>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</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><span style="color: #3366CC;">&quot;Hello jquery&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<ul>
<li style="text-align: justify;"><strong>Hooking up dynamic event handlers</strong>: Hooking up Javascript events was a pain. Now its surprisingly easy. Note how the document.getElementById has been replaced by the $. In this example we hook up a dynamic event handler for a button click event which gets the value from a textbox.</li>
</ul>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</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: #006600; font-style: italic;">//Getting value of button and assigning an event</span>
    <span style="color: #006600; font-style: italic;">//handler using an anonymous method</span>
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#btnSayHello'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</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><span style="color: #3366CC;">'Hello '</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#txtName'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<ul>
<li style="text-align: justify;"><strong>Animation made easy</strong>: Animation has always difficult in Javascript and pushed people towards Flash/Silverlight. JQuery&#8217;s animate API makes things almost too easy. In the example below, a div&#8217;s size is increased, its moved towards the left, made slightly transparent</li>
</ul>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;input type=&quot;button&quot; id=&quot;btnAnimate&quot; value=&quot;Animate&quot; /&gt;
&lt;div id=&quot;containerDiv&quot; &gt;
This is the text which would be animated
&lt;/div&gt;</pre></td></tr></table></div>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</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: #006600; font-style: italic;">//The animation is hooked on to</span>
    <span style="color: #006600; font-style: italic;">//the Animate Button's click handler,</span>
    <span style="color: #006600; font-style: italic;">//A callback function is specified to alert</span>
    <span style="color: #006600; font-style: italic;">//when the animation is over</span>
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#btnAnimate'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</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: #009900;">&#40;</span><span style="color: #3366CC;">'#containerDiv'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">animate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
            opacity<span style="color: #339933;">:</span> <span style="color: #CC0000;">0.6</span><span style="color: #339933;">,</span>
            marginLeft<span style="color: #339933;">:</span> <span style="color: #3366CC;">'+=2in'</span><span style="color: #339933;">,</span>
            fontSize<span style="color: #339933;">:</span> <span style="color: #3366CC;">'3em'</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">1000</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><span style="color: #3366CC;">'animation complete'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<ul>
<li style="text-align: justify;"><strong>AJAXify your application almost instantly</strong>: Writing raw AJAX code was just too much of a hassle considering the time you spent on ironing out the browser differences rather than your core application logic. JQuery makes AJAX extremely simple and takes care of the background work of creating the xmlhttp object, making the call and giving you back the result. In the below example, I created a simple autocomplete textbox that makes the suggestions dynamically based on what you type. This would have taken atleast 150 lines if written in plain-ol javascript.</li>
</ul>
<p><strong>HTML Code</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;span&gt;Enter Country Name&lt;/span&gt;&lt;br /&gt;
&lt;input type=&quot;text&quot; id=&quot;txtCountry&quot; style=&quot;width:250px&quot; /&gt;&lt;br /&gt;
&lt;span id=&quot;autoList&quot; style=&quot;width:250px;display:block&quot; /&gt;</pre></td></tr></table></div>

<p><strong>Javascript code</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</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: #006600; font-style: italic;">//Hooking the event handler to the keyup function</span>
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#txtCountry'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">keyup</span><span style="color: #009900;">&#40;</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: #006600; font-style: italic;">//Only call AJAX function if atleast 3 characters are there</span>
        $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#autoList'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#txtCountry'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">length</span> <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            $.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span> <span style="color: #006600; font-style: italic;">//Jquery AJAX api</span>
        <span style="color: #009900;">&#123;</span>
        url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;GetCountriesSuggestion.aspx&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #006600; font-style: italic;">//Send in data as a query string</span>
        data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;country=&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#txtCountry'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
        cache<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">,</span>
        async<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">,</span> <span style="color: #006600; font-style: italic;">//Make an asynchronous req</span>
        datatype<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;xml&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #006600; font-style: italic;">//This is a callback function</span>
        success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>xml<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#autoList'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#40;</span>xml<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Country'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">length</span> <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #003366; font-weight: bold;">var</span> ul <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'&lt;ul&gt;&lt;/ul'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #006600; font-style: italic;">//Creating a border and removing the bullets</span>
                <span style="color: #006600; font-style: italic;">//that appear in an unordered list by default</span>
                ul.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'border'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'solid 1px black'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'list-style'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'none'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                ul.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'left'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'0px'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #006600; font-style: italic;">//Find the country element and iterate</span>
                <span style="color: #006600; font-style: italic;">//through each element</span>
                $<span style="color: #009900;">&#40;</span>xml<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Country'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</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: #006600; font-style: italic;">//Creating a list item element and hooking up</span>
                    <span style="color: #006600; font-style: italic;">//its click handler</span>
                    <span style="color: #003366; font-weight: bold;">var</span> li <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'&lt;li&gt;'</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">text</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&lt;/li&gt;'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'cursor'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'pointer'</span><span style="color: #009900;">&#41;</span>
                    li.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'left'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'0px'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    li.<span style="color: #660066;">hover</span><span style="color: #009900;">&#40;</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: #006600; font-style: italic;">//This changes the color and background color</span>
                        <span style="color: #006600; font-style: italic;">//of the suggestion box when the mouse is taken over it</span>
                        <span style="color: #006600; font-style: italic;">//The hover method takes in two functions- one invoked on</span>
                        <span style="color: #006600; font-style: italic;">//mouseover and one on mouseout</span>
                        $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'color'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'#FFFFFF'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'background-color'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'#0000FF'</span><span style="color: #009900;">&#41;</span>
                    <span style="color: #009900;">&#125;</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: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'color'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'#000000'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'background-color'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'#FFFFFF'</span><span style="color: #009900;">&#41;</span>
                    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    li.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</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: #006600; font-style: italic;">//Set the clicked item to textbox text and empty the</span>
                        <span style="color: #006600; font-style: italic;">//Collecttion list</span>
                        $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#txtCountry'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">text</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#autoList'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    ul.<span style="color: #660066;">append</span><span style="color: #009900;">&#40;</span>li<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#autoList'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">append</span><span style="color: #009900;">&#40;</span>ul<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>ASP.NET Code Behind in C# </strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Page_Load<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>Request.<span style="color: #0000FF;">QueryString</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;country&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                Response.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>GetCountriesList<span style="color: #000000;">&#40;</span>Request.<span style="color: #0000FF;">QueryString</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;country&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> GetCountriesList<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> countryName<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//creating a string builder object</span>
            StringBuilder _response <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            XmlDocument _xDoc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlDocument<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Load the xml file with all the countries</span>
            _xDoc.<span style="color: #0000FF;">Load</span><span style="color: #000000;">&#40;</span>Server.<span style="color: #0000FF;">MapPath</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Countries.xml&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Get all country names in the xml file</span>
            XmlNodeList _allCountries <span style="color: #008000;">=</span> _xDoc.<span style="color: #0000FF;">GetElementsByTagName</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Entry&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Writing out xml declaration and root tag</span>
            _response.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;&lt;?xml version=<span style="color: #008080; font-weight: bold;">\&quot;</span>1.0<span style="color: #008080; font-weight: bold;">\&quot;</span> encoding=<span style="color: #008080; font-weight: bold;">\&quot;</span>ISO-8859-1<span style="color: #008080; font-weight: bold;">\&quot;</span> standalone=<span style="color: #008080; font-weight: bold;">\&quot;</span>yes<span style="color: #008080; font-weight: bold;">\&quot;</span>?&gt;&lt;Countries&gt;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Iterating through each country</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>XmlNode _country <span style="color: #0600FF;">in</span> _allCountries<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//If what user entered matches the country name,</span>
                <span style="color: #008080; font-style: italic;">//create a dynamic xml node and append</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>countryName.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">&lt;=</span> _country.<span style="color: #0000FF;">FirstChild</span>.<span style="color: #0000FF;">InnerText</span>.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span><span style="color: #000000;">&#40;</span> countryName.<span style="color: #0000FF;">ToUpper</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Equals</span><span style="color: #000000;">&#40;</span>_country.<span style="color: #0000FF;">FirstChild</span>.<span style="color: #0000FF;">InnerText</span>.<span style="color: #0000FF;">Substring</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span>, countryName.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    _response.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;&lt;Country&gt;&quot;</span> <span style="color: #008000;">+</span> _country.<span style="color: #0000FF;">FirstChild</span>.<span style="color: #0000FF;">InnerText</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;&lt;/Country&gt;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #008080; font-style: italic;">//Append closing root tag</span>
            <span style="color: #0600FF;">return</span> _response.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;&lt;Countries&gt;&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/04/jquery-the-javascript-magic-bullet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My first look at the dynamic keyword in C# 4.0</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/03/my-first-look-at-the-dynamic-keyword-in-c-4-0/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/03/my-first-look-at-the-dynamic-keyword-in-c-4-0/#comments</comments>
		<pubDate>Thu, 11 Mar 2010 20:17:59 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[DLR]]></category>
		<category><![CDATA[dynamic typing]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=1023</guid>
		<description><![CDATA[<p style="text-align: justify;">I have always believed that strong typing is the holy grail of .NET, which is not to be messed with, and it has been my primary grouse with VB.NET is that it uses sneaky workarounds to circumvent the typing rules of the CLR. C# for most of its initial existence followed static typing [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">I have always believed that strong typing is the holy grail of .NET, which is not to be messed with, and it has been my primary grouse with VB.NET is that it uses sneaky workarounds to circumvent the typing rules of the CLR. C# for most of its initial existence followed static typing religiously with slight changes being seen in 3.0 with the var keyword. But in 4.0, everything changed with the introduction of the Dynamic Language Runtime (DLR).</p>
<p style="text-align: justify;">The DLR according to wikipedia is <em><strong>&#8220;an ongoing effort to bring a set of services that run on top of the Common Language Runtime (CLR) and provides language services for several different dynamic languages.&#8221;</strong></em> As the definition says, it is independent of the CLR and adds no new OpCodes to the IL. Languages like C# used the DLR to introduce dynamic typing while maintaining the existing mechanism of statically determining types.</p>
<p style="text-align: justify;">The dynamic keyword is the C# construct introduced for this. In short &#8211; it tells the compiler that the call to this method is to be resolved at runtime and not to be bothered by throwing compiler errors. Lets see a simple example for the usage of the dynamic keyword. Suppose you have a book class which has four main properties &#8211; Author, Publisher, Price and Number Of Pages. However, each book may have a lot of other properties as well, which you wont know at design time. So the question arises, how to store the additional information? The first answer that would come to mind is storing them in a collection class and later retrieving it. The dynamic class provides you with a neat way of doing this shown in the code below :-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// The dynamic keyword bypasses any compile time checking for this object</span>
            dynamic _daVinciCode <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Book<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Sample Author&quot;</span>, <span style="color: #666666;">&quot;SomePublisher&quot;</span>, <span style="color: #FF0000;">250</span>, <span style="color: #FF0000;">450</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">/*** EXTRA PROPERTIES - NOT PRESENT IN THE OBJECT***/</span>
            _daVinciCode.<span style="color: #0000FF;">BookStores</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;Landmark&quot;</span>, <span style="color: #666666;">&quot;Oddyssey&quot;</span>, <span style="color: #666666;">&quot;Crosswords&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
            _daVinciCode.<span style="color: #0000FF;">CitiesAvailable</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;Delhi&quot;</span>, <span style="color: #666666;">&quot;Bangalore&quot;</span>, <span style="color: #666666;">&quot;Chennai&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
            _daVinciCode.<span style="color: #0000FF;">ExtraVat</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">45</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">/*** PRINTING OUT EXTRA PROPERTIES VALUE ***/</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>_daVinciCode.<span style="color: #0000FF;">ExtraVat</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// This is our dynamic class. It defines 4 concrete properties</span>
    <span style="color: #008080; font-style: italic;">/// and a dictionary class for storing any other property values</span>
    <span style="color: #008080; font-style: italic;">/// as well. The abstract class DynamicObject is implemented</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Book<span style="color: #008000;">:</span>DynamicObject
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Our four defined properties</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Author <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Publisher <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">double</span> Price <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> NumberOfPages <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//Constructor - Parametrized</span>
        <span style="color: #0600FF;">public</span> Book<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _author, <span style="color: #FF0000;">string</span> _publisher, <span style="color: #FF0000;">double</span> _price, <span style="color: #FF0000;">int</span> _numberOfPages<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Author</span> <span style="color: #008000;">=</span> _author<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Publisher</span> <span style="color: #008000;">=</span> _publisher<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Price</span> <span style="color: #008000;">=</span> _price<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">NumberOfPages</span> <span style="color: #008000;">=</span> _numberOfPages<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//This collection object stores all the extra properties</span>
        <span style="color: #0600FF;">public</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> _extraProperties <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//At runtime this method is called in order to bind the propertyname to a Getter</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">bool</span> TryGetMember<span style="color: #000000;">&#40;</span>GetMemberBinder binder, <span style="color: #0600FF;">out</span> <span style="color: #FF0000;">object</span> result<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> _extraProperties.<span style="color: #0000FF;">TryGetValue</span><span style="color: #000000;">&#40;</span>binder.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">ToLower</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #0600FF;">out</span> result<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//At runtime this method is called in order to bind the propertyname to a setter</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">bool</span> TrySetMember<span style="color: #000000;">&#40;</span>SetMemberBinder binder, <span style="color: #FF0000;">object</span> value<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _extraProperties.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>binder.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">ToLower</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The Book class is a dynamic type and derives from the abstract class DynamicObject. This base class can help determine how binding should occur at runtime. In our example, the dictionary object stores all the additional properties of the book class. The two overriden methods TryGetMember and the TrySetMember are responsible for the binding of the new properties to the dictionary object. The first time a property on a dynamic type is encountered, the DLR binds the property and then caches its address. So any subsequent calls are faster.</p>
<p>More on the DLR in future posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/03/my-first-look-at-the-dynamic-keyword-in-c-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Blogging: Length v/s Popularity</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/03/blogging-length-vs-popularity/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/03/blogging-length-vs-popularity/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 19:36:07 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[Blogging]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=1010</guid>
		<description><![CDATA[<p style="text-align: justify;">I have always believed that when it comes to blogging, brevity is soul and its very important to convey your idea in as less words as possible. Of course with technical blogs its an altogether different ball game with most of the visitors coming through search engines and looking for specific topics, where [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">I have always believed that when it comes to blogging, brevity is soul and its very important to convey your idea in as less words as possible. Of course with technical blogs its an altogether different ball game with most of the visitors coming through search engines and looking for specific topics, where you can be afford to be verbose. But with a mixed audience and a variety of blog subjects, it is extremely important to keep it as short and simple as possible to ensure maximum reach.</p>
<p style="text-align: justify;">To prove this point, I set out to find if there is a relation between the length of each post and the comments it receives. Though, the number of comments is not the best yardstick to measure the popularity of the post, it certainly is the most concrete one. The best place to try this out seemed to be my organization&#8217;s internal blogosphere, which had a lot of sample data (3500+ posts). Since its impossible to manually collect data for that many posts, I wrote a program to write it to a text file from where any correlation could be identified. Its a mixture of retrieving the data through HTML and RSS and parsing it. Though it should be compatible with any WordPress version, the comment counting function might need some tweaking to make it work on later versions. Once the code finishes executing, you would have a text file with the name of each post, the length and the number of comments. The data in this file can be imported into Excel for further manipulation.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Xml</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Net</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text.RegularExpressions</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Windows.Forms</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> TestRSS
<span style="color: #000000;">&#123;</span>
    StreamWriter _swObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamWriter<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Results.txt&quot;</span>, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> _feedURL <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;http://blog.ganeshzone.net&quot;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008000;">new</span>  TestRSS<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">RunTests</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> RunTests<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> <span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">//This is an infinite loop only to be broken when there are no more posts</span>
        <span style="color: #000000;">&#123;</span>
            XmlDocument _xdoc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlDocument<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//a New XmlDocument object</span>
            <span style="color: #008080; font-style: italic;">//Lets load the XML from the url</span>
            _xdoc.<span style="color: #0000FF;">LoadXml</span><span style="color: #000000;">&#40;</span>GetXmlData<span style="color: #000000;">&#40;</span>_feedURL <span style="color: #008000;">+</span> <span style="color: #000000;">&#40;</span>i<span style="color: #008000;">&gt;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">?</span><span style="color: #666666;">&quot;?paged=&quot;</span> <span style="color: #008000;">+</span> i<span style="color: #008000;">+</span><span style="color: #666666;">&quot;&amp;&quot;</span><span style="color: #008000;">:</span><span style="color: #666666;">&quot;?&quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">+</span><span style="color: #666666;">&quot;feed=rss2&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            XmlNodeList _xList <span style="color: #008000;">=</span> _xdoc.<span style="color: #0000FF;">GetElementsByTagName</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;item&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_xList.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
                break<span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//This means there are no more blog posts</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>XmlNode _tempNode <span style="color: #0600FF;">in</span> _xList<span style="color: #000000;">&#41;</span>
                <span style="color: #008080; font-style: italic;">//This method writes the name of post, length and the number of comments delimited by a colon</span>
                <span style="color: #008080; font-style: italic;">//So we need to remove the colon in case of any being present/</span>
                <span style="color: #008080; font-style: italic;">//Example Data: - ASP.NET Evolution WebForms v/s MVC: 6060:0</span>
                WriteToFile<span style="color: #000000;">&#40;</span>_tempNode.<span style="color: #0000FF;">FirstChild</span>.<span style="color: #0000FF;">InnerText</span>.<span style="color: #0000FF;">Replace</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;:&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;: &quot;</span> <span style="color: #008000;">+</span> _tempNode.<span style="color: #0000FF;">SelectSingleNode</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;description&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NextSibling</span>.<span style="color: #0000FF;">InnerText</span>.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;:&quot;</span> <span style="color: #008000;">+</span> GetComments<span style="color: #000000;">&#40;</span>_tempNode.<span style="color: #0000FF;">FirstChild</span>.<span style="color: #0000FF;">NextSibling</span>.<span style="color: #0000FF;">InnerText</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetXmlData<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _url<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//An ordinary retrieval of data from the url using the HttpWebRequest</span>
        <span style="color: #008080; font-style: italic;">//This is a workaround for sites with badly formed RSS feeds due to script tags.</span>
        <span style="color: #008080; font-style: italic;">//Once we get the data, we can load it into an XmlDocument class</span>
        HttpWebRequest _blogReq <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>HttpWebRequest<span style="color: #000000;">&#41;</span>WebRequest.<span style="color: #0000FF;">Create</span><span style="color: #000000;">&#40;</span>_url<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        HttpWebResponse _blogResp <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>HttpWebResponse<span style="color: #000000;">&#41;</span>_blogReq.<span style="color: #0000FF;">GetResponse</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        StreamReader _respStream <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamReader<span style="color: #000000;">&#40;</span>_blogResp.<span style="color: #0000FF;">GetResponseStream</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008080; font-style: italic;">//Replace Script tags</span>
        <span style="color: #0600FF;">return</span> Regex.<span style="color: #0000FF;">Replace</span><span style="color: #000000;">&#40;</span>_respStream.<span style="color: #0000FF;">ReadToEnd</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #666666;">@&quot;&lt;script[^&gt;]*?&gt;[\s\S]*?&lt;\/script&gt;&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> GetComments<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _url<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Retrieving the Comments from the HTML and not the RSS feed. I wasnt able</span>
        <span style="color: #008080; font-style: italic;">//to find a workaround for 10 comment limit in the RSS feed in wordpress 2.3,</span>
        <span style="color: #008080; font-style: italic;">//Hence retriving the HTML and matching the comment divs. Keep in mind this wont work</span>
        <span style="color: #008080; font-style: italic;">//for higher Wordpress versions. Just take the comment tag and substitute accordingly</span>
        Match _match <span style="color: #008000;">=</span> Regex.<span style="color: #0000FF;">Match</span><span style="color: #000000;">&#40;</span>GetXmlData<span style="color: #000000;">&#40;</span>_url<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;&lt;div class=<span style="color: #008080; font-weight: bold;">\&quot;</span>mycomment<span style="color: #008080; font-weight: bold;">\&quot;</span>[^&gt;]*?&gt;[<span style="color: #008080; font-weight: bold;">\\</span>s<span style="color: #008080; font-weight: bold;">\\</span>S]*?&lt;<span style="color: #008080; font-weight: bold;">\\</span>/div&gt;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> _counter<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">;</span> _match.<span style="color: #0000FF;">Success</span><span style="color: #008000;">;</span> _counter<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            _match <span style="color: #008000;">=</span> _match.<span style="color: #0000FF;">NextMatch</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> _counter<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> WriteToFile<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _tobeWritten<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Just write it to the file</span>
        _swObj.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>_tobeWritten<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _swObj.<span style="color: #0000FF;">Flush</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/03/blogging-length-vs-popularity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lifting the .NET Hood &#8211; Part 1 &#8211; Generics</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/03/lifting-the-net-hood-part-1-generics/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/03/lifting-the-net-hood-part-1-generics/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 21:33:39 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[Generics]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=966</guid>
		<description><![CDATA[<p style="text-align: justify;">I have started this series of posts dedicated to exploring the internals of the .NET framework and runtime. To get started on probing of internals of .NET, we need a debugging extension called SOS (Sons of Strike). Visual Studio comes packaged with this assembly (SOS.dll). The first posts is about one of the [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">I have started this series of posts dedicated to exploring the internals of the .NET framework and runtime. To get started on probing of internals of .NET, we need a debugging extension called SOS (Sons of Strike). Visual Studio comes packaged with this assembly (SOS.dll). The first posts is about one of the most important features of .NET 2.0 over 1.1 &#8211; Generics or &#8220;Parametric Polymorphism&#8221;. Wikipedia defines Generics as <em>&#8220;a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters&#8221;</em>.</p>
<p style="text-align: justify;">First, we need to set up Visual studio  to use the Sons of Strike. A few simple steps mentioned below are needed to accomplish this:-</p>
<ul>
<li>Enable Unmanaged Debugging in the Project Properties</li>
</ul>
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/03/unmanaged.jpg"><img class="aligncenter size-medium wp-image-967" title="unmanaged" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/03/unmanaged-300x183.jpg" alt="" width="300" height="183" /></a></p>
<ul>
<li style="text-align: justify;">Set the symbol server to  <strong>*C:\localcache*http://msdl.microsoft.com/download/symbols</strong>. The symbol server can be set by going to Tools -&gt; Options-&gt; Debugging. This step allows Visual studio to download the symbols needed for debugging from the Microsoft server.</li>
</ul>
<ul>
<li style="text-align: justify;">Set a breakpoint in the code and press F5 to start the program in debug mode. Once the application hits the breakpoint, load the SOS.dll using the command <strong>.load SOS </strong>in the Immediate Window.</li>
</ul>
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/03/loadDLL.jpg"><img class="aligncenter size-full wp-image-971" title="loadDLL" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2010/03/loadDLL.jpg" alt="" width="525" height="71" /></a></p>
<p style="text-align: justify;">Now we are ready to use the debugging extension. And SOS is also compatible with debugging tools like WinDbg in case you are comfortable with using that. Click <a href="http://geekswithblogs.net/.netonmymind/archive/2006/03/14/72262.aspx" target="_blank">here</a> for a list of SOS commands.</p>
<p style="text-align: justify;">Now, lets see the code that we would use for seeing how generics work. It consists of a Generic Type Customer which contains a list of the generic type and a public integer property.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">class</span> Employee
    <span style="color: #000000;">&#123;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> EmployeeID<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">int</span> age<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #FF0000;">class</span> Customer<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> CustomerID<span style="color: #008000;">;</span>
        List<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> _innerList <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> ListItems <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _innerList<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddItems<span style="color: #000000;">&#40;</span>T _addObject<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _innerList.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_addObject<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">The main method to call this code is below. We create the Customer class in three types &#8211; a string, an integer and a custom Employee type. Of these the string and Employee are reference types while integer is a primitive value type.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Customer<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> _cxStringObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Customer<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Customer<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span> _cxIntObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Customer<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Customer<span style="color: #008000;">&lt;</span>Employee<span style="color: #008000;">&gt;</span> _cxEmpObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Customer<span style="color: #008000;">&lt;</span>Employee<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            _cxStringObj.<span style="color: #0000FF;">CustomerID</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">34</span><span style="color: #008000;">;</span>
            _cxStringObj.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Ganesh&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            _cxIntObj.<span style="color: #0000FF;">CustomerID</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">23</span><span style="color: #008000;">;</span>
            _cxIntObj.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">43</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            _cxEmpObj.<span style="color: #0000FF;">CustomerID</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">34</span><span style="color: #008000;">;</span>
            _cxEmpObj.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Employee<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Every .NET class has two main data structures it uses to maintain type identity  &#8211; the MethodTable and EEClass. Every object has a pointer to its MethodTable, and this methodtable contains a pointer to the EEClass. In .NET 1.1, the EE class was the strongest identifier of Type Identity of an object, however with .NET 2.0 and the implementation of Generics, Generic Types can share the same EEClass, and the MethodTable takes on the mantle of being the unique type identifier.</p>
<p style="text-align: justify;">There are two main ways of implementing Generics which were proposed by the researchers who were working at Microsoft (<a href="http://research.microsoft.com/en-us/um/people/akenn/generics/DesignAndImplementationOfGenerics.pdf">This</a> paper provides details of the implementation).</p>
<ul>
<li style="text-align: justify;">Expansion: In this way, whenever the runtime encounters a generic type, the code could be generated on the fly for the type being called. For e.g. in our code, when the object Customer&lt;string&gt; was encountered, it could have expanded into the string representation of the object. When the type Customer&lt;int&gt; was encountered, a similar expansion can be done for it.</li>
</ul>
<ul>
<li style="text-align: justify;">Code sharing: In this approach only a single instantiation is done for the generic type, and it is reused for all the calls.</li>
</ul>
<p style="text-align: justify;">The method chosen in the end was a mixture of both these approaches. Generic types share as much code as possible They contain the same EEClass as mentioned before, but also have distinct MethodTables. Even though they have distinct MethodTables, code is shared between compatible types (all reference types).</p>
<p style="text-align: justify;">Fire up the debugger and load the SOS.dll. To see the particular instances of the type on the heap give the Command DumpHeap -type . Once all the three objects have been created, lets see the result of this command.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">!</span>DumpHeap <span style="color: #008000;">-</span>type Customer
 Address       MT     Size
01ed35cc 002331d8       <span style="color: #FF0000;">16</span>
01ed3604 00233284       <span style="color: #FF0000;">16</span>
01ed3638 0023336c       <span style="color: #FF0000;">16</span>
total <span style="color: #FF0000;">3</span> objects
Statistics<span style="color: #008000;">:</span>
      MT    Count    TotalSize <span style="color: #FF0000;">Class</span> Name
0023336c        <span style="color: #FF0000;">1</span>           <span style="color: #FF0000;">16</span> GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span>GenericsTry.<span style="color: #0000FF;">Employee</span>, GenericsTry<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
00233284        <span style="color: #FF0000;">1</span>           <span style="color: #FF0000;">16</span> GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Int32</span>, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
002331d8        <span style="color: #FF0000;">1</span>           <span style="color: #FF0000;">16</span> GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.<span style="color: #FF0000;">String</span>, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
Total <span style="color: #FF0000;">3</span> objects</pre></div></div>

<p style="text-align: justify;">As you can see from the MT column, all the three objects have different MethodTables. Lets see the MethodTables for each of the three type instantiations.</p>
<p style="text-align: justify;">The command is DumpMT -MD . First the Employee type. Think of the MethodTable as an extension to a conventional vtable which simply contains the method pointers. The MethodTable&#8217;s vtable points to 7 slots, 4 of which are inherited from the parent Object class and three which are defined by the object itself. If you see the JIT status, there is a YES and NONE. The NONE means the method has never been called by the JIT Compiler and it points to a temporary stub. The first time the method is called, it is compiled on the fly and the temporary stub is replaced with the actual method pointer. To optimize performance, JIT defers execution and compilation till as late as possible.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">!</span>DumpMT <span style="color: #008000;">-</span>MD 0023336c
EEClass<span style="color: #008000;">:</span> 00231420
Module<span style="color: #008000;">:</span> 00232c5c
Name<span style="color: #008000;">:</span> GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span>GenericsTry.<span style="color: #0000FF;">Employee</span>, GenericsTry<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
mdToken<span style="color: #008000;">:</span> 02000004  <span style="color: #000000;">&#40;</span>Projects\GenericsTry\GenericsTry\bin\Debug\GenericsTry.<span style="color: #0000FF;">exe</span><span style="color: #000000;">&#41;</span>
BaseSize<span style="color: #008000;">:</span> 0x10
ComponentSize<span style="color: #008000;">:</span> 0x0
Number of IFaces <span style="color: #0600FF;">in</span> IFaceMap<span style="color: #008000;">:</span> <span style="color: #FF0000;">0</span>
Slots <span style="color: #0600FF;">in</span> VTable<span style="color: #008000;">:</span> <span style="color: #FF0000;">7</span>
<span style="color: #008000;">--------------------------------------</span>
MethodDesc Table
   Entry MethodDesc      JIT Name
70766aa0   705e4a34   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
70766ac0   705e4a3c   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">Equals</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span><span style="color: #000000;">&#41;</span>
70766b30   705e4a6c   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">GetHashCode</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
707d7550   705e4a90   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">Finalize</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
0023c058   0023313c     NONE GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">get_ListItems</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
0023c060   00233148     NONE GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.__Canon<span style="color: #000000;">&#41;</span>
0023c068   00233154      JIT GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>..<span style="color: #0000FF;">ctor</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p style="text-align: justify;">Lets see the MethodTable for the integer type. As you can see the EEClass for the Integer and Employee types are not same, this is because they are not compatible types and hence no code sharing can take place</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">!</span>DumpMT <span style="color: #008000;">-</span>MD 00233284
EEClass<span style="color: #008000;">:</span> 002314b4
Module<span style="color: #008000;">:</span> 00232c5c
Name<span style="color: #008000;">:</span> GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Int32</span>, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
mdToken<span style="color: #008000;">:</span> 02000004  <span style="color: #000000;">&#40;</span>\GenericsTry\GenericsTry\bin\Debug\GenericsTry.<span style="color: #0000FF;">exe</span><span style="color: #000000;">&#41;</span>
BaseSize<span style="color: #008000;">:</span> 0x10
ComponentSize<span style="color: #008000;">:</span> 0x0
Number of IFaces <span style="color: #0600FF;">in</span> IFaceMap<span style="color: #008000;">:</span> <span style="color: #FF0000;">0</span>
Slots <span style="color: #0600FF;">in</span> VTable<span style="color: #008000;">:</span> <span style="color: #FF0000;">7</span>
<span style="color: #008000;">--------------------------------------</span>
MethodDesc Table
   Entry MethodDesc      JIT Name
70766aa0   705e4a34   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
70766ac0   705e4a3c   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">Equals</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span><span style="color: #000000;">&#41;</span>
70766b30   705e4a6c   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">GetHashCode</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
707d7550   705e4a90   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">Finalize</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
0023c080   00233254     NONE GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Int32</span>, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">get_ListItems</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
0023c088   00233260     NONE GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Int32</span>, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span>Int32<span style="color: #000000;">&#41;</span>
0023c090   0023326c      JIT GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Int32</span>, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>..<span style="color: #0000FF;">ctor</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p style="text-align: justify;">The last one is the string type. This brings us to interesting conclusions. Compare the first MethodTable with the last one. Both are reference types and hence compatible with other. It can be observed that the string and Employee tables have the same EEClass <strong>00231420</strong>. The integer type however has the EEClass <strong>002314b4</strong>. There is no way for primitive value types to share code with each other since they differ in size. For e.g. If we created a bool type for Customer class, it would still have a different EEClass and MethodTables.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">!</span>DumpMT <span style="color: #008000;">-</span>MD 002331d8
EEClass<span style="color: #008000;">:</span> 00231420
Module<span style="color: #008000;">:</span> 00232c5c
Name<span style="color: #008000;">:</span> GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.<span style="color: #FF0000;">String</span>, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
mdToken<span style="color: #008000;">:</span> 02000004  <span style="color: #000000;">&#40;</span>\GenericsTry\GenericsTry\bin\Debug\GenericsTry.<span style="color: #0000FF;">exe</span><span style="color: #000000;">&#41;</span>
BaseSize<span style="color: #008000;">:</span> 0x10
ComponentSize<span style="color: #008000;">:</span> 0x0
Number of IFaces <span style="color: #0600FF;">in</span> IFaceMap<span style="color: #008000;">:</span> <span style="color: #FF0000;">0</span>
Slots <span style="color: #0600FF;">in</span> VTable<span style="color: #008000;">:</span> <span style="color: #FF0000;">7</span>
<span style="color: #008000;">--------------------------------------</span>
MethodDesc Table
   Entry MethodDesc      JIT Name
70766aa0   705e4a34   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
70766ac0   705e4a3c   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">Equals</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span><span style="color: #000000;">&#41;</span>
70766b30   705e4a6c   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">GetHashCode</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
707d7550   705e4a90   PreJIT <span style="color: #000000;">System</span>.<span style="color: #FF0000;">Object</span>.<span style="color: #0000FF;">Finalize</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
0023c058   0023313c     NONE GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">get_ListItems</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
0023c060   00233148     NONE GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.__Canon<span style="color: #000000;">&#41;</span>
0023c068   00233154      JIT GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>..<span style="color: #0000FF;">ctor</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p style="text-align: justify;">One more thing of notice is the Method Descriptors for the first and third types. The AddItems method in Customer class has the same Method descriptor for both the string and Employee implementation. So even after a MethodTable is duplicated, both those entries still point to the same Method Description. Even the name has the type System.__Canon, which is dynamically replaced by the type on which the method is called. This is an illustration of the second approach of code sharing given by the researchers from Microsoft.</p>
<p style="text-align: justify;">Once the code for AddItems method is called for the first time, it is JIT Compiled and assigned a code address. The Method Descriptor holds this code address which is assembly code and can be viewed by the SOS command !u.  Till the method is Jitted, there is junk value in this field on the MethodDescriptor.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">!</span>DumpMD 00233148
Method Name<span style="color: #008000;">:</span> GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.__Canon<span style="color: #000000;">&#41;</span>
<span style="color: #FF0000;">Class</span><span style="color: #008000;">:</span> 00231420
MethodTable<span style="color: #008000;">:</span> 0023316c
mdToken<span style="color: #008000;">:</span> 06000005
Module<span style="color: #008000;">:</span> 00232c5c
IsJitted<span style="color: #008000;">:</span> yes
CodeAddr<span style="color: #008000;">:</span> 00aa0298</pre></div></div>

<p>Running the CodeAddress would give you a bunch of assembly code that is executed when the method is called.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">!</span>u 00aa0298
Normal JIT generated code
GenericsTry.<span style="color: #0000FF;">Customer</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">AddItems</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.__Canon<span style="color: #000000;">&#41;</span>
Begin 00aa0298, size <span style="color: #FF0000;">42</span>
<span style="color: #008000;">&gt;&gt;&gt;</span> 00AA0298 <span style="color: #FF0000;">55</span>               push        ebp
00AA0299 8BEC             mov         ebp,esp
00AA029B <span style="color: #FF0000;">57</span>               push        edi
00AA029C <span style="color: #FF0000;">56</span>               push        esi
00AA029D <span style="color: #FF0000;">53</span>               push        ebx
00AA029E 83EC34           sub         esp,34h
00AA02A1 33C0             xor         eax,eax
00AA02A3 8945F0           mov         dword ptr <span style="color: #000000;">&#91;</span>ebp<span style="color: #008000;">-</span>10h<span style="color: #000000;">&#93;</span>,eax
00AA02A6 33C0             xor         eax,eax
00AA02A8 8945E4           mov         dword ptr <span style="color: #000000;">&#91;</span>ebp<span style="color: #008000;">-</span>1Ch<span style="color: #000000;">&#93;</span>,eax
00AA02AB 894DC4           mov         dword ptr <span style="color: #000000;">&#91;</span>ebp<span style="color: #008000;">-</span>3Ch<span style="color: #000000;">&#93;</span>,ecx
00AA02AE 8955C0           mov         dword ptr <span style="color: #000000;">&#91;</span>ebp<span style="color: #008000;">-</span>40h<span style="color: #000000;">&#93;</span>,edx
00AA02B1 833D142E230000   cmp         dword ptr ds<span style="color: #008000;">:</span><span style="color: #000000;">&#91;</span>00232E14h<span style="color: #000000;">&#93;</span>,<span style="color: #FF0000;">0</span>
00AA02B8 <span style="color: #FF0000;">7405</span>             je          00AA02BF
00AA02BA E8BABC3571       call        71DFBF79 <span style="color: #000000;">&#40;</span>JitHelp<span style="color: #008000;">:</span> CORINFO_HELP_DBG_IS_JUST_MY_CODE<span style="color: #000000;">&#41;</span>
00AA02BF <span style="color: #FF0000;">90</span>               nop
00AA02C0 8B45C4           mov         eax,dword ptr <span style="color: #000000;">&#91;</span>ebp<span style="color: #008000;">-</span>3Ch<span style="color: #000000;">&#93;</span>
00AA02C3 8B4804           mov         ecx,dword ptr <span style="color: #000000;">&#91;</span>eax<span style="color: #008000;">+</span><span style="color: #FF0000;">4</span><span style="color: #000000;">&#93;</span>
00AA02C6 8B55C0           mov         edx,dword ptr <span style="color: #000000;">&#91;</span>ebp<span style="color: #008000;">-</span>40h<span style="color: #000000;">&#93;</span>
00AA02C9 <span style="color: #FF0000;">3909</span>             cmp         dword ptr <span style="color: #000000;">&#91;</span>ecx<span style="color: #000000;">&#93;</span>,ecx
00AA02CB E8E0F1D16F       call        707BF4B0 <span style="color: #000000;">&#40;</span><span style="color: #000000;">System.<span style="color: #0000FF;">Collections</span></span>.<span style="color: #0000FF;">Generic</span>.<span style="color: #0000FF;">List</span>`<span style="color: #FF0000;">1</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">System</span>.__Canon, mscorlib<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.__Canon<span style="color: #000000;">&#41;</span>, mdToken<span style="color: #008000;">:</span> 060019f1<span style="color: #000000;">&#41;</span>
00AA02D0 <span style="color: #FF0000;">90</span>               nop
00AA02D1 <span style="color: #FF0000;">90</span>               nop
00AA02D2 8D65F4           lea         esp,<span style="color: #000000;">&#91;</span>ebp<span style="color: #008000;">-</span>0Ch<span style="color: #000000;">&#93;</span>
00AA02D5 5B               pop         ebx
00AA02D6 5E               pop         esi
00AA02D7 5F               pop         edi
00AA02D8 5D               pop         ebp
00AA02D9 C3               ret</pre></div></div>

<p>In this post, we have looked at how the CLR treats Generics and how it takes care of performance implications of Generics code by sharing as much code as possible without having to needlessly box and unbox the types being passed to the Generic classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/03/lifting-the-net-hood-part-1-generics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Generic Binary Search Tree in C# .NET</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/02/generic-binary-search-tree-in-c-net/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/02/generic-binary-search-tree-in-c-net/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 13:33:19 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Data structures]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=895</guid>
		<description><![CDATA[<p style="text-align: justify;">Binary Trees are tree type data structures that contain two child nodes. They can be used to implement Binary Search trees, structures where the left child has a value lesser than the node and the right child has a greater value. Usually Linear collection objects require iteration linearly over the list. In the [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Binary Trees are tree type data structures that contain two child nodes. They can be used to implement Binary Search trees, structures where the left child has a value lesser than the node and the right child has a greater value. Usually Linear collection objects require iteration linearly over the list. In the worst case scenario that the element to be searched is at the end of the list this can take a really really long time. For Binary Trees the search time is cut by half. Since every node tells the search which direction to go and search.</p>
<p style="text-align: justify;">I implemented a basic Binary Tree in .NET for adding custom types. The Tree is generic and can be used to add any type objects. Also the object must implement the generic versions of IComparable and IEquitable for their types and object types. This leaves the search logic&#8217;s implementation to the type rather than the data structure. The complete solution can be downloaded <a href="http://www.ganeshzone.net/Files/BinaryTry.zip">here</a>.</p>
<p>Lets see the declaration of the Binary Tree along with the private members.</p>
<pre class="code"><span style="color: blue;">class </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; <span style="color: blue;">where
    </span>T:<span style="color: #2b91af;">IComparable</span>&lt;T&gt;,
    <span style="color: #2b91af;">IEquatable</span>&lt;T&gt;,
    <span style="color: #2b91af;">IEquatable</span>&lt;<span style="color: blue;">object</span>&gt;,
    <span style="color: #2b91af;">IComparable</span>&lt;<span style="color: blue;">object</span>&gt;
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _parentNode;
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _leftNode;
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _rightNode;
    <span style="color: blue;">public </span>T Value { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }</pre>
<p style="text-align: justify;">Each BinaryTree object must be aware of its parent node and its left and right children, and the value it holds.  Lets see the logic for adding the node. The adding logic is recursive. If it finds a null value, then the value is substituted. If not, then the node to be added is compared. If the value is lesser than the same method is called on the leftnode. This happens recursively till we get the node where the value is to be added.</p>
<pre class="code"><span style="color: blue;">public void </span>AddNode(T _nodeTobeAdded)
{
    <span style="color: blue;">if </span>(<span style="color: blue;">null</span>==Value)
        <span style="color: green;">//We found the value. Yay!!
        </span><span style="color: blue;">this</span>.Value = _nodeTobeAdded;
    <span style="color: blue;">else
    </span>{
        <span style="color: green;">//Compare the node to be added. Here the
        //type's IComparable is called.
        </span><span style="color: blue;">if </span>(_nodeTobeAdded.CompareTo(Value) &lt; 0)
        {
            <span style="color: green;">//Go down the left node. If the left node is null,
            //then create a new object, else return the existing object.
            </span>_leftNode = <span style="color: blue;">null</span>==_leftNode ?<span style="color: blue;">new </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;(<span style="color: blue;">this</span>):_leftNode;
            _leftNode.AddNode(_nodeTobeAdded);
        }
        <span style="color: blue;">else
        </span>{
            <span style="color: green;">//Go Down the right node.
            </span>_rightNode = <span style="color: blue;">null</span>==_rightNode?<span style="color: blue;">new </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;(<span style="color: blue;">this</span>):_rightNode;
            _rightNode.AddNode(_nodeTobeAdded);
        }
    }
}</pre>
<p style="text-align: justify;">The GetNode method follows a similar logic, with recursive searching of the tree till a match is found, if no match is found then a null value is returned. Note that only around half of the tree is searched, rather than all of the nodes, as would be the case with a linkedList. GetNode is implemented both for the type and an object. In both cases the Equals method&#8217;s implementation is called, giving the generic type the ability to decide on its own equality logic.</p>
<pre class="code"><span style="color: blue;">public </span>T GetNode(T _nodeToBeGotten)
{
   <span style="color: blue;">if</span>(_nodeToBeGotten.Equals(Value))
       <span style="color: blue;">return </span>Value;
   <span style="color: blue;">else if</span>(_nodeToBeGotten.CompareTo(Value)&lt;0)
       <span style="color: blue;">return null</span>==_leftNode? <span style="color: blue;">default</span>(T): _leftNode.GetNode(_nodeToBeGotten);
   <span style="color: blue;">else
       return null</span>==_rightNode?<span style="color: blue;">default</span>(T): _rightNode.GetNode(_nodeToBeGotten);
}

<span style="color: blue;">public </span>T GetNode(<span style="color: blue;">object </span>o)
{
    <span style="color: blue;">if </span>(Value.Equals(o))
        <span style="color: blue;">return </span>Value;
    <span style="color: blue;">else if </span>(Value.CompareTo(o)&gt;0)
        <span style="color: blue;">return </span>(<span style="color: blue;">null </span>== _leftNode) ?
            <span style="color: blue;">default</span>(T) : _leftNode.GetNode(o);
    <span style="color: blue;">else
        return null </span>== _rightNode ?
            <span style="color: blue;">default</span>(T) : _rightNode.GetNode(o);
}</pre>
<p>Deleting is a bit tricky business. We have four scenarios here:-</p>
<ol>
<li style="text-align: justify;"> Its a leaf node, i.e. both the left and right children are null. This is the simplest scenario. Simply set the node itself to null</li>
<li style="text-align: justify;">The LeftNode is null but the right node is not, in this scenario &#8211; the node&#8217;s right node is set to the parent node&#8217;s right node, and the node is set to null.</li>
<li style="text-align: justify;">The Right node is null but left node is not. It is handled similar to the previous scenario.</li>
<li style="text-align: justify;">Both leftNode and rightNode is not null. In this scenarios we need to go down the leftnode, and iterate to its right most non empty node. This node is to be replaced with the node to be deleted. Just the value needs to be replaced and the right most node should be orphaned.</li>
</ol>
<pre class="code"><span style="color: blue;">public void </span>DeleteNode(<span style="color: blue;">object </span>o)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode1 = <span style="color: blue;">this</span>.GetTreeNode(o);
    DeleteNode(_tempNode1);
}

<span style="color: blue;">public void </span>DeleteNode(T _nodeTobeDeleted)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode1 = <span style="color: blue;">this</span>.GetTreeNode(_nodeTobeDeleted);
    DeleteNode(_tempNode1);
}

<span style="color: blue;">private void </span>DeleteNode(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode1)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; _tempNode2 = _tempNode1;
    <span style="color: blue;">if </span>((<span style="color: blue;">null </span>== _tempNode1._leftNode) &amp;&amp; (<span style="color: blue;">null </span>== _tempNode1._rightNode))
        _tempNode1._parentNode = <span style="color: blue;">null</span>;
    <span style="color: blue;">else if </span>(<span style="color: blue;">null </span>== _tempNode1._leftNode)
        _tempNode1._parentNode._rightNode = _tempNode1._rightNode;
    <span style="color: blue;">else if </span>(<span style="color: blue;">null </span>== _tempNode1._rightNode)
        _tempNode1._parentNode._leftNode = _tempNode1._leftNode;
    <span style="color: blue;">else
    </span>{
        <span style="color: blue;">bool </span>_goingRight = <span style="color: blue;">false</span>;
        _tempNode1 = _tempNode1._leftNode;
        <span style="color: blue;">while </span>(_tempNode1._rightNode != <span style="color: blue;">null</span>)
        {
            _tempNode1 = _tempNode1._rightNode;
            _goingRight = <span style="color: blue;">true</span>;
        }
        _tempNode2.Value = _tempNode1.Value;
        <span style="color: blue;">if </span>(_goingRight) _tempNode1._parentNode._rightNode = <span style="color: blue;">null</span>;
        <span style="color: blue;">else </span>_tempNode1._parentNode._leftNode = <span style="color: blue;">null</span>;
        _tempNode1 = <span style="color: blue;">null</span>;
    }
}

<span style="color: green;">//Private methods to get the nodes to be deleted
</span><span style="color: blue;">private </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; GetTreeNode(T _nodeToBeGotten)
{
    <span style="color: blue;">if </span>(_nodeToBeGotten.Equals(Value))
        <span style="color: blue;">return this</span>;
    <span style="color: blue;">else if </span>(_nodeToBeGotten.CompareTo(Value) &lt; 0)
        <span style="color: blue;">return null </span>== _leftNode ? <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _leftNode.GetTreeNode(_nodeToBeGotten);
    <span style="color: blue;">else
        return null </span>== _rightNode ? <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _rightNode.GetTreeNode(_nodeToBeGotten);
}

<span style="color: blue;">private </span><span style="color: #2b91af;">BinaryTree</span>&lt;T&gt; GetTreeNode(<span style="color: blue;">object </span>o)
{
    <span style="color: blue;">if </span>(Value.Equals(o))
        <span style="color: blue;">return this</span>;
    <span style="color: blue;">else if </span>(Value.CompareTo(o) &gt; 0)
        <span style="color: blue;">return </span>(<span style="color: blue;">null </span>== _leftNode) ?
            <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _leftNode.GetTreeNode(o);
    <span style="color: blue;">else
        return null </span>== _rightNode ?
            <span style="color: blue;">default</span>(<span style="color: #2b91af;">BinaryTree</span>&lt;T&gt;) : _rightNode.GetTreeNode(o);
}</pre>
<p>The class which could be added to the tree needs to implement the four interfaces i mentioned. I implemented an Employee class which has just two fields Name and age and the comparison is done based on the age.</p>
<pre class="code"><span style="color: blue;">class </span><span style="color: #2b91af;">Employee </span>: <span style="color: #2b91af;">IComparable</span>&lt;<span style="color: #2b91af;">Employee</span>&gt;,<span style="color: #2b91af;">IEquatable</span>&lt;<span style="color: #2b91af;">Employee</span>&gt;,<span style="color: #2b91af;">IEquatable</span>&lt;<span style="color: blue;">object</span>&gt;,<span style="color: #2b91af;">IComparable</span>&lt;<span style="color: blue;">object</span>&gt;
    {
        <span style="color: blue;">private string </span>_name;
        <span style="color: blue;">private int </span>_age;

        <span style="color: blue;">public int </span>Age{<span style="color: blue;">get</span>{<span style="color: blue;">return </span>_age;}}

        <span style="color: blue;">public </span>Employee(<span style="color: blue;">string </span>_name, <span style="color: blue;">int </span>_age)
        {
            <span style="color: blue;">this</span>._name = _name;
            <span style="color: blue;">this</span>._age = _age;
        }

        <span style="color: blue;">#region </span>IComparable&lt;Employee&gt; Members

        <span style="color: blue;">public int </span>CompareTo(<span style="color: #2b91af;">Employee </span>other)
        {
            <span style="color: blue;">if </span>(<span style="color: blue;">this</span>._age &lt; other._age)
                <span style="color: blue;">return </span>-1;
            <span style="color: blue;">else
                return </span>1;
        }

        <span style="color: blue;">#endregion

        public bool </span>Equals(<span style="color: #2b91af;">Employee </span>other)
        {
            <span style="color: blue;">if </span>(<span style="color: blue;">this</span>._age == other._age)
                <span style="color: blue;">return true</span>;
            <span style="color: blue;">else
                return false</span>;
        }

        <span style="color: blue;">#region </span>IEquatable&lt;object&gt; Members

        <span style="color: blue;">public override bool </span>Equals(<span style="color: blue;">object </span>other)
        {
            <span style="color: blue;">int </span>_age=0;
            <span style="color: blue;">if </span>(<span style="color: blue;">int</span>.TryParse(other.ToString(), <span style="color: blue;">out </span>_age))
            {
                <span style="color: blue;">return this</span>._age == _age ? <span style="color: blue;">true </span>: <span style="color: blue;">false</span>;
            }
            <span style="color: blue;">else return false</span>;
        }

        <span style="color: blue;">#endregion

        #region </span>IComparable&lt;object&gt; Members

        <span style="color: blue;">public int </span>CompareTo(<span style="color: blue;">object </span>other)
        {
            <span style="color: blue;">int </span>_age = 0;
            <span style="color: blue;">if </span>(<span style="color: blue;">int</span>.TryParse(other.ToString(), <span style="color: blue;">out </span>_age))
                <span style="color: blue;">return this</span>._age &lt; _age ? -1 : 1;
            <span style="color: blue;">else return </span>1;
        }

        <span style="color: blue;">#endregion

    </span>}</pre>
<p>This is the main method which adds a few objects to the tree collection.</p>
<pre class="code"><span style="color: blue;">static void </span>Main(<span style="color: blue;">string</span>[] args)
{
    <span style="color: #2b91af;">BinaryTree</span>&lt;Employee&gt; _btree = <span style="color: blue;">new </span><span style="color: #2b91af;">BinaryTree</span>&lt;Employee&gt;(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"RootValue"</span>,40));
    _btree.AddNode(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"Test1"</span>, 34));
    _btree.AddNode(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"Test2"</span>, 26));
    _btree.AddNode(<span style="color: blue;">new </span>Employee(<span style="color: #a31515;">"Test3"</span>, 65));
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/02/generic-binary-search-tree-in-c-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tic-Tac-Toe game in Silverlight</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/tic-tac-toe-game-in-silverlight/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/tic-tac-toe-game-in-silverlight/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 20:05:12 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=852</guid>
		<description><![CDATA[<p>Recently someone asked me to write a TicTacToe game. So I worked out a rough logic for it. Heres the code. The idea is that the computer first scans through the tic-tac-toe board for any winning positions available. If none are available, then it looks for the manual user&#8217;s winning positions. If its able to [...]]]></description>
			<content:encoded><![CDATA[<p>Recently someone asked me to write a TicTacToe game. So I worked out a rough logic for it. Heres the code. The idea is that the computer first scans through the tic-tac-toe board for any winning positions available. If none are available, then it looks for the manual user&#8217;s winning positions. If its able to find them, it blocks it. If not the next available position is filled. The game can be played by clicking any of the squares below.</p>
<div style="text-align:center">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="340"><param name="source" value="http://www.ganeshzone.net/Silverlight/Objects/TicTacToe.xap"/><param name="onError" value="onSilverlightError" /><param name="background" value="white" /><param name="minRuntimeVersion" value="3.0.40818.0" /><param name="autoUpgrade" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=149156&#038;v=3.0.40818.0" style="text-decoration:none"><br />
 			  <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/></p>
<p>		  </a><br />
	    </object> </div>
<p>Here is the code for the game as a silverlight application. The complete project can be downloaded <a href="http://www.ganeshzone.net/Files/TicTacToe.zip">here</a>.</p>
<p>The XAML is quite simple. Just a grid with three rows and three columns</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;gridGame&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;300&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;300&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Center&quot;</span> <span style="color: #000066;">VerticalAlignment</span>=<span style="color: #ff0000;">&quot;Center&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/grid<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;grid</span> .RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;rowdefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;rowdefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;rowdefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;grid</span> .ColumnDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;columndefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;columndefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;columndefinition</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;100&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>It is then filled with the buttons in the Code Behind. I have hardcoded the grid size of three but this will work with any size.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #0600FF;">public</span> MainPage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            InitializeComponent<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span> _fromConstructor<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_fromConstructor<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                gridGame.<span style="color: #0000FF;">Children</span>.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            _logic <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TicTacLogic<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> j <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> j <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">;</span> j<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    Button _btnGrid <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Button<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;btn&quot;</span> <span style="color: #008000;">+</span> i.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> j.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    gridGame.<span style="color: #0000FF;">Children</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_btnGrid<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    Grid.<span style="color: #0000FF;">SetRow</span><span style="color: #000000;">&#40;</span>_btnGrid, j<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    Grid.<span style="color: #0000FF;">SetColumn</span><span style="color: #000000;">&#40;</span>_btnGrid, i<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Height</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">80</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Width</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">80</span><span style="color: #008000;">;</span>
                    _btnGrid.<span style="color: #0000FF;">Click</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> RoutedEventHandler<span style="color: #000000;">&#40;</span>_btnGrid_Click<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
            _logic.<span style="color: #0000FF;">StartGame</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>All the dynamically generated buttons have a single event handler. The idea is to identify the button which sent the event from the name. Once we have the position of the button, the content has to be changed with an X. After the user marks, the computer does its stuff and makes its move. After every marking, a check is done if someone has won or the board is full.</p>
</pre>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">void</span> _btnGrid_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, RoutedEventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Button _userClicked <span style="color: #008000;">=</span> sender <span style="color: #0600FF;">as</span> Button<span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _xPos <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>_userClicked.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">Substring</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span>,<span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _yPos <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>_userClicked.<span style="color: #0000FF;">Name</span>.<span style="color: #0000FF;">Substring</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">4</span>,<span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _userClicked.<span style="color: #0000FF;">Content</span> <span style="color: #008000;">=</span> GetMarking<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;X&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _logic.<span style="color: #0000FF;">ClickUser</span><span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #000000;">&#40;</span>_logic.<span style="color: #0000FF;">CheckIfSomeoneWon</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">||</span> _logic.<span style="color: #0000FF;">CheckIfBoardFull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">int</span> _xCom <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
                <span style="color: #FF0000;">int</span> _yCom <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
                _logic.<span style="color: #0000FF;">MoveComputer</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> _xCom, <span style="color: #0600FF;">ref</span> _yCom<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>UIElement _tempElem <span style="color: #0600FF;">in</span> gridGame.<span style="color: #0000FF;">Children</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    Button _comBtn <span style="color: #008000;">=</span> _tempElem <span style="color: #0600FF;">as</span> Button<span style="color: #008000;">;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_comBtn <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> _comBtn.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;btn&quot;</span> <span style="color: #008000;">+</span> _xCom <span style="color: #008000;">+</span> _yCom<span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        _comBtn.<span style="color: #0000FF;">Content</span> <span style="color: #008000;">=</span> GetMarking<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;O&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                        break<span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_logic.<span style="color: #0000FF;">CheckIfSomeoneWon</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">||</span> _logic.<span style="color: #0000FF;">CheckIfBoardFull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span>
                InitializeGameLogic<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> TextBlock GetMarking<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _mark<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            TextBlock _t <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TextBlock<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _t.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span> _mark<span style="color: #008000;">;</span>
            _t.<span style="color: #0000FF;">FontSize</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">25</span><span style="color: #008000;">;</span>
            _t.<span style="color: #0000FF;">FontWeight</span> <span style="color: #008000;">=</span> FontWeights.<span style="color: #0000FF;">Bold</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">return</span> _t<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The Board class maintains two important things. The position of all the squares and which player has it marked. The Board doesnt depend on the Player objects. It has an object of the WinningPositions object which calculates the winning positions which can be compared with later. This object makes it possible to play  with larger grids.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Board
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">readonly</span> <span style="color: #FF0000;">int</span> MAXSIZE<span style="color: #008000;">;</span>
    List<span style="color: #008000;">&lt;</span>positionmarking<span style="color: #008000;">&gt;</span> _boardState <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;/</span>positionmarking<span style="color: #008000;">&gt;&lt;</span>positionmarking<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    List<span style="color: #008000;">&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> _allWinningPositions<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span>positionmarking<span style="color: #008000;">&gt;</span> BoardState <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _boardState<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> AllWinningPositions <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _allWinningPositions<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> MaxSize <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> MAXSIZE<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Board<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">MAXSIZE</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">;</span>
        Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Board<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _maxSize<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        MAXSIZE <span style="color: #008000;">=</span> _maxSize<span style="color: #008000;">;</span>
        Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _allWinningPositions <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> WinningPositions<span style="color: #000000;">&#40;</span>MAXSIZE<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">AllWinningPositions</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xPos<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>_xPos<span style="color: #008000;">&lt;</span>maxsize <span style="color: #008000;">;</span>_xPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> _yPos <span style="color: #008000;">&lt;</span> MAXSIZE<span style="color: #008000;">;</span> _yPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _boardState.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> PositionMarking<span style="color: #000000;">&#40;</span>_xPos,_yPos<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> MarkPosition<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xUser, <span style="color: #FF0000;">int</span> _yUser, <span style="color: #FF0000;">bool</span> _userMarked<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempPos <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempPos.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">==</span> _xUser <span style="color: #008000;">&amp;&amp;</span> _tempPos.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">==</span> _yUser<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _tempPos.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_userMarked<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                break<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
<span style="color: #008080;">#if DEBUG</span>
        PrintBoardState<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080;">#endif</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> MarkedByUser<span style="color: #000000;">&#40;</span>Position _tempPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempMark <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempPos.<span style="color: #0000FF;">X</span> <span style="color: #008000;">==</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">&amp;&amp;</span> _tempPos.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">==</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> _tempMark.<span style="color: #0000FF;">IsUserMarked</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Position Not found on Board&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080;">#if DEBUG</span>
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> PrintBoardState<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">string</span> _userMarked <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">string</span> _compMarked <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempMark <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>
                _userMarked <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot;(&quot;</span><span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;,&quot;</span> <span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;) &quot;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span>
                _compMarked <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot;(&quot;</span> <span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;,&quot;</span> <span style="color: #008000;">+</span> _tempMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;) &quot;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;USER: &quot;</span> <span style="color: #008000;">+</span> _userMarked<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;COMP: &quot;</span> <span style="color: #008000;">+</span> _compMarked<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;________________________________________&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #008080;">#endif</span>
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span> IsBoardFull<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _tempMark <span style="color: #0600FF;">in</span> _boardState<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_tempMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Board Full&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The Winning Position class is given below and all positions are calculated at initialization. First the horizontal ones are considered and then the vertical ones. The remaining diagonal positons are taken care later. Each winning position is stored in an array of the position object which just holds the value of the Squares. These arrays are stored in a generic List.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> WinningPositions
<span style="color: #000000;">&#123;</span>
    List<span style="color: #008000;">&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> _allWinningPositions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _winPos1<span style="color: #008000;">;</span>
    Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _winPos2<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;&lt;</span>position <span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">&gt;</span> AllWinningPositions
    <span style="color: #000000;">&#123;</span>
        get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _allWinningPositions<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> WinningPositions<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _maxSize<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _winPos1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_maxSize<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
        _winPos2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_maxSize<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
        PopulateWinningPositions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> PopulateWinningPositions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">int</span> _iCounter<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> _xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> _yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> _xPos <span style="color: #008000;">&lt;</span> _winPos2.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _xPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> _yPos <span style="color: #008000;">&lt;</span> _winPos2.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _yPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _winPos1<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _winPos2<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_yPos, _xPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _iCounter<span style="color: #008000;">++;</span>
            <span style="color: #000000;">&#125;</span>
            _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos1<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos2<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _winPos1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_winPos1.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
            _winPos2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#91;</span>_winPos2.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
            _iCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        _iCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>, _yPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>_xPos <span style="color: #008000;">&lt;</span> _winPos1.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _xPos<span style="color: #008000;">++</span>, _yPos<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _winPos1<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            _iCounter<span style="color: #008000;">++;</span>
        <span style="color: #000000;">&#125;</span>
        _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos1<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _iCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>_xPos <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>, _yPos <span style="color: #008000;">=</span> _winPos1.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> _xPos <span style="color: #008000;">&lt;</span> _winPos1.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> _xPos<span style="color: #008000;">++</span>, _yPos<span style="color: #008000;">--</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _winPos2<span style="color: #000000;">&#91;</span>_iCounter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _iCounter<span style="color: #008000;">++;</span>
        <span style="color: #000000;">&#125;</span>
        _allWinningPositions.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>_winPos2<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Then there is the Player class of which we create two objects. The user takes care of his own moving logic, all we need to do is to change the state of the square for him. But the computer has its method called the <strong>SmartMove</strong>. Here we first move through the winning positions to identify any open squares that can be marked. If there are no squares, then we look to block the opponent's winning. If even this opportunity is not found, we mark an available open square.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Player
<span style="color: #000000;">&#123;</span>
    Board _currentBoardPosition<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">bool</span> _isComputer<span style="color: #008000;">;</span>
    List<span style="color: #008000;">&lt;</span>position<span style="color: #008000;">&gt;</span> _allMarkedPositions<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Player<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span> _isComputer,Board _currentBoardPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>._isComputer <span style="color: #008000;">=</span> _isComputer<span style="color: #008000;">;</span>
        _allMarkedPositions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;&lt;</span>position<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _currentBoardPosition <span style="color: #008000;">=</span> _currentBoardPos<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> SmartMove<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _xCom, <span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _yCom<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">bool</span> _markingDone <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
        <span style="color: #FF0000;">bool</span> _blockUser <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
        Position _userBlock <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _winPos <span style="color: #0600FF;">in</span> _currentBoardPosition.<span style="color: #0000FF;">AllWinningPositions</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> _userMarked <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _computerMarked <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _nullMarked<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
            Position _openPos<span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position _tempPos <span style="color: #0600FF;">in</span> _winPos<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> isUserMarked <span style="color: #008000;">=</span> _currentBoardPosition.<span style="color: #0000FF;">MarkedByUser</span><span style="color: #000000;">&#40;</span>_tempPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked<span style="color: #008000;">==</span><span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>
                    _userMarked<span style="color: #008000;">++;</span>
                <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span>
                    _computerMarked<span style="color: #008000;">++;</span>
                <span style="color: #0600FF;">else</span>
                <span style="color: #000000;">&#123;</span>
                    _openPos <span style="color: #008000;">=</span> _tempPos<span style="color: #008000;">;</span>
                    _nullMarked<span style="color: #008000;">++;</span>
                <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_computerMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">&amp;&amp;</span> _nullMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Wining block: &quot;</span> <span style="color: #008000;">+</span> _openPos.<span style="color: #0000FF;">X</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;,&quot;</span> <span style="color: #008000;">+</span> _openPos.<span style="color: #0000FF;">Y</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _currentBoardPosition.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_openPos.<span style="color: #0000FF;">X</span>, _openPos.<span style="color: #0000FF;">Y</span>, <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                _xCom <span style="color: #008000;">=</span> _openPos.<span style="color: #0000FF;">X</span><span style="color: #008000;">;</span>
                _yCom <span style="color: #008000;">=</span> _openPos.<span style="color: #0000FF;">Y</span><span style="color: #008000;">;</span>
                _markingDone <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
                break<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_userMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">2</span> <span style="color: #008000;">&amp;&amp;</span> _nullMarked <span style="color: #008000;">==</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _userBlock <span style="color: #008000;">=</span> _openPos<span style="color: #008000;">;</span>
                _blockUser <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_blockUser <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>_markingDone<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _currentBoardPosition.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_userBlock.<span style="color: #0000FF;">X</span>, _userBlock.<span style="color: #0000FF;">Y</span>, <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _xCom <span style="color: #008000;">=</span> _userBlock.<span style="color: #0000FF;">X</span><span style="color: #008000;">;</span>
            _yCom <span style="color: #008000;">=</span> _userBlock.<span style="color: #0000FF;">Y</span><span style="color: #008000;">;</span>
            _markingDone <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>_markingDone<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//No Winning Position Found or not able to block;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>PositionMarking _posMark <span style="color: #0600FF;">in</span> _currentBoardPosition.<span style="color: #0000FF;">BoardState</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_posMark.<span style="color: #0000FF;">IsUserMarked</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    _markingDone <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
                    _currentBoardPosition.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span>, _posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span>,<span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    _xCom <span style="color: #008000;">=</span> _posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">X</span><span style="color: #008000;">;</span>
                    _yCom <span style="color: #008000;">=</span> _posMark.<span style="color: #0000FF;">BoardPosition</span>.<span style="color: #0000FF;">Y</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #008000;">&lt;/</span>position<span style="color: #008000;">&gt;</span></pre></td></tr></table></div>

<p>Since the Board needs to maintain the state of each and every position on itself, we have another object for it, which maintains a position object and a nullable boolean. If the boolean is true, then the square is marked by the user, if false - then by the computer. If its still null - its open and can be marked. The marking is done by the object's method which makes a check to make sure no players marking is overwritten by another.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PositionMarking
<span style="color: #000000;">&#123;</span>
    Position _boardPos<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> _isUserMarked<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Position BoardPosition <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _boardPos<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> IsUserMarked <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _isUserMarked<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> PositionMarking<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xPos,<span style="color: #FF0000;">int</span> _yPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _isUserMarked <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
        _boardPos <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Position<span style="color: #000000;">&#40;</span>_xPos, _yPos<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> MarkPosition<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span> _markedByUser<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>_isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
        _isUserMarked <span style="color: #008000;">=</span> _markedByUser<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">else</span>
        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Position already taken&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Then there is the rest of the code including our business logic layer.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> TicTacLogic
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">bool</span> _userToMove<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">bool</span> _resultHasCome<span style="color: #008000;">;</span>
    Player _user<span style="color: #008000;">;</span>
    Player _computer<span style="color: #008000;">;</span>
    Board _gameBoard<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> TicTacLogic<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _userToMove <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
        _resultHasCome <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> StartGame<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span> ClickUser<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> _xUser, <span style="color: #FF0000;">int</span> _yUser<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> _gameBoard.<span style="color: #0000FF;">MarkPosition</span><span style="color: #000000;">&#40;</span>_xUser, _yUser, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> MoveComputer<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _xCom, <span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> _yCom<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _computer.<span style="color: #0000FF;">SmartMove</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> _xCom, <span style="color: #0600FF;">ref</span> _yCom<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">void</span> Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _gameBoard <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Board<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _user <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Player<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span>,_gameBoard<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _computer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Player<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">true</span>,_gameBoard<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> CheckIfSomeoneWon<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _tempWin <span style="color: #0600FF;">in</span> _gameBoard.<span style="color: #0000FF;">AllWinningPositions</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> _userWon<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">int</span> _compWon<span style="color: #008000;">=</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Position _p <span style="color: #0600FF;">in</span> _tempWin<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">bool</span><span style="color: #008000;">?</span> isUserMarked <span style="color: #008000;">=</span> _gameBoard.<span style="color: #0000FF;">MarkedByUser</span><span style="color: #000000;">&#40;</span>_p<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                    break<span style="color: #008000;">;</span>
                <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isUserMarked <span style="color: #008000;">==</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>
                    _userWon<span style="color: #008000;">++;</span>
                <span style="color: #0600FF;">else</span>
                    _compWon<span style="color: #008000;">++;</span>
&nbsp;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_userWon <span style="color: #008000;">==</span> _gameBoard.<span style="color: #0000FF;">MaxSize</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;User Won&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_compWon <span style="color: #008000;">==</span> _gameBoard.<span style="color: #0000FF;">MaxSize</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Computer Won&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">internal</span> <span style="color: #FF0000;">bool</span> CheckIfBoardFull<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> _gameBoard.<span style="color: #0000FF;">IsBoardFull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Position
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> _xPos<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">int</span> _yPos<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Position<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> X <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _xPos<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Y <span style="color: #000000;">&#123;</span> get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _yPos<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> Position<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> xPos, <span style="color: #FF0000;">int</span> yPos<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>._xPos <span style="color: #008000;">=</span> xPos<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>._yPos <span style="color: #008000;">=</span> yPos<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

</position></pre>
<p></maxsize></position></positionmarking></position></positionmarking></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/tic-tac-toe-game-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploying ASP.NET MVC Apps on Shared Hosting</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/deploying-asp-net-mvc-apps-on-shared-hosting/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/deploying-asp-net-mvc-apps-on-shared-hosting/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 18:20:39 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=823</guid>
		<description><![CDATA[<p>Here are the steps to deploy MVC applications to servers with shared hosting providers.</p>

In your Hosting provider&#8217;s IIS management panel, create a sub directory and configure it as an appplication- root, so that it is recognized as an asp.net application.


Set your MVC dll&#8217;s Copy To Local property to true, so that they are copied to [...]]]></description>
			<content:encoded><![CDATA[<p>Here are the steps to deploy MVC applications to servers with shared hosting providers.</p>
<ul>
<li>In your Hosting provider&#8217;s IIS management panel, create a sub directory and configure it as an appplication- root, so that it is recognized as an asp.net application.</li>
</ul>
<ul>
<li>Set your MVC dll&#8217;s Copy To Local property to true, so that they are copied to the bin directory of the project.</li>
</ul>
<ul>
<li>Edit your web.config file and update the debug property to false. This holds true for all web applications.</li>
</ul>
<ul>
<li>Update the connection strings to your hosting provider&#8217;s connection strings.</li>
</ul>
<p>Thats it. Your MVC application should run fine. Mine <a href="http://ganeshzone.net/mvctestdeploy/">does</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/deploying-asp-net-mvc-apps-on-shared-hosting/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>ASP.NET Evolution: WebForms v/s MVC</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2010/01/asp-net-evolution-webforms-vs-mvc/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2010/01/asp-net-evolution-webforms-vs-mvc/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 05:43:42 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=789</guid>
		<description><![CDATA[<p style="text-align: justify;">Though MVC is an age old architectural style that has existed since the 70s, its a relatively new entrant in the .NET world. I had written a general introduction about MVC earlier. That post is available here. While Java, Ruby, Python all had their MVC frameworks for quite some time, ASP.NET was quite comfortable [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Though MVC is an age old architectural style that has existed since the 70s, its a relatively new entrant in the .NET world. I had written a general introduction about MVC earlier. That post is available <a href="http://blog.ganeshzone.net/blog/index.php/2009/11/asp-net-mvc-applications/">here</a>. While Java, Ruby, Python all had their MVC frameworks for quite some time, ASP.NET was quite comfortable with the Webform based architecture till recently. And Webforms arent really a bad way to code at all, you work with almost a Windows style of programming, dragging dropping controls. Double clicking them to code their event handlers. In fact due to this Rapid application development, ASP.NET was amazingly simple to work with. However, like with all other simple ways, ASP.NET webforms also take a lot of control away from the developer.</p>
<p style="text-align: justify;">MVC seeks to give developers an alternative, where they have complete control over the application including the viewstate of the controls. My first look was at ASP.NET MVC was a training session given by an architect from Microsoft, and I absolutely didn&#8217;t like the complexity it brought to a simple demo application that was showed. I found that we were writing too much code, again bringing back spaghetti code that died with ASP. But over time, after digging into MVC, I found that it made a lot of sense. If my need is just to display a set of data, why should I sacrifice performance over all of the gridview&#8217;s bulky viewstate. Rather, it makes sense to use a HTML table and apply CSS to style it.  That is exactly the flexibility that MVC gives you, instead of relying on built in abstraction done by Webform architecture, you get to control every detail of your application.</p>
<h2>WebForms</h2>
<p style="text-align: justify;">ASP.NET Webforms are radically different from any other server side scripting technology. For one, its event driven. Just like Windows programming, you assign an event handler to an element, like a button and it calls the handler when the button is clicked. No longer, do you have to keep on submitting the form to handle click events and write bulky code to do simple stuff. ASP.NET made the server side code clean &#8211; in fact a helluva lot cleaner than ASP.</p>
<p style="text-align: justify;">But all this ignores the age old truth about the web/HTTP &#8211; that it is stateless. The server forgets about the page the minute its sent to the client and thats the end of it. So how is context maintained in WebForms? The answer is <strong>Viewstate</strong>. All of the control states are Base64 encoded and recreated on the server again where the request is executed. There is a lot of built-in plumbing to achieve this level of abstraction.</p>
<p style="text-align: justify;">The main problem with webforms is that though it cleans up your code and markup and seperates them neatly in your Visual studio solution, it horribly clutters the rendered markup to the browser. Every control takes up more and more viewstate and the nested control names which are really long, make the markup bulky, and since this does a round trip on every request, it starts impacting performance and eventually scalability.</p>
<p style="text-align: justify;">One more concern is the Testability, due to the event driven approach, the GUI is tighly coupled with your business layer and there isnt any effective way to test your web page. Automating such testing could be an tedious effort and you would most probably end up doing manual testing.</p>
<p style="text-align: justify;">Despite all of these problems, Webforms are not a bad architecture. It is extremely mature and extensible. A lot of good documentation exists for it and it still makes sense for quite a few scenarios.</p>
<h2>MVC</h2>
<p style="text-align: justify;">With MVC, it was love at first byte. In fact I never realized how inefficient webforms were, until i worked with MVC. Instead of a page receiving the request, its the Controller which lives at the heart of MVC. Once it gets the request, it decides which view to render and may use models.</p>
<p style="text-align: justify;">One great thing about MVC is the clean Seperation of Concerns (SoC ) which you are able to achieve out of the box. Both the Controllers and the Views can be tested separately using testing tools like NUnit or MBUnit. So that means no longer. Manual testing doesn&#8217;t really make any sense for most scenarios, because the effort is not repeatable and when you want to try with a different input, you would need to start all over again.</p>
<p style="text-align: justify;">
<div id="_mcePaste" style="text-align: justify;">Also, you have complete control over the HTML that your controls generate. No more grappling with heavy Viewstate and decreased performance. Also there is no concept of a postback in MVC. Hence although, we can make use of ASP.NET server controls, we cant use either ViewState or Postback in them. Microsoft is working to create a library of MVC aware server controls that would be more suitable for this architectural style. Also, you have complete control over the HTML that your controls generate. No more grappling with heavy Viewstate and decreased performance. Also there is no concept of a postback in MVC. Hence although, we can make use of ASP.NET server controls, we cant use either ViewState or Postback in them. Microsoft is working to create a library of MVC aware server controls that would be more suitable for this architectural style.</div>
<p style="text-align: justify;">One major point that is oft repeated is that we shouldn&#8217;t jump the gun to convert every existing webforms applications into MVC just because its the in thing. You would have to rewrite your application completely, and the benefit derived would often not be worth the effort. But I would certainly  recommend that  you use MVC for any new applications you create. Its certainly the smarter way.</p>
<p style="text-align: justify;">
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2010/01/asp-net-evolution-webforms-vs-mvc/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
