<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>c-30 &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/c-30/</link>
	<description>Feed of posts on WordPress.com tagged "c-30"</description>
	<pubDate>Thu, 03 Dec 2009 07:05:43 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[007! He knows what to fly! — Little Nellie and other autogiros]]></title>
<link>http://travelforaircraft.wordpress.com/2009/10/07/007-he-knows-what-to-fly/</link>
<pubDate>Wed, 07 Oct 2009 19:00:31 +0000</pubDate>
<dc:creator>travelforaircraft</dc:creator>
<guid>http://travelforaircraft.wordpress.com/2009/10/07/007-he-knows-what-to-fly/</guid>
<description><![CDATA[Who has not and been thrilled by the autogiro in the aerial battle piloted by world famous British s]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Who has not and been thrilled by the autogiro in the aerial battle piloted by world famous British secret agent James Bond 007 in <em>You Only Live Twice</em>? Seeing the craft slice and dice those evil helicopters excited us all as we watched our hero in the open cockpit of what appears to be a machine that is part helicopter and part airplane. As it turns out, the aircraft was named <em>Little Nellie</em> and was piloted in reality by the accomplished Ken Wallis — Wing Commander Kenneth Horatio Wallis MBE<strong>, </strong>DEng (hc), CEng<strong>, </strong>FRAeS, FSETP<strong>, </strong>PhD (hc), RAF (Ret&#8217;d). For a book on Little Nellie please see “Little Nellie” by Bruce Barrymore Halpenny.</p>
<p>Mr. Wallis is a great proponent of autogiros … so just what are these machines? Essentially, they are aircraft powered by an engine driving a propeller and this propeller provides forward momentum which, subsequently, passively turns a rotor disk.</p>
<p>I have seen four autogiro types in museums including one designed by the man who invented this class of flying machine, Juan de la Cierva. The first such craft I saw is in the <a href="http://www.fantasyofflight.com/" target="_self">Fantasy of Flight Aircraft Collection</a> — the Cierva C.30-A Autogiro. The second example I saw, was a Kellett XO-60 — and the third was an Autogiro Company of America AC‑35 — both in the <a href="http://www.nasm.si.edu/museum/" target="_self">Smithsonian National Air &#38; Space Museum Udvar‑Hazy Complex</a>. The fourth (yet another Kellett) was the K-2 Autogiro in the <a href="http://www.nationalmuseum.af.mil/" target="_self">National Museum of the USAF</a>.</p>
<p>The Cierva C.30-A Autogiro was the first of autogiros to have a tilting rotor hub, thus giving autogiros great handling characteristics at low speeds &#8212; what had been lacking without the tilting rotor hub.</p>
<p> </p>
<div id="attachment_373" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-373 " title="blog Cierva_MG_6597LG" src="http://travelforaircraft.wordpress.com/files/2009/08/blog-cierva_mg_6597lg1.jpg" alt="Cierva C.30 Autogiro -- photo by Joe May" width="600" height="400" /><p class="wp-caption-text">Cierva C.30 Autogiro — photo by Joe May</p></div>
<p>The Kellett autogiros took after the designs of Cierva as well as Pitcairn. The Kellett XO-60 was the acme of autogiro development and occurred in 1943, but the advent of the helicopter obviated the use of autogiros in the military.</p>
<p> </p>
<div id="attachment_374" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-374 " title="blog Kellett K-2_MG_8767" src="http://travelforaircraft.wordpress.com/files/2009/08/blog-kellett-k-2_mg_8767.jpg" alt="Kellett K-2 autogiro -- photo by Joe May" width="600" height="400" /><p class="wp-caption-text">Kellett K-2 autogiro — photo by Joe May</p></div>
<p> </p>
<div id="attachment_375" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-375 " title="blog Kellett XO-60_MG_9659" src="http://travelforaircraft.wordpress.com/files/2009/08/blog-kellett-xo-60_mg_9659.jpg" alt="Kellett XO-60 autogiro -- photo by Joe May" width="600" height="400" /><p class="wp-caption-text">Kellett XO-60 autogiro — photo by Joe May</p></div>
<p> </p>
<p>Harold F. Pitcairn developed many aviation designs and founded the predecessor to Eastern Airlines. One of his autogiro designs — the previously mentioned AC-35 — was unique in that the rotor blades could be folded and the engine could then engage the tail wheel so that motoring at 25 mph (40kph) was possible. </p>
<p> </p>
<div id="attachment_376" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-376 " title="blog Autogiro Company of America AC-35 IMG_9819" src="http://travelforaircraft.wordpress.com/files/2009/08/blog-autogiro-company-of-america-ac-35-img_9819.jpg" alt="Pitcairn's Autogiro Co. of America AC-35 -- photo by Joe May" width="600" height="400" /><p class="wp-caption-text">Pitcairn&#39;s Autogiro Co. of America AC-35 — photo by Joe May</p></div>
<p>Autogiros have not caught on commercially but are attractive to many since they are difficult to stall, flying as slowly as 20 mph (30kph), require a short take off run and much shorter landing run (nearly vertical with sufficient wind and a spiral approach), simplicity, open air cockpit and fuel economy.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ASP.NET print HTML report in A4 Paper]]></title>
<link>http://joehom.wordpress.com/2009/09/17/asp-net-print-html-report-in-a4-paper/</link>
<pubDate>Wed, 16 Sep 2009 16:54:44 +0000</pubDate>
<dc:creator>joehom</dc:creator>
<guid>http://joehom.wordpress.com/2009/09/17/asp-net-print-html-report-in-a4-paper/</guid>
<description><![CDATA[work in ASP.net project again. currently working on report module.  I need to print all members noti]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>work in ASP.net project again. currently working on report module.  I need to print all members notification letter in once.  the best way for web printing of course is generate PDF file, but my company no provide me PDF library, and I can’t find any free PDF library for ASP.net. So, the only method is use the javaScript, Window.print() function to print my report.</p>
<p>I used repeater web control to generate the report and in HTML form.</p>
<p>I need fix all in A4 size, if my repeater generate 4 member notification  letter, then I need exactly print 4 letters in A4 paper.</p>
<p><a href="http://joehom.files.wordpress.com/2009/09/0.png"><img style="display:inline;border-width:0;" title="0" src="http://joehom.files.wordpress.com/2009/09/0_thumb.png?w=456&#038;h=254" border="0" alt="0" width="456" height="254" /></a></p>
<p>But you may face this problem:</p>
<p><a href="http://joehom.files.wordpress.com/2009/09/1.png"><img style="display:inline;border-width:0;" title="1" src="http://joehom.files.wordpress.com/2009/09/1_thumb.png?w=448&#038;h=318" border="0" alt="1" width="448" height="318" /></a></p>
<p>when the first page content cannot fix in entire A4 paper, the second page content will move up. or maybe :</p>
<p><a href="http://joehom.files.wordpress.com/2009/09/2.png"><img style="display:inline;border-width:0;" title="2" src="http://joehom.files.wordpress.com/2009/09/2_thumb.png?w=442&#038;h=387" border="0" alt="2" width="442" height="387" /></a></p>
<p>the first page content too long, and extend to second page.</p>
<p>that&#8217;s not really possible to control,  because it depending on content. But I found out the IE8( or IE7) have a function call “shrink-to-fit”that can solve my problem.</p>
<p>I need to explain my situation,</p>
<p>1st, I <strong>build management system</strong> for a company but<strong> not create website</strong> for company. So, I can force my client using which browser to operate the system. 2nd, client no require cross browser capability . 3rd, my company no provide any printing library for me.</p>
<p>first of all, you need write all the page content(report content) within the &#60;div&#62; , 210mm X 297mm is A4 paper size.</p>
<p><a href="http://joehom.files.wordpress.com/2009/09/3.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="3" src="http://joehom.files.wordpress.com/2009/09/3_thumb.png?w=454&#038;h=188" border="0" alt="3" width="454" height="188" /></a></p>
<p>2nd, setting IE:</p>
<p>left click on &#8220;Page Setup&#8230; (menu item)&#8221;</p>
<p><a href="http://joehom.files.wordpress.com/2009/09/image.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" src="http://joehom.files.wordpress.com/2009/09/image_thumb.png?w=453&#038;h=286" border="0" alt="image" width="453" height="286" /></a></p>
<p>change the page size to A4 size.</p>
<p><a href="http://joehom.files.wordpress.com/2009/09/image1.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" src="http://joehom.files.wordpress.com/2009/09/image_thumb1.png?w=453&#038;h=286" border="0" alt="image" width="453" height="286" /></a></p>
<p>Tick the Enable Shink-to-Fit</p>
<p><a href="http://joehom.files.wordpress.com/2009/09/image2.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" src="http://joehom.files.wordpress.com/2009/09/image_thumb2.png?w=460&#038;h=291" border="0" alt="image" width="460" height="291" /></a></p>
<p>Done. Now you can print your report nicely. kindly Email me, if you face any problem in ASP.net printing issue.</p>
<p>you can download my solution file <a href="http://www.mediafire.com/download.php?ndzmzmyyddd">here</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[?? Operator (null-coalescing operator)]]></title>
<link>http://priyangpatel.wordpress.com/2009/09/10/operator-null-coalescing-operator/</link>
<pubDate>Thu, 10 Sep 2009 06:16:10 +0000</pubDate>
<dc:creator>priyangpatel</dc:creator>
<guid>http://priyangpatel.wordpress.com/2009/09/10/operator-null-coalescing-operator/</guid>
<description><![CDATA[?? is used to define a default value for a nullable value types as well as reference types. It retur]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>?? is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.</p>
<p>A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.</p>
<div id="attachment_57" class="wp-caption alignnone" style="width: 485px"><a href="http://priyangpatel.wordpress.com/files/2009/09/tempblog.jpg"><img class="size-full wp-image-57" title="Example" src="http://priyangpatel.wordpress.com/files/2009/09/tempblog.jpg" alt="Example" width="475" height="147" /></a><p class="wp-caption-text">Example</p></div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[wildcard searches using LINQ]]></title>
<link>http://joehom.wordpress.com/2009/08/26/wildcard-searches-using-linq/</link>
<pubDate>Wed, 26 Aug 2009 10:14:43 +0000</pubDate>
<dc:creator>joehom</dc:creator>
<guid>http://joehom.wordpress.com/2009/08/26/wildcard-searches-using-linq/</guid>
<description><![CDATA[recently work on ASP.Net Project. use LINQ as my Query Language, this is my favorite  feature of .Ne]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>recently work on ASP.Net Project.<br />
use LINQ as my Query Language, this is my favorite  feature of .Net 3.5.<br />
original I write my Search Query like this:<br />
<span style="font-size:xx-small;">var searchQuery=<span style="color:blue;">from</span> a <span style="color:blue;">in</span> db.customer<br />
<span style="color:blue;">where</span> a.ID=param<br />
<span style="color:blue;">select</span> a;</span></p>
<p>this is not a wildcard search query , you only can get the result when parameter(search key word)  exactly same with database record. So far customer no complain the search engine, because they don’t know and my boss also din ask me to do wildcard searches. but as a programmer, you do not want to create a system without standard. My boss always blame me do redundant work,  customer won’t appreciate it. But I not care, just a minor change only.</p>
<p>to do wildcard searches in sql is use LIKE operation and wildcard characters( %), I believe you familiar than me if you still using ADO.NET to query your database. it something like this:</p>
<pre>
<pre style="background-color:#ffffff;width:100%;"><a style="color:#0000ff;" href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=SELECT&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99"><span style="font-size:xx-small;">SELECT</span></a><span style="font-size:xx-small;"> *
</span></pre>
<pre style="background-color:#ffffff;width:100%;"><a style="color:#0000ff;" href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=FROM&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99"><span style="font-size:xx-small;">FROM</span></a><span style="font-size:xx-small;"> Customers
</span></pre>
<pre style="background-color:#ffffff;width:100%;"><a style="color:#0000ff;" href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=WHERE&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99"><span style="font-size:xx-small;">WHERE</span></a><span style="font-size:xx-small;"> Phone </span><a style="color:#0000ff;" href="http://search.microsoft.com/default.asp?so=RECCNT&#38;siteid=us%2Fdev&#38;p=1&#38;nq=NEW&#38;qu=LIKE&#38;IntlSearch=&#38;boolean=PHRASE&#38;ig=01&#38;i=09&#38;i=99"><span style="font-size:xx-small;">LIKE</span></a><span style="font-size:xx-small;"> </span><a href="mailto:'@param'"><span style="font-size:xx-small;">'%<span style="color:#8b0000;">param%'</span></span></a><span style="font-size:xx-small;"><span style="color:#8b0000;"> </span></span></pre>
</pre>
<p>It&#8217;s fairly simple, if you using LINQ, you just need to know .StartsWith, .EndsWith, and .Contains this 3 syntaxes. below show comparison of LINQ and SQL:</p>
<table border="0" cellspacing="0" cellpadding="2" width="520">
<tbody>
<tr>
<td width="133" valign="top"></td>
<td width="195" valign="top">
<p align="center"><strong>LINQ</strong></p>
</td>
<td width="190" valign="top">
<p align="center"><strong>SQL</strong></p>
</td>
</tr>
<tr>
<td width="133" valign="top">StartsWith</td>
<td width="195" valign="top">
<div><span style="font-size:xx-small;">var query=<span style="color:blue;">from</span> a <span style="color:blue;">in</span> db.customer</p>
<p><span style="color:blue;">where</span> a.ID.StartsWith(param)</p>
<p><span style="font-size:xx-small;"> <span style="color:blue;">select</span> a;</span></p>
<p></span></div>
</td>
<td width="190" valign="top">
<div><span style="font-size:xx-small;"><span style="color:blue;">Select</span>*</p>
<p><span style="color:#0000ff;">from</span> Customer</p>
<p><span style="font-size:xx-small;"><span style="color:#0000ff;">where</span> id=param%;</span></p>
<p></span></div>
</td>
</tr>
<tr>
<td width="133" valign="top">EndsWith</td>
<td width="195" valign="top">
<div><span style="font-size:xx-small;">var query=<span style="color:blue;">from</span> a <span style="color:blue;">in</span> db.customer</p>
<p><span style="color:blue;">where</span> a.ID.EndsWith(param)</p>
<p><span style="font-size:xx-small;"> <span style="color:blue;">select</span> a;</span></p>
<p></span></div>
</td>
<td width="190" valign="top">
<div><span style="font-size:xx-small;"><span style="color:blue;">Select</span>*</p>
<p><span style="color:#0000ff;">from</span> Customer</p>
<p><span style="font-size:xx-small;"><span style="color:#0000ff;">where</span> id=%param;</span></p>
<p></span></div>
</td>
</tr>
<tr>
<td width="133" valign="top">Contains</td>
<td width="195" valign="top">
<div><span style="font-size:xx-small;">var query=<span style="color:blue;">from</span> a <span style="color:blue;">in</span> db.customer</p>
<p><span style="color:blue;">where</span> a.ID.Contains(param)</p>
<p><span style="font-size:xx-small;"> <span style="color:blue;">select</span> a;</span></p>
<p></span></div>
</td>
<td width="190" valign="top">
<div><span style="font-size:xx-small;"><span style="color:blue;">Select</span>*</p>
<p><span style="color:#0000ff;">from</span> Customer</p>
<p><span style="font-size:xx-small;"><span style="color:#0000ff;">where</span> id=%param%;</span></p>
<p></span></div>
</td>
</tr>
</tbody>
</table>
<p>it look longer than SQL, but you don’t forget when you do binding in .net project you still need write very very long ADO.NET statement. Compare to ADO.NET, LINQ(actually also part of ADO.NET) is simply and easy, just 3 sentence to create bindable query.</p>
<p>So Far, I just know this method to do wildcard search, any better suggestion?</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[When the increment is happening?]]></title>
<link>http://halwagy.wordpress.com/2009/08/20/when-the-increment-is-happening/</link>
<pubDate>Thu, 20 Aug 2009 13:10:48 +0000</pubDate>
<dc:creator>Ahmed</dc:creator>
<guid>http://halwagy.wordpress.com/2009/08/20/when-the-increment-is-happening/</guid>
<description><![CDATA[In my last post when I linked to a very interesting article on Eric Lippert&#8217;s blog. Now I want]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>
In my last <a href="http://halwagy.wordpress.com/2009/08/11/operators-precednce-vs-the-order-of-evaluation/">post</a> when I linked<br />
to a very <a href="http://blogs.msdn.com/ericlippert/archive/2009/08/10/precedence-vs-order-redux.aspx">interesting article</a> on Eric Lippert&#8217;s blog.<br />
Now I want to follow up on the subject of the post increment (++) operator.
</p>
<p>
Personally I used to think the the post increment operator will increment the value of its operand at the very end of the current<br />
statement (i.e. just before the terminating &#8220;;&#8221;). So according to my understanding, this expression (x+(y++)+y) would evaluate to 0&#8211;<br />
of course of both x and y were initialized to 0.
</p>
<p>
If you tried this example in the C# compiler you would find that the result of<br />
the expression is 1! (yes not 0 :S). Obviously I was wrong! Here&#8217;s how I thought the sequence of evaluating this expression (z = x+(y++)+y;)<br />
would go: First, x is added to y and the result is stored somewhere (a for example)<br />
	Second, the result of (#First) will be added to y again (note: y here is still 0, the increment didn&#8217;t happen yet)<br />
		and the result of this evaluation is stored somewhere (b for example)<br />
	Third, the assignment will happen; assigning the result of (#second &#8220;b&#8221;) to whatever on the left side of the &#8220;=&#8221; operator.<br />
	Fourth: Now (and only now) increment y. y = 1 now.
</p>
<p>
If this is right, I would get 0 as a result of Console.WriteLine(z); but it is NOT. This flow of evaluation is not correct.<br />
My understanding of the<br />
post increment operator is not right! (I&#8217;m doomed, eh!?).
</p>
<p>
So I checked up the c# documentation, still couldn&#8217;t find any specific statement<br />
about when exactly the increment happens. After an hour on the internet, I turned to my favorite site, my <a href="http://www.hanselman.com/blog/TheDeveloperTheoryOfTheThirdPlace.aspx"><br />
third place</a> now, Stackoverflow.com.
</p>
<p>
I logged in and posted a <a href="http://stackoverflow.com/questions/1260227/int-arr0-int-value-arrarr0-value-1">question</a>.<br />
Go ahead click the link and check the accepted answer, if you&#8217;re lazy, here&#8217;s my summary of the answer.
</p>
<p>
First you have to know that the ++ operator has an operation to perform with a specified precedence and a SIDE EFFECT. In short, the ++<br />
operator has the higher precednce than (* + &#8211; /). See the <a href="http://msdn.microsoft.com/en-us/library/aa691323(VS.71).aspx">specs</a><br />
This means that the operator will execute instantly! Yes Instantly! So the increment will be the first thing to happen (even if it&#8217;s<br />
post increment or pre-increment). The difference between pre and post comes from the side effect. When post incrementing the old value is<br />
stored, then the increment happens (i.e. the value of the variable increments),<br />
and the value that&#8217;s used to continue evaluating the expression is the (yeah, you guessed it) old value.
</p>
<p>
So to get back to the example (z = z +(y++) +y;), the order of evaluating this expression would be as follows: </p>
<ol>
<li> Store the value of y somwhere -say a. a now = 0. </li>
<li>Increment y (remember the increment has the highest precednece). </li>
<li> Add x to the value of a(which is the old value of y; that&#8217;s the side effect part of the operator) and save the result of<br />
the addition somewhere (say b). now b = 0; </li>
<li> Add the value of b to the value of y (what&#8217;s the value of y now? yes you&#8217;re right, it&#8217;s 1), and store the result somewhere<br />
say c. say now = 1. </li>
<li> Assign the value of c to z. z now = 1. </li>
</ol>
<p>
As you can see, the increment happens instantly. And its side effect forces the use of the old value of the incremented variable<br />
for evaluating the very next part of the expression. After that when trying to dereference the incremented value and get its value,<br />
you will actually get the incremented value.
</p>
<p><b><br />
Makes perfect sense to me now. What about you dear reader?<br />
<b></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Building an ASP.Net application with C# and Entity Framework]]></title>
<link>http://dotnetstories.wordpress.com/2009/06/27/building-an-asp-net-application-with-c-and-entity-framework/</link>
<pubDate>Sat, 27 Jun 2009 19:31:49 +0000</pubDate>
<dc:creator>fofo</dc:creator>
<guid>http://dotnetstories.wordpress.com/2009/06/27/building-an-asp-net-application-with-c-and-entity-framework/</guid>
<description><![CDATA[In this post I will show you a step by step example on how to build an ASP.NET application with C# a]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In this post I will show you a step by step example on how to build an ASP.NET application with C# and Entity Framework. First let&#8217;s try to define what EF is and why it is going to help us to create easily data-centric applications.Entity Framework is an object-relational mapping (ORM) framework for the .NET Framework.EF addresses the problem of <a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch" target="_blank">Object-relational impedance mismatch</a>. I will not be talking about that mismatch because it is well documented in many sites on the Internet. Through that framework we can program against a conceptual application model instead of programming directly against a relational schema-model. By doing so we can decrease the amount of code we do write to access a data storage and thus decrease maintenance time.</p>
<p>ADO.NET Entity Framework (EF) is included with .NET Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1</p>
<p>So you must donwload and have this software installed if you want to follow along.</p>
<p>It is not going to be a very difficult example. I will just bring data from a entity model to a gridview control and then give the user a way to filter that data.</p>
<p>There are many new enhancements regarding EF in VS 2010 and .Net .4.0 framework. I will not be talking about that since these enhancements are brand new and I am currently looking into them. I will just mention model-first development. This feature allows you to create your entity data model from scratch and then generate a database from it!!! We will do the opposite in this example.</p>
<p>Obviously for this example we will need a database. I will use the Pubs database. This is a well known database and many people are familiar with its schema.You can download the Pubs database from this <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&#38;DisplayLang=en" target="_blank">link</a>. If you need some help on how to install the database have a look <a href="http://www.codeproject.com/KB/database/InstallingNorthwindAndPub.aspx" target="_blank">here</a> .</p>
<p>I have installed SQL Server 2008 Standard edition in my PC. SQL Server 2008/2005 Express editions will work just fine.You can download SQL Server 2008 Express edition from this <a href="http://www.microsoft.com/express/sql/register/" target="_blank">link</a>. I have attached the Pubs database in my local instance of the SQL Server.</p>
<p>Let&#8217;s start out project.</p>
<p>1) Launch Visual studio 2008</p>
<p>2) Create a new Project and from the available templates choose &#8220;ASP.Net web application&#8221;</p>
<p>3) Choose C# as your language of development and save your project in your hard drive with a name e.g &#8220;EFWebApplication&#8221; and click &#8220;OK&#8221;.</p>
<p>4) Click on the Solutions Explorer and open the <strong>Default.aspx</strong> page.</p>
<p>5) From the Toolbox drag and drop on the page , a <strong>Gridview</strong> control, a <strong>Textbox</strong> control and <strong>Button</strong> control. Leave the default names.</p>
<p>6) From the Toolbox drag and drop a <strong>EntityDatasource</strong> control on the page.</p>
<p>7) Choose the data source of the gridview control to be the <strong>EntityDatasource1</strong> object.</p>
<p> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> Now we are ready to create our entity model. Right &#8211; click on your project from the <strong>Solutions Explorer</strong> window and <strong>Add a new Item</strong>. From the availble templates choose <strong>ADO.NET Entity data model</strong>. Give it the name <strong>Pubs.edmx </strong>and click the <strong>Add</strong> button.</p>
<p>9) In the <strong>Entity data model wizard </strong>window choose <strong>Generate from database</strong> and click <strong>Next</strong> .</p>
<p>10) Click <strong>New Connection</strong>, choose the <strong>Server name</strong> and from the databases your <strong>Pubs</strong> database is attached and then connect to the <strong>Pubs</strong> database and test your connection and click <strong>OK</strong></p>
<p>11) If you notice you will see that there is something called <strong>Entity connection string</strong> and looks like this</p>
<blockquote><p>metadata=res://*/Pubs.csdl&#124;res://*/Pubs.ssdl&#124;res://*/Pubs.msl;provider=System.Data.SqlClient;provider connection string=&#8221;Data Source=FOFO-PC;Initial Catalog=pubs;Integrated Security=True&#8221;</p></blockquote>
<p>The connection string used by the Entity Framework contains not only the database connection string, but a metadata parameter with pointers to three mapping files separated by a pipe character.These mapping files will be generated when we finish this wizard.</p>
<p>12) Click Next on your wizard window and from the databases objects available choose <strong>Tables</strong> and more specifically the <strong>Titles</strong>, <strong>Authors</strong> and <strong>TitleAuthor</strong> tables. Leave the Model namespace as <strong>pubsModel</strong> and click <strong>Finish</strong>.</p>
<p>13) Our new <strong>Pubs.edmx</strong> file called is created and all the entities are generated which are basically classes derived from the data model . Have a look at the picture below to see the Entity model in the Designer window. You can zoom in and zoom out using the appropriate buttons.</p>
<p><a href="http://dotnetstories.wordpress.com/files/2009/06/pubsedmx.jpg"><img class="aligncenter size-full wp-image-1020" title="pubsedmx" src="http://dotnetstories.wordpress.com/files/2009/06/pubsedmx.jpg" alt="pubsedmx" width="460" height="287" /></a></p>
<p>14) Have a look at the Mapping details of each entity type (Authors, Titles,  TitleAuthor). You can change if you want the property names for a particular entity type. For example you can change <strong>au_lname</strong> to <strong>lastname</strong> of the Authors entity type. You can also change the names of the entity types and singularise them in a way so they resemble more like a class name. Change <strong>Authors</strong> to <strong>Author</strong> and <strong>Titles</strong> to <strong>Title</strong> from the Designer.</p>
<p>15) Go to your <strong>default.aspx</strong> page and click on the EntityDatasource object and hit the option <strong>Configure Data Source</strong>. In the window that appears choose <strong>Named Connection</strong> and select the <strong>PubsEntities</strong> that will apear in the drop-down and hit the <strong>Next</strong> button.</p>
<p><a href="http://dotnetstories.wordpress.com/files/2009/06/pubsef-1.jpg"><img class="aligncenter size-full wp-image-1021" title="pubsef-1" src="http://dotnetstories.wordpress.com/files/2009/06/pubsef-1.jpg" alt="pubsef-1" width="460" height="287" /></a></p>
<p>16) In the next step from the EntitySetName select <strong>authors</strong>. Select all fields and and enable automatic inserts,updates,deletes and hit the <strong>Finish</strong> button.</p>
<p><a href="http://dotnetstories.wordpress.com/files/2009/06/pubsef-2.jpg"><img class="aligncenter size-full wp-image-1022" title="pubsef-2" src="http://dotnetstories.wordpress.com/files/2009/06/pubsef-2.jpg" alt="pubsef-2" width="460" height="287" /></a></p>
<p>17) In your gridview control enable paging,sorting,editing,deleting and selection.</p>
<p><a href="http://dotnetstories.wordpress.com/files/2009/06/pubsef-3.jpg"><img class="aligncenter size-full wp-image-1023" title="pubsef-3" src="http://dotnetstories.wordpress.com/files/2009/06/pubsef-3.jpg" alt="pubsef-3" width="460" height="287" /></a></p>
<p>18) Build and run your application and see the records in your web page. Try to sort,edit, delete records. Well done!!!!</p>
<p>19) Let&#8217;s give the ability to the user to apply a filter to the data by typing something to the textbox and return only the relevant data.Choose your <strong>EntityDatasource</strong> object and from the <strong>Properties</strong> window select  <strong>Where. </strong>Click on the &#8220;&#8230;&#8221; to launch the Expression editor window.</p>
<p>20) We will create an expression to use it as a filter(e.g filter the records by city name). The expression could be something like this</p>
<p><strong>it.city=@city OR @city IS NULL</strong></p>
<p>This expression above is written in Entity SQL which is T-SQL like syntax.</p>
<p><strong>Click the Add Parameter</strong> button and under name write &#8220;city&#8221; and the value will be a control, so from the <strong>Parameter Source</strong> select <strong>Control</strong> and from the <strong>ControlID</strong> your textbox control (e.g TextBox1)</p>
<p>Go to show advanced properties and in the &#8220;Type&#8221; field choose <strong>String</strong>.  Your settings should be like this:</p>
<p><a href="http://dotnetstories.wordpress.com/files/2009/06/pubsef-4jpg.jpg"><img class="aligncenter size-full wp-image-1024" title="pubsef-4jpg" src="http://dotnetstories.wordpress.com/files/2009/06/pubsef-4jpg.jpg" alt="pubsef-4jpg" width="460" height="416" /></a></p>
<p>21) Hit the <strong>OK</strong> button to close the <strong>Expression Editor</strong> window. Hit F5 to run your application. In the textbox type</p>
<p>&#8220;Oakland&#8221; and hit the button control. See the filtered results. That is all!!!! We did that without writing a single line of code.</p>
<p>If you need the source code for this example, just leave a comment and I will email it to you as soon as possible.</p>
<p>Hope it helps!!!</p>
<p style="text-align:left;"><a href="http://www.facebook.com/sharer.php?u=http://dotnetstories.wordpress.com/2009/06/27/building-an-asp-net-application-with-c-and-entity-framework/" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb201m05.png" alt="Add to Facebook" /></a><a href="http://www.newsvine.com/_wine/save?u=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;h=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb202m05.png" alt="Add to Newsvine" /></a><a href="http://digg.com/submit?phase=2&#38;url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;title=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb203m05.png" alt="Add to Digg" /></a><a href="http://del.icio.us/post?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;title=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb204m05.png" alt="Add to Del.icio.us" /></a><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;title=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb205m05.png" alt="Add to Stumbleupon" /></a><a href="http://reddit.com/submit?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;title=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb206m05.png" alt="Add to Reddit" /></a><a href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&#38;Description=&#38;Url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;Title=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb207m05.png" alt="Add to Blinklist" /></a><a href="http://ma.gnolia.com/bookmarklet/add?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;title=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb208m05.png" alt="Add to Ma.gnolia" /></a><a href="http://www.technorati.com/faves?add=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb209m05.png" alt="Add to Technorati" /></a><a href="http://www.furl.net/storeIt.jsp?u=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F27%2Fbuilding-an-asp-net-application-with-c-and-entity-framework%2F&#38;t=Building%20an%20ASP.Net%20application%20with%20C%23%20and%20Entity%20Framework" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb210m05.png" alt="Add to Furl" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Object Oriented Programming Concepts with C#3.0]]></title>
<link>http://dotnetstories.wordpress.com/2009/06/21/object-oriented-programming-concepts-with-c3-0/</link>
<pubDate>Sun, 21 Jun 2009 20:35:54 +0000</pubDate>
<dc:creator>fofo</dc:creator>
<guid>http://dotnetstories.wordpress.com/2009/06/21/object-oriented-programming-concepts-with-c3-0/</guid>
<description><![CDATA[In this blog I try to write about all the latest issues regarding the .Net platform. But in this pos]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In this blog I try to write about all the latest issues regarding the .Net platform.</p>
<p>But in this post I will try to explain thoroughly the Object Oriented programming model-paradigm.</p>
<p>Speaking from my experience so far, I have identified that the lack of knowledge of basic-advanced <a href="http://en.wikipedia.org/wiki/Object-oriented_programming" target="_blank">OOP</a> concepts is the main reason that people fail to grasp how to design and implement a .Net application.</p>
<p>Dragging and dropping controls from the Toolbox to an .aspx page and connecting to a database does not mean we know OOP.</p>
<p>Unless you do have a good knowledge of OOP concepts , there is a pretty good chance you will fail in your projects.</p>
<p>In this very long post I will try to explain in details the OOP concepts using C# 3.0 in an ASP.NET application.</p>
<p>Many good people have created very good tutorials which are available on the internet about OOP , but I thought I will have a go myself.Along the way I will show you tips and tricks with <em>do&#8217;s</em> and <em>dont&#8217;s</em>.</p>
<p>Well, some people think, <em>&#8220;I do not need classes and object oriented programming to develop my applications&#8221;</em>.</p>
<p>That is a true. However if you want to create .NET applications you must use objects. Even if you fail to realise it, everything in .Net is an object. When you open a connection to a database that &#8220;connection&#8221; is an object. To put it in one line:</p>
<p><strong>Each class in C# is automatically (implicitly) inherited from the Object class.</strong></p>
<p>I have been posting about C# 3.0 new features in other posts and there will be links where required.</p>
<p>Some of the topics-concepts, I will try to cover are:</p>
<ul>
<li>Classes</li>
<li>Properties</li>
<li>Methods</li>
<li>Fields</li>
<li>Members</li>
<li>Enums</li>
<li>Casting</li>
<li>Structures</li>
<li>Abstraction</li>
<li>Encapsulation</li>
<li>Interfaces</li>
<li>Static classes</li>
<li>Constructors</li>
<li>Method overloading</li>
<li>Inheritance</li>
<li>Overriding methods</li>
<li>Virtual methods</li>
<li>Abstract classes</li>
<li>Polymorphism</li>
<li>Delegates</li>
<li>Events</li>
<li>Assemblies</li>
<li>Namespaces</li>
</ul>
<p>and many more&#8230;</p>
<p>Before jumping into bits of code and create our step by step example, I must explain some basic concepts regarding  OOP.</p>
<ul>
<li><span style="text-decoration:underline;"><strong> What is a class?</strong></span></li>
</ul>
<p>A class is an abstract concept. It is a blueprint. Try to think of a class as e.g  the blueprints of a <span style="text-decoration:underline;"><em>car</em></span><em> </em>in the real world.</p>
<p>The designers of auto mobiles sit in front of their computer (or use paper and pencil) and describe exactly the parts of the auto mobile. They describe how these parts interact, the colour of the car, the height of the car, the size of the engine, the acceleration of the car, if the car has air-conditioning system installed.</p>
<p>Then the mechanics that observe the production line, make sure that the cars built (the actual cars) follow the blueprints outlined in the design stage of building a car.</p>
<p>So a class is a way of describing real world entities. It is the code definition for objects.</p>
<p>The class is the <strong>fundamental building block of code</strong> when creating object-oriented software. A class describes in abstract (in theory) all of the characteristics and behaviour of an object.</p>
<p>The object on the other hand is <strong>the instance of a class</strong>. The real thing, if you excuse my slang&#8230;</p>
<p>So we must start thinking about modelling our applications in terms of objects.</p>
<p>When someone, who has hired us to implement a web site-commerce site for his business, he could outline his view of the web site in plain words&#8230;</p>
<p>&#8221; I would like to have a site where I can keep track of the sales-orders that were placed through the site. I also would like to be able to see the customer details and manage my employees details&#8221;,</p>
<p>Then you must think in terms of <strong>Orders,Customer,Employee classes</strong>-objects for this particular scenario.</p>
<p>This is a first attempt of <strong>Abstraction</strong> for the scenario above.</p>
<p><strong>Abstraction</strong> is the process of representing simplified versions of real-world objects in your classes and objects.</p>
<p>Programming with the OOP paradigm is to decide what a class should represent and breaking down your code into a group of interrelated classes.</p>
<p><span style="text-decoration:underline;"><strong>Members of a class</strong></span></p>
<p>The first thing after finalising the class names is to identify the members of a class.</p>
<p>I will talk about <strong>Properties</strong>, <strong>methods</strong> and <strong>event</strong>s. As we go on I will talk in greater detail about class members.</p>
<ul>
<li><span style="text-decoration:underline;">What is a property ?</span></li>
</ul>
<p>A Property allows you to access an object’s data. Properties can be read-only, so they cannot be modified, while others can be changed. A Property defines the state of an object.It describes its individual data or unique configuration.</p>
<ul>
<li><span style="text-decoration:underline;">What is a method ?</span></li>
</ul>
<p>A method allows you to perform an action with an object. Unlike properties, methods are used for actions that perform a distinct task and may  change the object’s state-property.</p>
<ul>
<li><span style="text-decoration:underline;">What is an event ?</span></li>
</ul>
<p>An event provides notification that something has happened. Objects can fire events to trigger the code we have placed in the event-handling routines-methods. For example, if a user clicks on a button,the button object fires a <strong>Click</strong> event, which our code can react to.</p>
<p>Methods, properties and events can be considered as the <strong>public interface </strong>of a class.</p>
<p>Now we are ready to move on and practice what we have been saying so far.</p>
<p>I assume that people who will read this post, have some experience with C# and Visual studio as a development platform.</p>
<p>I will use Visual Studio 2008 Professional edition. People who have downloaded and installed Visual web developer 2008 can also follow these examples. You can download Visual Web Developer by clicking <a title="Visual web developer" href="http://www.asp.net/downloads/essential/" target="_blank">here</a> .</p>
<p>I will create an ASP.NET application. I will create a base class and then take it from there and try to highlight all the concepts mentioned above. The point of this example is not create super sophisticated classes and methods but to create a simple class with plain properties and methods.</p>
<p>1) Launch VS 2008</p>
<p>2) Go to File-&#62;New-&#62;Project</p>
<p>3) From the templates, choose ASP.NET web application. Make sure you select C# as the language of development</p>
<p>4) Give a name for your project. I name it &#8220;LearnCLass&#8221;. Click <strong>OK</strong> on the Templates window.</p>
<p>5) You will have 2 main files, <em><strong>Default.aspx</strong></em> and <em><strong>Default.aspx.cs</strong></em></p>
<p><span style="text-decoration:underline;"><strong>Building a basic class</strong></span></p>
<p>The class I will construct regards a <strong>Person</strong> class.This class can represent any person, e.g the customer of an e-commerce shop.The <strong>Person</strong> class will store the person&#8217;s data, and it will include the built-in functionality needed to generate a block of HTML that displays the person details on a web page. We will test this class with an ASP.NET page.<br />
Once you’ve defined a class, the first step is to add some basic data. The next example defines five member variables that store information about the person, namely, its name, surname, age, height,weight .</p>
<p>In your default.aspx.cs (code behind file) you have something like this:</p>
<blockquote><p>using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.UI;<br />
using System.Web.UI.WebControls;</p>
<p>namespace LearnCLass<br />
{<br />
public partial class _Default : System.Web.UI.Page<br />
{</p></blockquote>
<p>Then add the class definition</p>
<blockquote><p>public class Person<br />
{<br />
public string name;<br />
public string surname;<br />
public int age;<br />
public decimal height;<br />
public decimal weight;<br />
}</p></blockquote>
<p>Now we have the class definition we need to creating an object. We must use <strong>new</strong> keyword to do that. The<strong> new</strong> keyword instantiates the object, which means it creates a copy of the class in memory. If you define an object but don’t instantiate it, you’ll receive an error from the compiler.The members of a class (methods and properties) are accessed <strong>using dot &#8216;.&#8217; operator</strong> against the reference of the object.</p>
<p>In the Page _Load event handling routine type</p>
<blockquote><p>protected void Page_Load(object sender, EventArgs e)<br />
{<br />
Person mynewperson;<br />
mynewperson=new Person();<br />
mynewperson.name = &#8220;nikos&#8221;;<br />
mynewperson.surname = &#8220;kantzelis&#8221;;<br />
mynewperson.age = 31;<br />
mynewperson.weight = 88;<br />
mynewperson.height = 1.78M;<br />
Response.Write(mynewperson.name);<br />
}</p></blockquote>
<p>Run your application by hitting F5 from the keyboard and see the results.</p>
<p>What I am trying to highlight here, is how to create an object from a class.The bit that does it is this:</p>
<h4>Person mynewperson;<br />
mynewperson=new Person();</h4>
<p>One could write it in a single line</p>
<h4>Person mynewperson=new Person();</h4>
<p>But the snippet of code inside the Page_Load method is not very well thought.</p>
<p>One could write <strong>mynewperson.age = -2;</strong></p>
<p>We would not like to have the code above. The reason the code above works is that the properties of the Person class,</p>
<p>are all <strong>public</strong>. That is the <strong>visibility</strong> of the properties is public. Another more technical word for visibility is <em>scope</em>.</p>
<p>This is very important concept and one must understand.</p>
<p>The main accessibility keywords are</p>
<p><strong>public</strong> -Members defined as public can be accessed by any other class<br />
<strong>private -</strong> Members defined as private can be accessed only by code procedures inside the current class<br />
<strong>internal</strong> &#8211; Members defined as internal can be accessed by code procedures in any of the classes in the current assembly (the compiled file)<br />
<strong>protected</strong> Members defined as protected can be accessed by code procedures in the current class or by any class<br />
that inherits from this class</p>
<p>So by having in our example the variables defined as <em>public</em>, this means that any other class or method of another class has direct access to those variables-properties.</p>
<p>We must not design classes like that. In order to have useful classes we must have a way to protect the data within them. This is called, <strong>Encapsulation</strong>. Encapsulation is is the hiding of the internal mechanisms and data of a class behind a defined interface.Other classes , if they need to &#8220;talk&#8221; &#8211; interact with a specific class, they can do so by just knowing its interface. Let me try to explain this better with my car analogy example. When you try to change the gear in your car, imagine the gear system as class or a component, the gear system interacts with another system that commands the car to slow down or accelerate. The gear system does not have to know how it is done, just how to interacts with it.</p>
<p>So let&#8217;s change public to private.</p>
<blockquote><p>private string name;<br />
private string surname;<br />
private int age;<br />
private decimal height;<br />
private decimal weight;</p></blockquote>
<p>Let&#8217;s run the code again. We get the following error. I am sure you get what is going on here. There is no variable name still &#8220;alive-visible&#8221; when we call it in the Page_Load event handling routine.</p>
<h4>Error    1    &#8217;LearnCLass._Default.Person.name&#8217; is inaccessible due to its protection level    C:\Users\fofo\Desktop\webapps\LearnCLass\LearnCLass\Default.aspx.cs    24    25    LearnCLass</h4>
<p>In general objects are automatically released when the appropriate variable goes out of scope. Objects are also released when your application ends. That means that their memory is reclaimed. In the managed applications, the <a href="http://dotnetstories.wordpress.com/2008/04/08/what-is-the-net-framework/" target="_blank">CLR </a>uses a service (garbage collector) that periodically scans for released objects and reclaims the memory they hold.</p>
<p>So , you must be thinking that we have not accomplished anything yet. The truth is that we have not finished yet.</p>
<p>We must write <em><strong>property accessors </strong></em>for the member variables<em><strong>.</strong></em></p>
<p>For the name member variable we have</p>
<blockquote><p>public string Name<br />
{<br />
get<br />
{<br />
return name;<br />
}</p>
<p>set<br />
{<br />
name = value;<br />
}</p>
<p>}</p></blockquote>
<p>With C# 3.0 we had a new feature that is called <strong>Auto-implemented</strong> properties. Have a look <a href="http://dotnetstories.wordpress.com/2008/06/23/c-30-new-language-features-auto-implemented-properties/" target="_blank">here</a> in one of my past posts to find out more about that.Basically with auto implemented properties,  there is no need to implement a private field to store the value.</p>
<p>So we could write the code above like this</p>
<h4>public string Name { get; set; }</h4>
<p>much easier isn&#8217;t it?</p>
<p>We can do that for all property accessors if no no additional logic is required.</p>
<p>So we have</p>
<h4>public string Name { get; set; }<br />
public string Surname { get; set; }</h4>
<p>that means that we can comment out the following lines from our class declaration.</p>
<p><strong>//private string name;<br />
//private string surname;</strong></p>
<p>but for the Age,Height,Weight member variables we require some additional logic for the property accessors.</p>
<p>Just for this example let&#8217;s just assume that a person&#8217;s age must between 1 and 100, his height from 1 to 2.40 and his weight from 30 to 240.</p>
<blockquote><p>public int Age<br />
{<br />
get<br />
{<br />
return age;<br />
}</p>
<p>set<br />
{<br />
if (value &#60; 1 &#124;&#124; value &#62; 100)<br />
{<br />
throw new Exception(&#8220;Invalid age&#8221;);<br />
}</p>
<p>age = value;<br />
}</p>
<p>}</p>
<p>public decimal Height<br />
{<br />
get<br />
{<br />
return height;<br />
}</p>
<p>set<br />
{<br />
if (value &#60; 1.00M &#124;&#124; value &#62; 2.40M )<br />
{<br />
throw new Exception(&#8220;Invalid height&#8221;);<br />
}</p>
<p>height = value;<br />
}</p>
<p>}</p>
<p>public decimal Weight<br />
{<br />
get<br />
{<br />
return weight;<br />
}</p>
<p>set<br />
{<br />
if (value &#60; 30 &#124;&#124; value &#62; 240)<br />
{<br />
throw new Exception(&#8220;Invalid weight&#8221;);<br />
}</p>
<p>weight = value;<br />
}</p>
<p>}</p></blockquote>
<p>When trying to assign an invalidvalue, an exception is thrown by the class code.</p>
<p>Now let&#8217;s create a method for our Person Class.</p>
<p>We can create a very simple method like:</p>
<h4>public void Talk()</h4>
<p>{</p>
<p>// add logic later</p>
<p>}</p>
<p>or we can add a method that returns something (it is not void) and can do something useful.</p>
<p>So we can have a method that calculates the age of the person in years. The method follows:</p>
<blockquote><p>public int CalculateAge(DateTime birthDate)<br />
{DateTime now = DateTime.Today;int years = now.Year &#8211; birthDate.Year;if (now.Month &#60; birthDate.Month &#124;&#124; (now.Month == birthDate.Month &#38;&#38; now.Day &#60; birthDate.Day))<br />
&#8211;years;return years;<br />
}</p></blockquote>
<p>It is not something difficult.  We should not focus on how the method does it, right now. Basically I am just using</p>
<p><strong>DateTime</strong> Class in the <strong>System namespace</strong>.</p>
<p>In your Page_Load event you can add to the code already there, the following bit</p>
<blockquote><p>string myDateTimeString;int res;myDateTimeString = &#8220;17 Feb,1977&#8243;;DateTime dt;<br />
dt = Convert.ToDateTime(myDateTimeString);<br />
res=mynewperson.CalculateAge(dt);Response.Write(res.ToString());</p></blockquote>
<p>Run your application and see the results.</p>
<p>The <strong>Person</strong> class so far:</p>
<blockquote><p>using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Web;<br />
using System.Web.UI;<br />
using System.Web.UI.WebControls;</p>
<p>namespace LearnCLass<br />
{<br />
public partial class _Default : System.Web.UI.Page<br />
{</p>
<p>public class Person<br />
{<br />
//private string name;<br />
//private string surname;<br />
private int age;<br />
private decimal height;<br />
private decimal weight;</p>
<p>public int Age<br />
{<br />
get<br />
{<br />
return age;<br />
}</p>
<p>set<br />
{<br />
if (value &#60; 1 &#124;&#124; value &#62; 100)<br />
{<br />
throw new Exception(&#8220;Invalid age&#8221;);<br />
}</p>
<p>age = value;<br />
}</p>
<p>}</p>
<p>public decimal Height<br />
{<br />
get<br />
{<br />
return height;<br />
}</p>
<p>set<br />
{<br />
if (value &#60; 1.00M &#124;&#124; value &#62; 2.40M )<br />
{<br />
throw new Exception(&#8220;Invalid height&#8221;);<br />
}</p>
<p>height = value;<br />
}</p>
<p>}</p>
<p>public decimal Weight<br />
{<br />
get<br />
{<br />
return weight;<br />
}</p>
<p>set<br />
{<br />
if (value &#60; 30 &#124;&#124; value &#62; 240)<br />
{<br />
throw new Exception(&#8220;Invalid weight&#8221;);<br />
}</p>
<p>weight = value;<br />
}</p>
<p>}</p>
<p>public string Name { get; set; }<br />
public string Surname { get; set; }</p>
<p>public int CalculateAge(DateTime birthDate)<br />
{</p>
<p>DateTime now = DateTime.Today;</p>
<p>int years = now.Year &#8211; birthDate.Year;</p>
<p>if (now.Month &#60; birthDate.Month &#124;&#124; (now.Month == birthDate.Month &#38;&#38; now.Day &#60; birthDate.Day))<br />
&#8211;years;</p>
<p>return years;<br />
}</p>
<p>public void Talk()<br />
{<br />
//add logic later<br />
}</p>
<p>}</p>
<p>protected void Page_Load(object sender, EventArgs e)<br />
{<br />
Person mynewperson=new Person();<br />
mynewperson.Name = &#8220;nikos&#8221;;<br />
mynewperson.Surname = &#8220;kantzelis&#8221;;<br />
mynewperson.Age = 22;<br />
mynewperson.Weight = 88;<br />
mynewperson.Height = 1.78M;<br />
Response.Write(mynewperson.Name);<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
Response.Write(mynewperson.Surname);<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
Response.Write(mynewperson.Age);<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
Response.Write(mynewperson.Height);<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
Response.Write(mynewperson.Weight);<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
mynewperson.Talk();</p>
<p>string myDateTimeString;</p>
<p>int res;</p>
<p>myDateTimeString = &#8220;17 Feb,1977&#8243;;</p>
<p>DateTime dt;<br />
dt = Convert.ToDateTime(myDateTimeString);<br />
res=mynewperson.CalculateAge(dt);</p>
<p>Response.Write(res.ToString());</p>
<p>mynewperson.Talk();</p>
<p>}<br />
}<br />
}</p></blockquote>
<p>When we create our Person object,</p>
<h4>Person mynewperson=new Person();</h4>
<p>you might think that we have here is a method call.When an instance of a class is created the C# system makes a call to a <strong>constructor</strong> method in that class. A constructor is a function with the same name as that of the class. Every single class must have a constructor method.It is called when we write the <strong>new</strong> keyword. Even If we do not provide a constructor method, the compiler creates a default one,without any parameters.</p>
<p>So in our case is:</p>
<blockquote><p>public Person()</p>
<p>{</p>
<p>}</p></blockquote>
<p>We often need to <strong>overload</strong> our default constructors. Let me explain what <strong>overload</strong> is.</p>
<p>It is possible to have more than one method with the same name and return type but with a different number and type of arguments-parameters. The compiler knows every time which method to call by looking at the number of the arguments. I will explain more about overloading later on.</p>
<p>Sometimes it is better to send some information to the class upfront so it is available as soon as it is constructed. So let&#8217;s overload the default constructor.</p>
<blockquote><p>public Person( string thename, string thesurname, int theage)<br />
{<br />
Name = thename;<br />
Surname=thesurname;<br />
Age = theage;<br />
}</p></blockquote>
<p>We can also have a destructor.<strong>Destructors</strong> are just the opposite of constructors.</p>
<p>It has the same name as the containing class but prefixes it with the ~ (tilde) sign.</p>
<p>It is called automatically when the object is about to be destructed (when <a href="http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)" target="_blank">garbage collector</a> is about to destroy your object).</p>
<p>It has no return type just as the constructor does not have one as well.<br />
We declare the destructor in our case like</p>
<blockquote><p>~Person()<br />
{<br />
// place our e.g resource freeing code here<br />
}</p></blockquote>
<p>What really happens is that the C# compiler internally converts the destructor to the <strong>Finalize()</strong> method.</p>
<p>The <strong>Object</strong> class is the parent of all objects in .Net.It contains a method called <strong>Finalize()</strong>.<br />
This method is  be called when your object is garbage collected . One can override this method and put here code for freeing resources that you reserved when using the object.</p>
<blockquote><p>protected override void Finalize()<br />
{<br />
try<br />
{</p>
<p>// put some code here<br />
}<br />
finally<br />
{<br />
base.Finalize();<br />
}<br />
}</p></blockquote>
<p>Do not worry about the <strong>override</strong> keyword. I will explain it later on.</p>
<p>Many people ask me about enums and structures and what they are and how we can use them.</p>
<p><span style="text-decoration:underline;"><strong>What is enum?</strong></span></p>
<p>An enumeration is a group of related constants. Each constant is given a descriptive name.<br />
Every enumerated value corresponds to a preset integer.</p>
<p>Sometimes we want to hold a range of particular values or states. This is a perfect place to use enums.</p>
<p>In our example we could have something like</p>
<blockquote><p>public enum PersonState<br />
{<br />
Married = 1,<br />
Widoewed = 2,<br />
Single = 3,<br />
Divorced = 4<br />
}</p></blockquote>
<p>And then call it from our Page_load event</p>
<blockquote><p>PersonState personstate;</p>
<p>personstate =PersonState.Married;<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
Response.Write(personstate);</p></blockquote>
<p>C# compiler will  represent these states as particular numeric values . But it will do so behind the curtains.</p>
<p>So I can use the enum name values and have more readable code. The concept of enumerated values is extremely important, because the .NET class library uses it extensively.</p>
<p><span style="text-decoration:underline;"><strong>What is a structure ?</strong></span></p>
<p>Structures are lightweight objects. Structures are very similar to classes in C#.</p>
<p>Basically they can hold a collection of different things about a particular item.</p>
<p>They are denoted in C# by the <strong>struct</strong> keyword. In our example we could have a structure like this</p>
<blockquote><p>struct NewPerson<br />
{<br />
public string name;<br />
public string surname;<br />
public int age;<br />
public decimal height;<br />
public decimal weight;</p>
<p>}</p></blockquote>
<p>In the Page_Load event routine we can have</p>
<blockquote><p>NewPerson myperson;</p>
<p>myperson.name = &#8220;John&#8221;;</p>
<p>Response.Write(myperson.name);</p></blockquote>
<p>As you notice there is no need for the <strong>new</strong> keyword.</p>
<p>There is a key difference between objects and structures. Structures are managed in terms of value while objects are managed in terms of reference.</p>
<p>A reference holds the physical address of where the data is stored in memory. So it points to the data. It is not the actual data. On the other hand structure variables hold the actual data.</p>
<p>There are some limitations with structures and even if they have their place when we design a software component, they can never be used to replace a class type.</p>
<p>A structure  for example can neither inherit another class, nor can they be inherited. A structure can implement interfaces.</p>
<p>A common place where we find structures  are Net framework types like System.Int32, System.Double , System.Boolean.If you want to check it out yourselves just place the pointer of your mouse on an<strong> int </strong>declaration and right click. From the right-menu click on the &#8220;Go To Definition &#8220;. Then you will see the definitions. See the picture below.</p>
<div>
<table border="0" cellspacing="0" cellpadding="0" width="633">
<tbody>
<tr>
<td style="padding:0;" align="left" valign="top"></td>
</tr>
</tbody>
</table>
</div>
<p><img src="http://dotnetstories.wordpress.com/files/2009/06/gotodef.jpg" alt="go to def" /></p>
<p><span style="text-decoration:underline;"><strong><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">Inheritance<br />
</span></strong></span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">I know a lot people who use Inheritance in their applications without even realizing.</span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">If you look at the <strong>Default.aspx.cs</strong> you can see</span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"><strong><em>public partial class _Default : System.Web.UI.Page</em></strong></span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">In plain English , this means that every web page we create is a child of the <strong>Page </strong>class. Inheritance is a form of code reuse. It allows one class to acquire and extend the functionality of another class. There is no need to reinvent the wheel when other people have done this for you. Instead of that you have only to think about the peculiarities of the project at hand.</span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">Let&#8217;s assume that we need to create another class,called <strong>Student.</strong></span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">In this class we want to inherit the functionality of the Person class or base class.</span></p>
<h4><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"> class  Student : Person</span></h4>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">Then we want to extend the Parent class. We want to create a new simple method to calculate the total marks achieved by the student.</span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">The whole Student class follows. I have explained in detail properties and methods in previous paragraphs.<br />
</span></p>
<blockquote><p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">class  Student : Person<br />
{<br />
private int _marksEnglish;<br />
private int _marksLiterature;<br />
private int _marksIT;<br />
private int _marksMaths;<br />
private int marksTotal;</span></p>
<p>public int marksEnglish<br />
{<br />
get<br />
{<br />
return _marksEnglish;<br />
}<br />
set<br />
{<br />
if (value &#60; 0 &#124;&#124; value &#62; 20)<br />
{<br />
throw new Exception(&#8220;Invalid number&#8221;);<br />
}</p>
<p>_marksEnglish = value;<br />
}<br />
}<br />
public int marksLiterature<br />
{<br />
get<br />
{<br />
return _marksLiterature;<br />
}<br />
set<br />
{<br />
if (value &#60; 0 &#124;&#124; value &#62; 20)<br />
{<br />
throw new Exception(&#8220;Invalid number&#8221;);<br />
}<br />
_marksLiterature = value;<br />
}<br />
}</p>
<p>public int marksMaths<br />
{<br />
get<br />
{<br />
return _marksMaths;<br />
}<br />
set<br />
{<br />
if (value &#60; 0 &#124;&#124; value &#62; 20)<br />
{<br />
throw new Exception(&#8220;Invalid number&#8221;);<br />
}<br />
_marksMaths = value;<br />
}<br />
}</p>
<p>public int marksIT<br />
{<br />
get<br />
{<br />
return _marksIT;<br />
}<br />
set<br />
{<br />
if (value &#60; 0 &#124;&#124; value &#62; 20)<br />
{<br />
throw new Exception(&#8220;Invalid number&#8221;);<br />
}<br />
_marksIT = value;<br />
}<br />
}</p>
<p>public int CalculateTotalMarks()<br />
{</p>
<p>marksTotal = marksEnglish + marksLiterature + marksIT + marksMaths;</p>
<p>return marksTotal;<br />
}<br />
}</p></blockquote>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"><br />
</span><br />
<span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;">In our Page_Load event , we can create a new object of type Student.</span></p>
<blockquote><p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"> Student mystudent = new Student();<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
mystudent.Name=&#8221;fofo&#8221;;<br />
Response.Write(mystudent.Name);<br />
mystudent.marksEnglish = 12;<br />
mystudent.marksLiterature = 13;<br />
mystudent.marksIT = 18;</span><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"> </span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"> mystudent.marksMaths = 17;</span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"> mystudent.CalculateTotalMarks();</span></p>
<p><span style="font-size:12pt;line-height:115%;font-family:&#34;color:black;"><br />
Response.Write(mystudent.CalculateTotalMarks());</span></p></blockquote>
<p>If you pay attention even though we did not define the Name and Surname properties for the Student class, they are available to the class, since they are inherited. The same applies for the <strong>CalculateAge</strong> method.</p>
<p>Some things worth mentioning regarding inheritance are:</p>
<ul>
<li>C# allows only single class inheritance</li>
<li> Multiple inheritance of classes is not allowed in C#</li>
<li>The Object class defined in the <strong>System namespace</strong> is implicitly the ultimate base class of all the classes in C# and the .NET framework</li>
<li>A class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.</li>
</ul>
<p>Now, we know how to make a new class based on an existing one and extend it.If we want to change the behavior of a method in the base class in the child class we must override it.</p>
<p>Let&#8217;s create a new method in the base class (<strong>Person</strong>) that we want to override it later on the child class. It is just a method that calculates the pay of a person.</p>
<blockquote><p>public double CalculatePay(double hoursWorked, double wageperhour,double tax)<br />
{</p>
<p>return (hoursWorked * wageperhour * tax);<br />
}</p></blockquote>
<p>This method is inherited in the Student class. Let&#8217;s assume that we live in a fantastic world where student&#8217;s money is not taxed if the student worked less than 100 hours.</p>
<p>The first thing to do is to add the word <strong>virtual</strong> to the CalculatePay method.So we have:</p>
<blockquote><p>public <strong>virtual</strong> double CalculatePay(double hoursWorked, double wageperhour,double tax)<br />
{</p>
<p>return (hoursWorked * wageperhour * tax);<br />
}</p></blockquote>
<p>and then to use the word <strong>override</strong> in Student class CalculatePay method</p>
<blockquote><p>public <strong>override</strong> double CalculatePay(double hoursWorked, double wageperhour,double tax)<br />
{<br />
if (hoursWorked &#62; 100)<br />
{</p>
<p>return (hoursWorked * wageperhour * tax);<br />
}<br />
else<br />
{<br />
return (hoursWorked * wageperhour);</p>
<p>}<br />
}</p>
<p>From our Page_Load event we can call this</p>
<p>Response.Write(mystudent.CalculatePay(45, 4, 0.45));</p>
<p>By calling the line above the <strong>CalculatePay </strong>method of the student class will be invoked.This relationship between virtual  methods and the derived class methods that override them enables polymorphism.</p></blockquote>
<p>If we want to stop overriding a class we can use the special word <strong>sealed. </strong>This means that this class cannot be used as the basis for another class.</p>
<p>if you change the</p>
<p><strong>public class Person</strong> to <strong>public sealed class Person </strong></p>
<p>and run your application you will receive an error</p>
<p>&#8220;<strong>cannot derive from sealed type &#8216;LearnCLass._Default.Person</strong>&#8220;</p>
<p>Now it is time to see in greater detail <strong>method overloading</strong>.</p>
<p>In our Person class we can define a new method</p>
<blockquote><p>public string JoinNames(string name, string surname)<br />
{<br />
return name + &#8221; &#8221; + surname;<br />
}</p></blockquote>
<p>Now we could have a different implementation of the method above.</p>
<blockquote><p>public string JoinNames(string prefix, string name, string surname)<br />
{<br />
return prefix + &#8221; &#8221; + name + &#8221; &#8221; + surname;<br />
}</p></blockquote>
<p>In our Page_ Load event if we write the line:</p>
<h4>mynewperson.JoinNames(&#8220;Mr&#8221;,&#8221;nikos&#8221;, &#8220;kantzelis&#8221;)</h4>
<p>The compiler will not complain. It will know which method to invoke depending on the number of the parameters-arguments it &#8220;sees&#8221;.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms173152(VS.100).aspx">Polymorphism</a> (<span lang="en-us">from the Greek meaning               &#8220;having multiple forms&#8221;</span> &#8211; &#8220;Poly&#8221; means many and &#8220;morphy&#8221; means &#8220;shape&#8221;) can be achieved by overloading a method.</p>
<p><span style="text-decoration:underline;"><strong>What is a static class?</strong></span></p>
<p>In .NET we can  use some class members without creating an object first. These are called static members, and they’re accessed by class name. So far in the previous examples we have seen the static property <strong>DateTime.Now</strong> to retrieve a DateTime object that represents the current date and time. We didn&#8217; create a <strong>DateTime</strong> object first.</p>
<p>If we wanted to have a method that determines whether a person can hold a valid driving licence, the method would look like this.</p>
<blockquote><p>public bool AllowedToDrive(int age)<br />
{<br />
if (age &#62;= 18 &#124;&#124; age &#60;= 80)<br />
{<br />
return true;<br />
}<br />
else<br />
{<br />
return false;<br />
}</p>
<p>}</p></blockquote>
<p>The method above is a good candidate to become a static method.In order to do that, we just add the word <strong>static</strong></p>
<blockquote><p>public <strong>static </strong>bool AllowedToDrive(int age)<br />
{<br />
if (age &#62;= 18 &#124;&#124; age &#60;= 80)<br />
{<br />
return true;<br />
}<br />
else<br />
{<br />
return false;<br />
}</p>
<p>}</p></blockquote>
<p>In our Page_Load event routine,we can write</p>
<p><strong>Person.AllowedToDrive(22)</strong></p>
<p>As you see we do not need an object to invoke our method, just the class name.</p>
<p>So a static member is a member of the class and not a member of an instance of the class.</p>
<p>It takes some experience to determine which methods or classes. One common place where we find static classes and methods is the creation of libraries that provide general functionality, e.g find the square root of a number, find the perimeter of a circle.</p>
<p>The next thing to review is <strong>Interfaces</strong>. I will not cover Interfaces in detail because you can find another <a href="http://dotnetstories.wordpress.com/2008/07/22/interfaces-in-c/" target="_blank">post</a> of mine on Interfaces on this blog.</p>
<p>The Interface is basically a contract between a the Interface and a class. In the Interface we do not have implementation of properties of methods.</p>
<p>The class that implements the Interface or inherits from the Interface must implement the methods defined in the Interface.</p>
<p>A .NET interface is similar to an abstract class in the sense that it’s a kind of a template. More on abstract classes later.</p>
<p>If we define an interface like this</p>
<blockquote><p>interface IPerson<br />
{<br />
double DaysVacation(int yearsOfWork);<br />
}</p></blockquote>
<p>and if we say that the Person class implements the IPerson Interface</p>
<h4>class Person : IPerson</h4>
<p>the Person class must in its body implement the <em>DaysVacation(int yearsOfWork)</em> method.</p>
<blockquote><p>public double DaysVacation(int yearsOfWork)<br />
{</p>
<p>if (yearsOfWork &#62; 25)<br />
{<br />
return 25;<br />
}<br />
else if (yearsOfWork &#60; 25 &#38;&#38; yearsOfWork &#62; 20)<br />
{<br />
return 20;<br />
}<br />
else<br />
{<br />
return 10;<br />
}</p>
<p>}</p></blockquote>
<p><span style="text-decoration:underline;"><strong>What is an abstact class?</strong></span></p>
<p>If we need to provide common fields and members to all subclasses, we create an <strong>Abstract</strong> class. We can create an abstract class, with the use of the <strong>abstract</strong> keyword. Abstract classes cannot be instantiated. In our example if we decide that there are some things that an object of type <strong>Person</strong> must do, then we can make the class <strong>Person</strong> abstract and then get the clild classes to provide the implementation. I will create another class to demonstrate abstract classes, because we need to change los of code in the <strong>Person</strong> class  and I do not want to do that.</p>
<p>In abstract classes we can have abstract members and virtual members. An abstract member is not implemented in the base class and must be implemented in derived classes in order for the class to compile. A virtual member must be implemented in the base class, and if need be (optionally) overriden in the derived class if want the child method to do something different.</p>
<p>Let&#8217;s define our abstract <strong>Vehicle</strong> class.</p>
<blockquote><p>public abstract class Vehicle<br />
{</p>
<p>public string Model { get; set; }<br />
public string Color { get; set; }<br />
public int NumOfDoors { get; set; }<br />
public int NumoOfWheels { get; set; }</p>
<p>public Vehicle(string model, string color)<br />
{<br />
this.Color = color;<br />
this.Model = model;</p>
<p>}<br />
public abstract string Accelarate(int speed);</p>
<p>public virtual double CalculatePetrolCostPerDistance( double distance)</p>
<p>{<br />
double costperkilometer=0.25;<br />
double res;</p>
<p>res = distance * costperkilometer;</p>
<p>return res;<br />
}</p>
<p>}</p></blockquote>
<p>Now we can have another class<strong> Car</strong> that can inherit from the <strong>Vehicle</strong> class. The method <strong>Accelerate</strong> in the Vehicle class must be implemented in the child class.</p>
<blockquote><p>public class Car : Vehicle<br />
{</p>
<p>public Car(string model, string color): base(model,color)<br />
{<br />
//code to be added<br />
}</p>
<p>public override string Accelarate(int speed)<br />
{<br />
return &#8220;I can accelerate. My speed is right now:&#8221;+speed.ToString();<br />
}</p>
<p>public override double CalculatePetrolCostPerDistance(double distance)<br />
{<br />
double costperkilometer = 0.45;<br />
double res;</p>
<p>res = distance * costperkilometer;</p>
<p>return res;<br />
}</p>
<p>}</p></blockquote>
<p>We can create and use an object type Car in our Page_Load event handling routine</p>
<blockquote><p>Car mycar = new Car( &#8220;bmw&#8221;, &#8220;silver&#8221;);<br />
Response.Write(mycar.Accelarate(134));<br />
Response.Write(&#8220;&#60;/br&#62;&#8221;);<br />
Response.Write(&#8220;The cost is: &#8221; + mycar.CalculatePetrolCostPerDistance(125.5).ToString() +&#8221; euros&#8221;);</p></blockquote>
<p>In the child class I have implemented a simple version of the <strong>Accelarate</strong> method by using the <strong>override</strong> keyword and I chose to ovveride <strong>CalculatePetrolCostPerDistance. </strong>But If i did not need any different behaviour for the <strong>CalculatePetrolCostPerDistance </strong>then that would be ok, my class would compile just fine.</p>
<p>Abstract classes are a lot like interfaces, however abstract classes are different in that they contain fully implemented methods alongside the abstract ones.So we do not have to implement the same methods in each of the components that implement a particular interface. An abstract class can contain fields, constructors, or destructors and implement properties while an interface cannot.<br />
An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but <span style="text-decoration:underline;">only one</span> abstract class.</p>
<p><span style="text-decoration:underline;"><strong>What is a delegate?</strong></span></p>
<p>For more information on this topic have a look at this <a href="http://dotnetstories.wordpress.com/2008/07/22/how-to-use-net-delagates-and-event-handling-using-delagates/" target="_blank">post</a> of mine.</p>
<p><span style="text-decoration:underline;"><strong>What is Generics</strong></span> ?</p>
<p>Same applies here. I have another single post on <a href="http://dotnetstories.wordpress.com/2008/07/09/generics-in-c-20-and-limitations-of-arraylists/" target="_blank">Generics</a> and I do not see any point repeating myself.</p>
<p><span style="text-decoration:underline;"><strong>What is a namespace?</strong></span></p>
<p>In my solution in the <strong>Default.aspx.cs</strong> , I have the <strong>namespace LearnCLass</strong> namespace. All my classes and code is included in this namespace.</p>
<p>Namespaces are a logical way to group classes. Let me give you an example of what it means. It is a way that we can identify a class beyond doubt.</p>
<p>Imagine that you want to phone an old friend that you have lost track, so you can invite him to your wedding. So you phone the phone directory service.</p>
<p>Your friend&#8217;s name is <em>George Patouxas</em>. The operator lets you know that there are 100 people with this name coming up. Then you tell the operator that his mother&#8217;s name and father&#8217;s name are <em>Maria</em> and <em>John</em> respectively. BINGO!! The operator tells you there is only match. So in our example the <strong>LearnCLass.Person </strong>class resides in this specific namespace and if someone wants to use it, he can use the<strong> using LearnCLass.Person </strong>declaration<strong>.<br />
</strong></p>
<p>That is exactly why namespaces are for in .NET.  We try to group related classes in namespaces and all of them that reside in this particular namespace will be uniquely identified.</p>
<p>If I have a class called <strong>Calculate</strong> in my <strong>LearnClass</strong> namespace, then there will be no conflict if need be to use another component from a third party that has also a <strong>Calculate</strong> Class.</p>
<p>That <strong>Calculate</strong> class will reside in the <strong>AnotherNameSpace</strong> so there will be no conflict.</p>
<p>Please note that in the beginning of the Default.aspx.cs we import namespaces that we need to <strong>using System.Web.UI</strong>;</p>
<p><span style="text-decoration:underline;"><strong>Assemblies<br />
</strong></span></p>
<p>All .NET classes (built-in or custom made) are contained in assemblies. Assemblies are the physical files that contain compiled code. Assembly files have the extension .exe if they are stand-alone applications or .dll if they’re reusable components. Assemblies are a physical package for distributing code. Often, assemblies and namespaces have the same names. For example, you’ll find the namespace <strong>System.Web</strong> in the assembly file <strong>System.Web.dll</strong>.</p>
<p>But in many cases there is no direct mapping between assemblies and namespaces.</p>
<p><span style="text-decoration:underline;"><strong>What is Casting?</strong></span></p>
<p>When we talk about casting, we can think of this concept in terms of <em>narrowing</em> and <em>widening</em>. If you move a value from one type to another that <em>narrows</em> the value, it will ask you to explicitly do it yourself. When you move a value from one type to another by widening it, it does not complain.</p>
<p>By widening I mean that if I have the declaration:</p>
<blockquote>
<h4>int mynum=5;</h4>
<h4>float anothernum=mynum;</h4>
</blockquote>
<p>This will be fine because the floating point type can hold all the values supported by the integer type.</p>
<p>If I have this statement (narrowing)</p>
<blockquote>
<h4>double mynum = 3.5;<br />
float thenum = mynum;</h4>
</blockquote>
<p>the compiler will complain.</p>
<p><strong>Cannot implicitly convert type &#8216;double&#8217; to &#8216;float&#8217;. An explicit conversion exists (are you missing a cast?) </strong></p>
<p>The compiler is basically saying &#8220;Is there any chance you are discarding information?&#8221;</p>
<p>But you can cast the value by using this statement.</p>
<blockquote>
<h4>double mynum = 3.5;<br />
float thenum = (float)mynum;</h4>
</blockquote>
<p>This is an explicit conversion and I say in simple words to the compiler, that I take the responsibility for the possible data loss.</p>
<p>For reference types, if we have a situation like this, where the derived type (Student) is converted to base type (Person), we have imlicit conversion which is safe.</p>
<blockquote>
<h4>Student thestudent = new Student();</h4>
</blockquote>
<p>while if we type this:</p>
<blockquote>
<h4>Person theperson=new Person();</h4>
</blockquote>
<p>this will fail and we must explicitly cast it to the <strong>Student</strong> type, like this.</p>
<blockquote>
<h4>Person theperson=new Person();<br />
Student thestudent = (Student)theperson;</h4>
</blockquote>
<p>Hope it helps. If you need the source code, leave a comment and I will email it to you.</p>
<p style="text-align:left;"><a href="http://www.facebook.com/sharer.php?u=http://dotnetstories.wordpress.com/2009/06/21/object-oriented-programming-concepts-with-c3-0/" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb201m03.png" alt="Add to Facebook" /></a><a href="http://www.newsvine.com/_wine/save?u=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;h=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb202m03.png" alt="Add to Newsvine" /></a><a href="http://digg.com/submit?phase=2&#38;url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;title=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb203m03.png" alt="Add to Digg" /></a><a href="http://del.icio.us/post?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;title=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb204m03.png" alt="Add to Del.icio.us" /></a><a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;title=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb205m03.png" alt="Add to Stumbleupon" /></a><a href="http://reddit.com/submit?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;title=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb206m03.png" alt="Add to Reddit" /></a><a href="http://www.blinklist.com/index.php?Action=Blink/addblink.php&#38;Description=&#38;Url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;Title=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb207m03.png" alt="Add to Blinklist" /></a><a href="http://ma.gnolia.com/bookmarklet/add?url=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;title=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb208m03.png" alt="Add to Ma.gnolia" /></a><a href="http://www.technorati.com/faves?add=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb209m03.png" alt="Add to Technorati" /></a><a href="http://www.furl.net/storeIt.jsp?u=http%3A%2F%2Fdotnetstories.wordpress.com%2F2009%2F06%2F21%2Fobject-oriented-programming-concepts-with-c3-0%2F&#38;t=Object%20Oriented%20Programming%20Concepts%20with%20C%233.0" target="_blank"><img style="border:0;margin:0;padding:0;" src="http://getsocialserver.wordpress.com/files/2008/05/gsb210m03.png" alt="Add to Furl" /></a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Microsoft Visual Studio Gallery - Products and Extensions for Visual Studio]]></title>
<link>http://vakul.wordpress.com/2009/06/11/microsoft-visual-studio-gallery-products-and-extensions-for-visual-studio/</link>
<pubDate>Thu, 11 Jun 2009 14:46:52 +0000</pubDate>
<dc:creator>Vakul Kumar More</dc:creator>
<guid>http://vakul.wordpress.com/2009/06/11/microsoft-visual-studio-gallery-products-and-extensions-for-visual-studio/</guid>
<description><![CDATA[Are you to looking to find products, extensions, and add-ins for Visual Studio.   Your search ends a]]></description>
<content:encoded><![CDATA[Are you to looking to find products, extensions, and add-ins for Visual Studio.   Your search ends a]]></content:encoded>
</item>
<item>
<title><![CDATA[CrystalMapper ORM]]></title>
<link>http://csharplive.wordpress.com/2009/06/05/crystalmapper-orm/</link>
<pubDate>Fri, 05 Jun 2009 11:42:18 +0000</pubDate>
<dc:creator>Faraz Masood Khan</dc:creator>
<guid>http://csharplive.wordpress.com/2009/06/05/crystalmapper-orm/</guid>
<description><![CDATA[CrystalMapper&#160; is a very simple object ORM, infect it needs to improve a lot to qualify as ORM.]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://csharplive.files.wordpress.com/2009/06/cooltext424775800.png"><img style="display:inline;border-width:0;" title="cooltext424775800" border="0" alt="cooltext424775800" src="http://csharplive.files.wordpress.com/2009/06/cooltext424775800_thumb.png?w=244&#038;h=59" width="244" height="59" /></a></p>
<p>CrystalMapper&#160; is a very simple object ORM, infect it needs to improve a lot to qualify as ORM. CrystalMapper written to compete with ADO.NET DataSet fetch speed. It is very fast compare to other ORMs and provides only basic search, create, update and delete operations.</p>
<p><strong><a title="CrystalMapper QuickStart" href="http://www.youtube.com/watch?v=5_0UxY55ZF4" target="_blank">Quick Start video tutorial</a></strong></p>
<p>It is fast because it does not do any heaving loading task all by itself, instead leaves it to object for filling itself up when ask by CrystalMapper. Don’t you worry about having to writing manually for filling data logic, CrystalMapper includes Template for generating classes and it is integral part of ORM. Templates are written for CodeSmith. I know it is not Open Source but until I get understanding of an open source code generator tool please bear with it. You can use trial versions of CodeSmith for now.</p>
<p>Only very basic level searching is provided, there is no concept on referential entities or object changes tracking. It only allows you to transform an raw data into objects, on that business logic can be build I will show you basic search, complex query search and update functionality.</p>
<p>Note: example provided along with package is of AdventureWork database, normally used in Microsoft Labs Hands On (You can download it easily from codeplex, make sure to download SQL Server 2005 version).</p>
<p><strong>Basic Search:</strong></p>
<p>Basic search can be done with objects where not complex criteria is required.</p>
<pre class="code"><a href="http://csharplive.files.wordpress.com/2009/06/newpicture.png"><img style="display:inline;border-width:0;" title="New Picture" border="0" alt="New Picture" src="http://csharplive.files.wordpress.com/2009/06/newpicture_thumb.png?w=594&#038;h=209" width="594" height="209" /></a></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p><strong>Complex Search:</strong></p>
<p>Complex search requires complex criteria where simple equal to (=) does not work.</p>
<p><a href="http://csharplive.files.wordpress.com/2009/06/newpicture1.png"><img style="display:inline;border-width:0;" title="New Picture" border="0" alt="New Picture" src="http://csharplive.files.wordpress.com/2009/06/newpicture_thumb1.png?w=611&#038;h=167" width="611" height="167" /></a></p>
<p><strong>Updating:</strong></p>
<p>Update is very simple just call update function</p>
<p><a href="http://csharplive.files.wordpress.com/2009/06/newpicture2.png"><img style="display:inline;border-width:0;" title="New Picture" border="0" alt="New Picture" src="http://csharplive.files.wordpress.com/2009/06/newpicture_thumb2.png?w=601&#038;h=302" width="601" height="302" /></a></p>
<p><strong>Transactions:</strong></p>
<p>For updating objects in transaction, you just have to call dataContext.BeginTransaction() and dataContext.CommitTransaction() functions. Every object that is update by passing this dataContext in update or create function will effect changes in database with in same transaction.</p>
<p><strong>Open Source</strong></p>
<p>I want this project to be open source, therefore it is hosted on CodePlex.com: <a href="http://crystalmapper.codeplex.com">http://crystalmapper.codeplex.com</a></p>
<p><strong>Future Plans:</strong></p>
<p>Plans are very ambitious, two supports that I want to put in this ORM is LINQ and Parent Child relation entities. This referential relation will not be implemented like other ORM but instead it will only be prebuild queries for accessing Childs objects. Creating parent child relation is mainly a task of modifying template.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Circular Buffer for .NET]]></title>
<link>http://alexreg.wordpress.com/2009/05/23/circular-buffer-for-net/</link>
<pubDate>Sat, 23 May 2009 01:07:40 +0000</pubDate>
<dc:creator>Noldorin</dc:creator>
<guid>http://alexreg.wordpress.com/2009/05/23/circular-buffer-for-net/</guid>
<description><![CDATA[This is a quick announcement that I&#8217;ve released my code for an implementation of a generic cir]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>This is a quick announcement that I&#8217;ve released my code for an implementation of a generic <a href="http://en.wikipedia.org/wiki/Circular_buffer">circular buffer</a> for .NET (written in C# 3.0). The release also includes an implementation of a circular stream, which is a wrapper over a circular buffer of bytes. You can <a href="http://circularbuffer.codeplex.com/">view the project</a> and <a href="http://circularbuffer.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27751">download the source code</a> over at CodePlex, where I&#8217;ve licensed it under the MS-PL, which should hopefully be fairly unrestrictive.</p>
<p>If you&#8217;re wondering where this idea came from, I recently came across an interesting use for a circular buffer, and upon finding out that the .NET BCL contained nothing along the lines of a circular buffer (or stream), I decided to implement one myself. I&#8217;ve attempted to do everything properly of course (i.e. in the style of the BCL data structures), so hopefully it should be immediately useful to anyone familiar with the concept.</p>
<p>More about this to come later.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[LINQ to YAML]]></title>
<link>http://alexreg.wordpress.com/2009/05/14/linq-to-yaml/</link>
<pubDate>Wed, 13 May 2009 23:53:48 +0000</pubDate>
<dc:creator>Noldorin</dc:creator>
<guid>http://alexreg.wordpress.com/2009/05/14/linq-to-yaml/</guid>
<description><![CDATA[LINQ to XML is one of the many technologies introduced with the .NET Framework 3.5, and one that is ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://msdn.microsoft.com/en-us/library/bb387098.aspx">LINQ to XML</a> is one of the many technologies introduced with the .NET Framework 3.5, and one that is certainly a step forward in terms of usability. It allows querying in both the functional style (using LINQ and lambda expressions) and the more traditional imperative one, meaning that it&#8217;s a great tool for concisely working with XML data in any sort of application, and undoubtedly a significant improvement over the old XML DOM that resides in the <em>System.Xml</em> namespace.</p>
<p>In the spirit of LINQ, and with the advent of <a href="http://www.yaml.org/">YAML</a>, I recntly decided it was about time that this new &#8220;markup language&#8221; were integrated with LINQ. Surprisingly, there does not already exist anything akin to LINQ to YAML out there (though there are a couple of fairly usable implementations of a YAML reader/writer for .NET). This seemed to me like a good chance to potentially create something that might be used by more than the odd .NET developer or two. My plans are to implement a LINQ to YAML provider either from scratch or on top of one of the existing YAML libraries. (Which option I choose will depend on the state of the existing projects, which I haven&#8217;t yet investigated properly. I am however suspecting that it might be worthwhile writing my own, since it would a) teach me all the intricacies of YAML, and b) allow me to support the latest version [1.2], which the existing libraries do not.)</p>
<p>Before I launch into an overview of my intended implementation, here is a little bit about YAML itself, for those who aren&#8217;t already familiar with it. Although technically YAML isn&#8217;t a markup language (after all, the recursive acronym stands for <em>YAML Ain&#8217;t Markup Language</em>) &#8211; it is rather a serialisation format &#8211; it does essentially fulfill the the role that XML  traditionally has, in a variety of common situations. I&#8217;m not going to try to sell the format to you right now, but it should suffice to say that you wouldn&#8217;t have reached this far in the post if you weren&#8217;t already at least intrigued! Without doubt, the format is actively gaining popularity because of it&#8217;s ultra-lightweight syntax and suitability for hand editing, perhaps the two points that summarise its advantages over XML.</p>
<p>Anyway, here&#8217;s a short example of a YAML document (taken straight from <a href="http://en.wikipedia.org/wiki/Yaml#Sample_document">the Wikipedia page</a>), so you can see precisely how pleasant it is to work with (at least for humans).</p>
<p>&#8212;</p>
<pre>receipt:     Oz-Ware Purchase Invoice
date:        2007-08-06
customer:
    given:   Dorothy
    family:  Gale

items:
    - part_no:   A4786
      descrip:   Water Bucket (Filled)
      price:     1.47
      quantity:  4

    - part_no:   E1628
      descrip:   High Heeled "Ruby" Slippers
      price:     100.27
      quantity:  1

bill-to:  &#38;id001
    street: &#124;
            123 Tornado Alley
            Suite 16
    city:   East Westville
    state:  KS

ship-to:  *id001

specialDelivery:  &#62;
    Follow the Yellow Brick
    Road to the Emerald City.
    Pay no attention to the
    man behind the curtain.
...</pre>
<p>Of course, the great thing about YAML, which is demonstrated clearly by this example, is that you don&#8217;t have to have any real knowledge about YAML to understand exactly and immediately what the data represents, and as a bonus it doesn&#8217;t hurt your eyes to stare at for too long! Even the referencing syntax should be fairly self evident. (<em>&#38;id00</em> and<em> *id001</em> would surely be nothing new to C programmers.)</p>
<p>The semantics as well as the syntax of YAML obviously differ to those of XML greatly, although there is almost always some sort of correspondence between the features and possibilities that the two formats offer. The only notable missing feature when contrasted to XML is attributes, yet their usefulness is questionable anyway.</p>
<p>Right, so now I ought to explain a bit about how I actually plan to design this library. The basic framework will be virtually equivalent to that of LINQ to XML. In other words, the hierarchy will be largely based around an abstract <em>YamlObject</em> (<em>YObject</em>?) class, and will look very much like the one contained within <em>System.Xml.Linq</em>.</p>
<p><a href="http://i.msdn.microsoft.com/Bb308960.xlinqoverview01(en-us,MSDN.10).jpg"><img style="width:100%;" src="http://i.msdn.microsoft.com/Bb308960.xlinqoverview01(en-us,MSDN.10).jpg" alt="Diagram of LINQ to XML class hierarchy" /></a><em>LINQ to XML class hierarchy</em></p>
<p>Though LINQ to YAML must of course accomodate for the unique nature of the format, I would initially aim for minimal difference and only significantly adjust the hierarchy when it is found to be necessary. Classes such as <em>XCData</em> and <em>XDocumentType</em> would not apply at all to YAML, yet there would need to be a place for a <em>YReference</em> or such somewhere in the hierarchy. The referencing aspect of YAML will likely prove to be one of the more interesting challenges; while YAML&#8217;s lists, maps (dictionaries), and combinations thereof would seem relatively straightforward with regards to emulation of the LINQ to XML design, references would introduce a substantially novel concept. Some sort of implementation of lazy evaluation followed by concrete referencing should be able to solve the problem, but there&#8217;s no way to predict how well this might work in practice at this moment.</p>
<p>What I realised only after deciding to create a LINQ to YAML library is that among LINQ providers, LINQ to XML is somewhat special in that the LINQ aspect of it is built <em>on top of</em> <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx">LINQ to Objects</a> (i.e. LINQ using <em>IEnumerable&#60;T&#62;</em> objects), with only a relatively small number of extension methods specific to LINQ to XML. Indeed, most LINQ providers (LINQ to Objects and LINQ to SQL among others) require you to implement the <em>IQueryable</em> and <em>IQueryProvider</em> interfaces to provide complex logic for interpreting and returning the results of expressions, as well as evaluating complex expression trees.  All this means that I can pretty much just design a DOM  to a certain style (i.e. one suited to functional code, like LINQ to XML), and let LINQ to Objects to everything else for me.</p>
<p>As I can&#8217;t think of anything more worth mentioning about my project at this time, I shall leave any more specific and complex details to a future post. Still, do by all means feel free to query me about my plans &#8211; I would be glad to answer any questions, and even gladder to receive some suggestions as how you think I might design LINQ to YAML, or simply a nod that you might find this useful at some point. I don&#8217;t anticipate this project to be a very long one, though I must say that both my work and free-time schedule are likely to be fairly messed up for the next month or two, therefore I&#8217;m not going to promise when I&#8217;ll get around to my initial release. Whenever it so happens, I will duly post the link to the project page on Launchpad (or wherever I decide to host it).</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Strongly-Typed CSV Reader in C#]]></title>
<link>http://alexreg.wordpress.com/2009/05/03/strongly-typed-csv-reader-in-c/</link>
<pubDate>Sun, 03 May 2009 13:41:28 +0000</pubDate>
<dc:creator>Noldorin</dc:creator>
<guid>http://alexreg.wordpress.com/2009/05/03/strongly-typed-csv-reader-in-c/</guid>
<description><![CDATA[As part of a project on which I&#8217;ve recently started working, I found it necessary to write a c]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>As part of a project on which I&#8217;ve recently started working, I found it necessary to write a class that reads entries from <a href="http://en.wikipedia.org/wiki/Comma-separated_values">CSV</a> files. Such a simple format, you might think, so why would I bother sharing such trivial code? Indeed, it is a relatively short class, but I thought I&#8217;d post it here nonetheless, primarily because I believe its usage promotes a design practice of which I am particularly fond, and I suspect (hope) other people may appreciate as well. There are also a few bits of code that might be considered interesting (and unusual) from a language/design perspective.</p>
<p>When I decided to formalise the logic for reading from CSV files, I firstly thought it would be nice to write something in the spirit of .NET 3.5 &#8211; in this case, easily compatible with LINQ, fully generic (strongly-typed), and attribute-oriented (as seems to be the trend in APIs nowadays). Before I launch into any further discussion, here&#8217;s the code for the class in full.</p>
<pre class="csharp" style="border:1px solid #d0d0d0;overflow:auto;font-family:monospace;color:#000066;background-color:#f0f0f0;width:100%;max-height:40em;margin-bottom:1em;"><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.ComponentModel</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Collections.Generic</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.Linq</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Reflection</span><span style="color:#008000;">;</span>
<span style="color:#0600FF;">using</span> <span style="color:#008080;">System.Text</span><span style="color:#008000;">;</span>

<span style="color:#0600FF;">namespace</span> NetworkAnalyser
<span style="color:#000000;">{</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">class</span> CsvReader<span style="color:#008000;">&#60;</span>TEntry<span style="color:#008000;">&#62;</span> <span style="color:#008000;">:</span> IDisposable where TEntry <span style="color:#008000;">:</span> <span style="color:#FF0000;">struct</span>
    <span style="color:#000000;">{</span>
        <span style="color:#0600FF;">private</span> StreamReader streamReader<span style="color:#008000;">;</span>
        <span style="color:#0600FF;">private</span> FieldTypeInfo<span style="color:#000000;">[</span><span style="color:#000000;">]</span> fieldTypeInfos<span style="color:#008000;">;</span>

        <span style="color:#0600FF;">private</span> <span style="color:#FF0000;">bool</span> isDisposed <span style="color:#008000;">=</span> false<span style="color:#008000;">;</span>

        <span style="color:#0600FF;">public</span> CsvReader<span style="color:#000000;">(</span><span style="color:#FF0000;">string</span> path<span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            streamReader <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> StreamReader<span style="color:#000000;">(</span>path<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            Initialize<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> CsvReader<span style="color:#000000;">(</span>Stream stream<span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            streamReader <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> StreamReader<span style="color:#000000;">(</span>stream<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            Initialize<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        ~CsvReader<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            Dispose<span style="color:#000000;">(</span><span style="color:#0600FF;">false</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> <span style="color:#0600FF;">void</span> Dispose<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            Dispose<span style="color:#000000;">(</span><span style="color:#0600FF;">true</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            GC.<span style="color:#0000FF;">SuppressFinalize</span><span style="color:#000000;">(</span><span style="color:#0600FF;">this</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">protected</span> <span style="color:#0600FF;">virtual</span> <span style="color:#0600FF;">void</span> Dispose<span style="color:#000000;">(</span><span style="color:#FF0000;">bool</span> disposing<span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span><span style="color:#008000;">!</span>isDisposed<span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
                <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>disposing<span style="color:#000000;">)</span>
                <span style="color:#000000;">{</span>
                    <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>streamReader <span style="color:#008000;">!=</span> <span style="color:#0600FF;">null</span><span style="color:#000000;">)</span>
                        streamReader.<span style="color:#0000FF;">Dispose</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                <span style="color:#000000;">}</span>
            <span style="color:#000000;">}</span>

            isDisposed <span style="color:#008000;">=</span> true<span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> IEnumerable<span style="color:#008000;">&#60;</span>TEntry<span style="color:#008000;">&#62;</span> ReadAllEntries<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            TEntry<span style="color:#008000;">?</span> entry<span style="color:#008000;">;</span>
            <span style="color:#0600FF;">while</span> <span style="color:#000000;">(</span><span style="color:#000000;">(</span>entry <span style="color:#008000;">=</span> ReadEntry<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">HasValue</span><span style="color:#000000;">)</span>
                yield <span style="color:#0600FF;">return</span> entry.<span style="color:#0000FF;">Value</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">public</span> TEntry<span style="color:#008000;">?</span> ReadEntry<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            var line <span style="color:#008000;">=</span> streamReader.<span style="color:#0000FF;">ReadLine</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            <span style="color:#0600FF;">if</span> <span style="color:#000000;">(</span>line <span style="color:#008000;">==</span> <span style="color:#0600FF;">null</span><span style="color:#000000;">)</span>
                <span style="color:#0600FF;">return</span> null<span style="color:#008000;">;</span>

            var entry <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> TEntry<span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            var fields <span style="color:#008000;">=</span> line.<span style="color:#0000FF;">Split</span><span style="color:#000000;">(</span><a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> <span style="color:#FF0000;">char</span><span style="color:#000000;">[</span><span style="color:#000000;">]</span> <span style="color:#000000;">{</span> <span style="color:#666666;">','</span> <span style="color:#000000;">}</span>, StringSplitOptions.<span style="color:#0000FF;">None</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            FieldTypeInfo fieldTypeInfo<span style="color:#008000;">;</span>
            <span style="color:#FF0000;">object</span> fieldValue<span style="color:#008000;">;</span>

            <span style="color:#0600FF;">for</span> <span style="color:#000000;">(</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;">&#60;</span> fields.<span style="color:#0000FF;">Length</span><span style="color:#008000;">;</span> i<span style="color:#008000;">++</span><span style="color:#000000;">)</span>
            <span style="color:#000000;">{</span>
                fieldTypeInfo <span style="color:#008000;">=</span> fieldTypeInfos<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span><span style="color:#008000;">;</span>
                fieldValue <span style="color:#008000;">=</span> fieldTypeInfo.<span style="color:#0000FF;">TypeConverter</span>.<span style="color:#0000FF;">ConvertFromString</span><span style="color:#000000;">(</span>fields<span style="color:#000000;">[</span>i<span style="color:#000000;">]</span>.<span style="color:#0000FF;">Trim</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
                fieldTypeInfo.<span style="color:#0000FF;">FieldInfo</span>.<span style="color:#0000FF;">SetValueDirect</span><span style="color:#000000;">(</span>__makeref<span style="color:#000000;">(</span>entry<span style="color:#000000;">)</span>, fieldValue<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            <span style="color:#000000;">}</span>

            <span style="color:#0600FF;">return</span> entry<span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">private</span> <span style="color:#0600FF;">void</span> Initialize<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
        <span style="color:#000000;">{</span>
            var entryType <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>TEntry<span style="color:#000000;">)</span><span style="color:#008000;">;</span>
            fieldTypeInfos <span style="color:#008000;">=</span> <span style="color:#000000;">(</span>from fieldInfo <span style="color:#0600FF;">in</span> entryType.<span style="color:#0000FF;">GetFields</span><span style="color:#000000;">(</span>BindingFlags.<span style="color:#0000FF;">Instance</span> <span style="color:#008000;">&#124;</span>
                                  BindingFlags.<span style="color:#0600FF;">Public</span><span style="color:#000000;">)</span>
                              let fieldTypeConverterAttrib <span style="color:#008000;">=</span> fieldInfo.<span style="color:#0000FF;">GetCustomAttributes</span><span style="color:#000000;">(</span>
                                  <a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>TypeConverterAttribute<span style="color:#000000;">)</span>, <span style="color:#0600FF;">true</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">SingleOrDefault</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span>
                                  <span style="color:#0600FF;">as</span> TypeConverterAttribute
                              let fieldTypeConverter <span style="color:#008000;">=</span> <span style="color:#000000;">(</span>fieldTypeConverterAttrib <span style="color:#008000;">==</span> <span style="color:#0600FF;">null</span><span style="color:#000000;">)</span> <span style="color:#008000;">?</span> <span style="color:#0600FF;">null</span> <span style="color:#008000;">:</span>
                                  Activator.<span style="color:#0000FF;">CreateInstance</span><span style="color:#000000;">(</span>Type.<span style="color:#0000FF;">GetType</span><span style="color:#000000;">(</span>
                                      fieldTypeConverterAttrib.<span style="color:#0000FF;">ConverterTypeName</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
                                  <span style="color:#0600FF;">as</span> TypeConverter
                              select <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> FieldTypeInfo<span style="color:#000000;">(</span><span style="color:#000000;">)</span>
                              <span style="color:#000000;">{</span>
                                  FieldInfo <span style="color:#008000;">=</span> fieldInfo,
                                  TypeConverter <span style="color:#008000;">=</span> fieldTypeConverter <span style="color:#008000;">??</span>
                                      TypeDescriptor.<span style="color:#0000FF;">GetConverter</span><span style="color:#000000;">(</span>fieldInfo.<span style="color:#0000FF;">FieldType</span><span style="color:#000000;">)</span>
                              <span style="color:#000000;">}</span><span style="color:#000000;">)</span>.<span style="color:#0000FF;">ToArray</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>

        <span style="color:#0600FF;">private</span> <span style="color:#FF0000;">struct</span> FieldTypeInfo
        <span style="color:#000000;">{</span>
            <span style="color:#0600FF;">public</span> FieldInfo FieldInfo<span style="color:#008000;">;</span>
            <span style="color:#0600FF;">public</span> TypeConverter TypeConverter<span style="color:#008000;">;</span>
        <span style="color:#000000;">}</span>
    <span style="color:#000000;">}</span>
<span style="color:#000000;">}</span></pre>
<p>(Please excuse the utter lack of comments in the code. Most of it is self-explanatory, but admittedly some parts are probably not. I put it together pretty quickly, but I may get around to commenting it some time soon. Some basic error handling might also be nice.)</p>
<p>At this point it may seem rather excessive just to read data from a CSV file, but I hope you&#8217;ll agree that it&#8217;s worthwhile once you see an example of typical usage.</p>
<p>The first step is to define a structure (<em>struct</em>) that holds each entry in memory. Here we&#8217;re going to define one that holds some basic information about a programming language.</p>
<pre class="csharp" style="border:1px solid #d0d0d0;overflow:auto;font-family:monospace;color:#000066;background-color:#f0f0f0;width:100%;margin-bottom:1em;"><span style="color:#0600FF;">public</span> <span style="color:#FF0000;">struct</span> LanguageEntry
<span style="color:#000000;">{</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;">string</span><span style="color:#000000;">[</span><span style="color:#000000;">]</span> Paradigms<span style="color:#008000;">;</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">string</span> LatestVersion<span style="color:#008000;">;</span>
    <span style="color:#000000;">[</span>TypeConverter<span style="color:#000000;">(</span><a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>CustomDateTimeConverter<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#000000;">]</span>
    <span style="color:#0600FF;">public</span> DateTime InitialRelease<span style="color:#008000;">;</span>
    <span style="color:#000000;">[</span>TypeConverter<span style="color:#000000;">(</span><a href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color:#008000;">typeof</span></a><span style="color:#000000;">(</span>CustomDateTimeConverter<span style="color:#000000;">)</span><span style="color:#000000;">)</span><span style="color:#000000;">]</span>
    <span style="color:#0600FF;">public</span> DateTime LatestRelease<span style="color:#008000;">;</span>
    <span style="color:#0600FF;">public</span> <span style="color:#FF0000;">float</span> Popularity<span style="color:#008000;">;</span>
<span style="color:#000000;">}</span></pre>
<p>The <em>TypeConverter</em> attributes are completely optional, and are only required when you&#8217;re reading some fields that have unusual formats and whose values you would like to convert to something simpler/more accessible (e.g. a string &#8220;Jun2002&#8243; to a <em>DateTime</em> object in this case). For any field of a type recognisable by the default type converter, you don&#8217;t need to bother, as is shown for the <em>double</em> type. (This actually applies to a very large range of types within the BCL, including <em>System.Drawing.Color</em>, which can be specified in any format that you might use in the propeprty editor of Visual Studio, such as &#8220;DarkRed&#8221;.)</p>
<p>Finally, here&#8217;s a snippet to show how you might actually use the <em>CsvReader&#60;TEntry&#62;</em> class to read from a CSV file. This example reads all entries from the languages.csv file and prints out to the console the names of all functional languages.</p>
<pre class="csharp" style="border:1px solid #d0d0d0;overflow:auto;font-family:monospace;color:#000066;background-color:#f0f0f0;width:100%;margin-bottom:1em;"><span style="color:#0600FF;">using</span> <span style="color:#000000;">(</span>var languagesReader <span style="color:#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:#008000;">new</span></a> CsvReader<span style="color:#008000;">&#60;</span>LanguageEntry<span style="color:#008000;">&#62;</span><span style="color:#000000;">(</span><span style="color:#666666;">"language.csv"</span><span style="color:#000000;">)</span><span style="color:#000000;">)</span>
<span style="color:#000000;">{</span>
    var languages <span style="color:#008000;">=</span> from lang <span style="color:#0600FF;">in</span> languagesReader.<span style="color:#0000FF;">ReadAllEntries</span><span style="color:#000000;">(</span><span style="color:#000000;">)</span>
                    where lang.<span style="color:#0000FF;">Paradigms</span>.<span style="color:#0000FF;">Contains</span><span style="color:#000000;">(</span><span style="color:#666666;">"Functional"</span><span style="color:#000000;">)</span>
                    select lang<span style="color:#008000;">;</span>
    <span style="color:#0600FF;">foreach</span> <span style="color:#000000;">(</span>var lang <span style="color:#0600FF;">in</span> languages<span style="color:#000000;">)</span>
        Console.<span style="color:#0000FF;">WriteLine</span><span style="color:#000000;">(</span>lang.<span style="color:#0000FF;">Name</span><span style="color:#000000;">)</span><span style="color:#008000;">;</span>
<span style="color:#000000;">}</span></pre>
<p>Hopefully that&#8217;s now convinced you that this is the right way to go about reading data entries from files. What this class provides is completely strongly-typed I/O (reading in this case, though it wouldn&#8217;t be very hard to create a similar <em>CsvWriter</em> class), and a declarative manner to defining entry types (or records, to use database termninology).</p>
<p>I&#8217;m not going to delve too deeply into the implementation of the class, but I think it&#8217;s worth highlighting a few specifics. Going back to the code for the class, the first thing to notice is the <em>Initialize</em> method &#8211; this is where much of the interesting stuff is happening. To summarise: it loops over all the public fields of the type specified by <em>TEntry</em>, gets the default type converter for the type of each field (or the one given by <em>TypeConverterAttribute</em>, if it exists), and then stores the <em>FieldInfo</em> along with the <em>TypeConverter</em> in a simple struct. The only other noteworthy point is the call to <em>SetValueDirect</em> in the <em>ReadEntry</em> method. This uses a keyword that&#8217;s almost wholly unknown (and undocumented!) to C# developers by the name of <em>__makeref</em> (there are other related ones by the names of <em>__reftype</em> and <em>__refvalue</em>) &#8211; I was certainly unaware of it before today. The problem that I initially encountered was one of using the <em>SetValue</em> method, which works perfectly well on classes, but presents a unique problem with structs: namely, because they are value-types, and the <em>obj</em> parameter is of type <em>object</em>, the argument must be boxed (wrapped into a reference type) and placed on the heap rather than the stack, meaning that the heap-based copy gets altered, and not the one you passed to the method (which is on the stack)! What the <em>__makeref</em> keyword does is create a <em>TypeReference</em> that directly references the stack-based object and thus allows <em>SetValueDirect</em> to set the field accordingly.</p>
<p>That&#8217;s enough explanation, I think. If you still aren&#8217;t sure about how it works precisely, then feel free to comment on this post. I&#8217;d also be quite happy to hear what anyone thinks of the general design and implementation, too.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Sudoku Solver in C# using Lambda Expressions]]></title>
<link>http://antimatroid.wordpress.com/2009/05/01/sudoku-solver-in-c-using-lambda-expressions/</link>
<pubDate>Fri, 01 May 2009 07:00:31 +0000</pubDate>
<dc:creator>lewellen</dc:creator>
<guid>http://antimatroid.wordpress.com/2009/05/01/sudoku-solver-in-c-using-lambda-expressions/</guid>
<description><![CDATA[Seems that everywhere you look someone has a Sudoku Solver that they want to showcase, well, I]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Seems that everywhere you look someone has a Sudoku Solver that they want to showcase, well, I&#8217;m no different so I figured I&#8217;d post my take on the subject. Microsoft has introduced/included/borrowed a number of functional programming features into the latest version of C# (3.0) that have made it easier for developers to write better, cleaner code. One of those features continues the trend of improving  anonymous methods, which extend delegates which extend interfaces now known as Lambda expressions. E.g., the following are all the same for the expression <img src='http://l.wordpress.com/latex.php?latex=%5Clambda+x+.+x+%2A+x&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda x . x * x' title='\lambda x . x * x' class='latex' />: </p>
<pre class="brush: csharp;">
Func&lt;int, int&gt; square = (x) =&gt; x * x;
</pre>
<pre class="brush: csharp;">
Func&lt;int, int&gt; square = new Func&lt;int, int&gt;(delegate(int x) { return x * x; });
</pre>
<pre class="brush: csharp;">
public interface Func&lt;T, R&gt; {
    R Evaluate(T x);
}

public class Square : Func&lt;int, int&gt; {
    public int Evaluate(int x) {
        return x*x;
    }
}

...

Func&lt;int,int&gt; square = new Square();
</pre>
<p>Given that level of expressive power, I thought I would approach this implementation using as many lambda expressions as possible to see how concise and easy to follow an implementation I could create. </p>
<p>To start off, the solver will assume that the board will be passed in as a 81 character array containing digits 0-9. Zero shall represent an unassigned cell. </p>
<p>The core loop is pretty simple: Start with the initial board on a stack, in a loop take the first board off the stack and check if it is valid. A board is said to be valid if for every row, column and region each structure contains one and only one instance of the digits 1-9. If the board is not valid, no further work should be done.</p>
<p>Next we need to check if the board is solved. If it is not, then we need to explore the possible boards that can be derived from that board. To do so, we will need to find the first possible cell that is unassigned and push on to the the stack a derived board using the possible values that can be assigned to the identified cell.</p>
<p>Once the loop finally exits, print out the solved board.</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;

namespace Sudoku {
    public class Program {
        static public void Main(string[] args) {
            string input = &quot;200080300060070084030500209000105408000000000402706000301007040720040060004010003&quot;;
            Board inputBoard = null;
            try {
                inputBoard = new Board(input);
            } catch (InvalidInputException iie) {
                Console.WriteLine(iie.InvalidInput);
                return;
            }

            Stack boards = new Stack();
            boards.Push(inputBoard);
            Board board = null;
            do {
                board = boards.Pop();
                if (!board.Valid)
                    continue;
                if (!board.Solved)
                    board.FirstAvailable((r, c) =&gt;
                        board.PossibleValuesAt(r, c, (v) =&gt;
                            boards.Push(board.DeriveUsing(r, c, v))
                        )
                    );
            } while (boards.Count &gt; 0 &amp;&amp; !board.Solved);
            Console.WriteLine(board);
        }
    }
}
</pre>
<p>I&#8217;m going to start with the private member methods since they form the basic grammar that I will use to implement the public member methods and properties.</p>
<p>The first thing you&#8217;ll notice is the private class Structure; it is a simple pair class that contains two member properties for accessing a function that iterates over all possible structures and a function that iterates over all the cells in a specific structure. </p>
<p>The private constructor instantiates a private member array containing the function pointers that enumerate over Rows, Column and Regions. </p>
<p>assertStructure method which iterates over every instance of a structure in the table, and verifies that one and only one instance of the digits 1-9 exist in that structure instance. </p>
<p>indexInStructure iterates over all of the indices of a structure- in this case, 0-8.</p>
<pre class="brush: csharp;">
using System;
using System.Text;

namespace Sudoku {
    public partial class Board {
        private class Struct {
            public Action&lt;Action&lt;int&gt;&gt; In { get; set; }
            public Action&lt;int, Action&lt;int&gt;&gt; ForValues { get; set; }
            public Struct(Action&lt;Action&lt;int&gt;&gt; _in, Action&lt;int, Action&lt;int&gt;&gt; forValues) {
                In = _in; ForValues = forValues;
            }
        }

        private Struct[] structures;

        private Board(int[] board) {
            this.board = board;
            structures = new Struct[] {
                new Struct(Rows, ValuesInRow), new Struct(Columns, ValuesInColumn),
                new Struct(Regions, ValuesInRegion)
            };
        }

        private bool assertStructure(Action&lt;Action&lt;int&gt;&gt; structure, Action&lt;int, Action&lt;int&gt;&gt;
            valuesInStructure) {
            bool asserted = true;
            structure((x) =&gt; {
                int[] used = new int[10];
                valuesInStructure(x, (y) =&gt; used[y]++);
                used[0] = 0;
                asserted &amp;= forAllValues((v) =&gt; v &lt; 2, used);
            });
            return asserted;
        }

        private void indexInStructure(Action&lt;int&gt; actOnIndex) {
            indexInStructure((n) =&gt; true, actOnIndex);
        }

        private void indexInStructure(Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex) {
            indexFromToWhere(0, 9, p, actOnIndex, false);
        }
</pre>
<p>The forAllValues method is simply a way of writing the predicate <img src='http://l.wordpress.com/latex.php?latex=%28%5Cforall+x%29+Px&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(\forall x) Px' title='(\forall x) Px' class='latex' />  applied to members of the universe of discourse (the array that was passed in).</p>
<p>indexFromToWhere is a simple wrapper around a common for loop with filtering and the option to break after the first object to pass through the filter is found.</p>
<pre class="brush: csharp;">
        private bool forAllValues(Predicate f, T[] A) {
            bool held = true;
            for (int n = 0; n &lt; A.Length &amp;&amp; held; n++)
                held &amp;= f(A[n]);
            return held;
        }

        private void indexFromToWhere(int min, int max, Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex,
            bool breakAfterFirst) {
            for (int n = min; n &lt; max; n++)
                if (p(n)) {
                    actOnIndex(n);
                    if (breakAfterFirst)
                        break;
                }
        }
</pre>
<p>The following methods are all related to working with the board representation. I choose to implement the board as an integer array. The at method maps a logical row and column to a row order array value within board. Each of the different indexInBoard methods allows for iterating over the indices of the board.</p>
<pre class="brush: csharp;">
        private int[] board;

        private int at(int row, int col) {
            return row * 9 + col;
        }

        private void indexInBoard(Action&lt;int&gt; actOnIndex) {
            indexInBoard((n) =&gt; true, actOnIndex);
        }

        private void indexInBoard(Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex) {
            indexInBoard(p, actOnIndex, false);
        }

        private void indexInBoard(Predicate&lt;int&gt; p, Action&lt;int&gt; actOnIndex, bool breakAfterFirst) {
            indexFromToWhere(0, board.Length, p, actOnIndex, breakAfterFirst);
        }
    }
}
</pre>
<p>The first set of public member methods and properties we can look at are for managing the state of the board. The board is only Solved if each index is assigned. The board is only Valid if every structure in the board is asserted to be true. The constructor checks the input to make sure it is valid, delegates the some work to the private constructor and loads the input string in to the integer array.</p>
<pre class="brush: csharp;">
using System;
using System.Text;

namespace Sudoku {
    public partial class Board {
        public bool Solved {
            get {
                return forAllValues((x) =&gt; x &gt; 0, board);
            }
        }
        public bool Valid {
            get {
                return forAllValues((s) =&gt; assertStructure(s.In, s.ForValues), structures);
            }
        }

        public Board(string input) : this (new int[81]) {
            if (string.IsNullOrEmpty(input))
                throw new InvalidInputException(InvalidInput.Empty);
            if (input.Length != 81)
                throw new InvalidInputException(InvalidInput.Length);
            for (int n = 0; n  board[n] = input[n] - '0');
        }

        override public string ToString() {
            StringBuilder S = new StringBuilder(board.Length);
            indexInBoard((n) =&gt; S.Append((char)('0' + board[n])));
            return S.ToString();
        }
</pre>
<p>Next, we need a way to operate on each of the structures in the board. Each row from top to bottom, each column from left to right and each region from top left to bottom right (zig-zag) will be assigned an index from 0-8 respectively.</p>
<pre class="brush: csharp;">
        public void Columns(Action&lt;int&gt; actOnColumn) {
            indexInStructure(actOnColumn);
        }

        public void Regions(Action&lt;int&gt; actOnRegion) {
            indexInStructure(actOnRegion);
        }

        public void Rows(Action&lt;int&gt; actOnRow) {
            indexInStructure(actOnRow);
        }
</pre>
<p>It is easy to then iterate the cells in a given structure. The values in a column are simply a trip down the Rows and we only want to act when the value is defined. The values in a row are just as easy by traveling across the Columns and acting when the value is defined. Iterating over the values in the region is a little more involved, but nonetheless just as easy to follow- map the region to the appropriate reference row and column and then iterate over the 3&#215;3 grid and act only when the value is defined.</p>
<pre class="brush: csharp;">
        public void ValuesInColumn(int column, Action&lt;int&gt; actOnValue) {
            Rows((r) =&gt; {
                int value = board[at(r, column)];
                if (value &gt; 0)
                    actOnValue(value);
            });
        }

        public void ValuesInRegion(int region, Action&lt;int&gt; actOnValue) {
            int row = (region / 3) * 3;
            int column = (region % 3) * 3;
            int value = 0;
            for (int r = 0; r &lt; 3; r++)
                for (int c = 0; c  0)
                        actOnValue(value);
                }
        }

        public void ValuesInRow(int row, Action&lt;int&gt; actOnValue) {
            Columns((c) =&gt; {
                int value = board[at(row, c)];
                if (value &gt; 0)
                    actOnValue(value);
            });
        }
</pre>
<p>Finally, we have the interesting methods used in the main loop. DeriveUsing will copy the board into a cloned integer array and then assign the derived at row and column with the value supplied. The newly derived board is then returned. </p>
<p>FirstAvailable iterates over all the indices of the board until it finds an unassigned value and then it acts upon the reference row and column.</p>
<p>PossibleValuesAt goes and collects a list of possible values by first collecting the values used in the row, column and region that the reference row and column reside within, then each value not found is acted upon.</p>
<pre class="brush: csharp;">
        public Board DeriveUsing(int row, int colum, int withValue) {
            int[] derived = new int[81];
            indexInBoard((n) =&gt; derived[n] = board[n]);
            derived[at(row, colum)] = withValue;
            return new Board(derived);
        }

        public void FirstAvailable(Action&lt;int, int&gt; actOnRowAndColumn) {
            indexInBoard((n) =&gt;
                board[n] == 0, (n) =&gt; actOnRowAndColumn(n / 9, n % 9), true);
        }

        public void PossibleValuesAt(int row, int column, Action&lt;int&gt; actOnPossibleValue) {
            bool[] used = new bool[10];
            ValuesInRow(row, (x) =&gt; used[x] = true);
            ValuesInColumn(column, (x) =&gt; used[x] = true);
            ValuesInRegion((row / 3) * 3 + (column / 3), (x) =&gt; used[x] = true);
            indexFromToWhere(1, used.Length, (n) =&gt; !used[n], actOnPossibleValue, false);
        }
    }
}
</pre>
<p>Having approached this implementation as I did, I found some interesting bugs that I hadn&#8217;t come across before and I figure I&#8217;ll close with one that caught me off guard. I had spent an hour writing all my code and figured I&#8217;d run it to see what kind of output I got. To my surprise I got an immediate StackOverflowExeception. So I spent and an additional 10 minutes debugging and found the following offending code. Take a look at it and see if you can see what&#8217;s wrong with it before reading on.</p>
<pre class="brush: csharp;">
public void act(Func&lt;int,int&gt; assign){
    act((n) =&gt; board[n] = assign(n));
}

public void act(Action&lt;int&gt; actOn) {
    for(int n = 0; n &lt; board.Length; n++)
      actOn(n);
}
</pre>
<p>After a minute I had my ah-ha moment (as I&#8217;m sure have as well) and remembered that the assignment operator returns the value of the assignment so the compiler was turning (n) =&#62; board[n] = assign(n), into Func&#60;int, int&#62; instead of Action&#60;int&#62; as I had hoped. To fix the bug, I had to do the following to get the compiler to pick the statement up as Action&#60;int&#62;.</p>
<pre class="brush: csharp;">
public void act(Func&lt;int,int&gt; assign) {
    for(int n = 0; n &lt; board.Length; n++)
        act((n) =&gt; { board[n] = assign(n); });
}
</pre>
<p>Having made the change, I tested my input string and out printed the solution immediately. I decided against writing similar function overloading in the final implementation to prevent any unintended bugs.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Roland annuncia: On-line il sito italiano del C-30]]></title>
<link>http://it.audiofanzine.com/2009/04/16/roland-annuncia-on-line-il-sito-italiano-del-c-30/</link>
<pubDate>Thu, 16 Apr 2009 07:29:53 +0000</pubDate>
<dc:creator>audiofanzineitalian</dc:creator>
<guid>http://it.audiofanzine.com/2009/04/16/roland-annuncia-on-line-il-sito-italiano-del-c-30/</guid>
<description><![CDATA[Roland annuncia l&#8217;apertura del nuovo sito dedicato al suo nuovo clavicembalo digitale C-30.]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://audiofanzineit.wordpress.com/files/2009/04/rlogo1.jpg"><img class="alignleft size-thumbnail wp-image-3889" title="rlogo1" src="http://audiofanzineit.wordpress.com/files/2009/04/rlogo1.jpg?w=128" alt="rlogo1" width="128" height="21" /></a>Roland annuncia l&#8217;apertura del nuovo <a href="http://www.c30.roland.it/">sito</a> dedicato al suo nuovo clavicembalo digitale C-30.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[.NET Book Zero by Charles Petzold]]></title>
<link>http://vakul.wordpress.com/2009/03/20/net-book-zero-by-charles-petzold/</link>
<pubDate>Fri, 20 Mar 2009 09:01:26 +0000</pubDate>
<dc:creator>Vakul Kumar More</dc:creator>
<guid>http://vakul.wordpress.com/2009/03/20/net-book-zero-by-charles-petzold/</guid>
<description><![CDATA[Charles Petzold is a well known author of over fifteen programming books. To many, his books on prog]]></description>
<content:encoded><![CDATA[Charles Petzold is a well known author of over fifteen programming books. To many, his books on prog]]></content:encoded>
</item>
<item>
<title><![CDATA[C# 3.0 Features]]></title>
<link>http://hirentechie.wordpress.com/2009/02/06/csharp-3-features/</link>
<pubDate>Fri, 06 Feb 2009 10:44:49 +0000</pubDate>
<dc:creator>Hiren Patel</dc:creator>
<guid>http://hirentechie.wordpress.com/2009/02/06/csharp-3-features/</guid>
<description><![CDATA[1. Implicitly Typed Variable (var) Implicitly typed local variable is a variable that can be declare]]></description>
<content:encoded><![CDATA[1. Implicitly Typed Variable (var) Implicitly typed local variable is a variable that can be declare]]></content:encoded>
</item>
<item>
<title><![CDATA[Ouroboros: reinventing Nibbles]]></title>
<link>http://antimatroid.wordpress.com/2009/02/01/ouroboros-reinventing-nibbles/</link>
<pubDate>Sun, 01 Feb 2009 07:00:43 +0000</pubDate>
<dc:creator>lewellen</dc:creator>
<guid>http://antimatroid.wordpress.com/2009/02/01/ouroboros-reinventing-nibbles/</guid>
<description><![CDATA[Introduction I talked about some classic arcade games in a previous post that I had worked on over t]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2>Introduction</h2>
<p>I talked about some classic arcade games in a previous post that I had worked on over the years and mentioned that I&#8217;d get around to posting some implementation details of one of them. A few months later here we are and the following is an overview of the implementation details of Ouroboros- my revisioning of the classic arcade game Nibbles that I enjoyed playing and learning about back in my QBasic days.</p>
<p>This write-up will go over the activities associated with the software development process from specification to implementation. Before I get into the details, here&#8217;s a game play of what is that I&#8217;ll be explaining how to make:</p>
<p><span style='text-align:center; display: block;'><object width='425' height='350'><param name='movie' value='http://www.youtube.com/v/GSJCGoDmnqI&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' /><param name='allowfullscreen' value='true' /><param name='wmode' value='transparent' /><embed src='http://www.youtube.com/v/GSJCGoDmnqI&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;hd=0' type='application/x-shockwave-flash' allowfullscreen='true' width='425' height='350' wmode='transparent'></embed></object></span></p>
<h2>Specification</h2>
<p>The goal of the game is to collect rewards. Each time a reward is collected, the user&#8217;s score is increased. The snake is constantly moving in the direction last requested by the user. The user can direct the snake to move either left, up, right or down. To make the game more challenging, the snake will grow whenever the snake consumes a reward. The game then ends once the snake spans the entire board or the snake collides with itself. When the snake &#8220;hits&#8221; a wall, its position wraps around the board. When either of the terminating conditions is meet the user is asked if he or she wishes to play again.</p>
<h2>Requirements</h2>
<p>The user may control the direction the snake may move by using the keyboard. The following keys are valid: {&#8592;, &#8593;, &#8594;, &#8595;} and {a, w, d, s} to the directions {left, up, right and down}.</p>
<p>The game is to be displayed to the user as as command line interface (CLI), 2D graphical user interface (2DGUI) using WinForms and a 3D GUI (3DGUI) using  Windows Presentation Foundation. The CLI and 2DGUI shall appear as boards that the snake and reward appear on. The 3DGUI shall appear as a torus that the snake and reward appear on.</p>
<p>The game may not appear to be slower as the length of the snake increases.</p>
<h2>Design</h2>
<h3>The Board</h3>
<p>The board is a simple coordinate system with a fixed side length <img src='http://l.wordpress.com/latex.php?latex=B&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='B' title='B' class='latex' />. Each <img src='http://l.wordpress.com/latex.php?latex=%5Cvec%7Bx%7D+%5Csubset+%7B+%5C%7B+0%2C+1%2C+%5Cldots+B+-+1+%5C%7D+%7D%5E%7B2%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{x} \subset { \{ 0, 1, \ldots B - 1 \} }^{2}' title='\vec{x} \subset { \{ 0, 1, \ldots B - 1 \} }^{2}' class='latex' /> coordinate may be occupied by at most one snake segment. For each view, a mapping <img src='http://l.wordpress.com/latex.php?latex=f+%3A+M+%5Cto+V&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f : M \to V' title='f : M \to V' class='latex' /> from the model space, <img src='http://l.wordpress.com/latex.php?latex=M&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M' title='M' class='latex' />, to the view space, <img src='http://l.wordpress.com/latex.php?latex=V&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='V' title='V' class='latex' />, is necessary to achieve the required behavior. </p>
<p><img src="http://antimatroid.wordpress.com/files/2009/02/snake_space1.png" alt="snake_space1" title="snake_space1" width="480" height="180" class="aligncenter size-full wp-image-508" /></p>
<p>For the CLI view, let <img src='http://l.wordpress.com/latex.php?latex=f%28%5Cvec%7Bx%7D%29+%3D+%5Cvec%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(\vec{x}) = \vec{x}' title='f(\vec{x}) = \vec{x}' class='latex' /> since every coordinate maps one-to-one with a cursor position on the console.</p>
<p>The 2DGUI view requires a scaling factor, <img src='http://l.wordpress.com/latex.php?latex=c+%26%2362%3B+1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c &gt; 1' title='c &gt; 1' class='latex' />, otherwise the board would appear to be too small to play- unless for example, upon a cellphone LCD. Let <img src='http://l.wordpress.com/latex.php?latex=f%28%5Cvec%7Bx%7D%29+%3D+c%5Cvec%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(\vec{x}) = c\vec{x}' title='f(\vec{x}) = c\vec{x}' class='latex' />. </p>
<p>The 3DGUI view requires an initial mapping from a <img src='http://l.wordpress.com/latex.php?latex=%5Cvec%7Bx%7D+%3D+%28x%2Cy%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{x} = (x,y)' title='\vec{x} = (x,y)' class='latex' /> coordinate to a <img src='http://l.wordpress.com/latex.php?latex=%5Cvec%7By%7D+%3D+%28%5Cvartheta%2C+%5Cvarphi%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{y} = (\vartheta, \varphi)' title='\vec{y} = (\vartheta, \varphi)' class='latex' /> system. This is accomplished by <img src='http://l.wordpress.com/latex.php?latex=g%28%5Cvec%7Bx%7D%29+%3D+%5Cfrac%7B2%5Cpi%7D%7BB%7D%5Cvec%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='g(\vec{x}) = \frac{2\pi}{B}\vec{x}' title='g(\vec{x}) = \frac{2\pi}{B}\vec{x}' class='latex' /> where <img src='http://l.wordpress.com/latex.php?latex=B&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='B' title='B' class='latex' /> is the length of the edge of the board. A torus is defined in terms of an interior radius, <img src='http://l.wordpress.com/latex.php?latex=R&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='R' title='R' class='latex' />, and the swept radius, <img src='http://l.wordpress.com/latex.php?latex=r&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='r' title='r' class='latex' />. Thus a torus is defined as the following: </p>
<p><img src='http://l.wordpress.com/latex.php?latex=%5Cdisplaystyle+%28f+%5Ccirc+g%29%28%5Cvec%7Bx%7D%29+%3D+%5Cbegin%7Bpmatrix%7D%28R+%2B+r+cos%28%5Cvarphi%29%29cos%28%5Cvartheta%29%5C%5C%28R+%2B+r+cos%28%5Cvarphi%29%29cos%28%5Cvartheta%29%5C%5Cr+sin%28%5Cvarphi%29%5Cend%7Bpmatrix%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\displaystyle (f \circ g)(\vec{x}) = \begin{pmatrix}(R + r cos(\varphi))cos(\vartheta)\\(R + r cos(\varphi))cos(\vartheta)\\r sin(\varphi)\end{pmatrix}' title='\displaystyle (f \circ g)(\vec{x}) = \begin{pmatrix}(R + r cos(\varphi))cos(\vartheta)\\(R + r cos(\varphi))cos(\vartheta)\\r sin(\varphi)\end{pmatrix}' class='latex' /> </p>
<h3>The Snake</h3>
<p>The snake is conceptually a sequence of segments that I choose to represent as a singly-linked list where each node contains a pointer to the next segment and the segment&#8217;s position. The following illustrates a snake of length five:</p>
<p><img src="http://antimatroid.wordpress.com/files/2009/01/snake_model.png" alt="snake_model" title="snake_model" width="480" height="360" class="aligncenter size-full wp-image-444" /></p>
<p>To achieve movement, the position of the head segment is passed to the next segment, and the next segment on to its next segment so on and so forth until the tail is reached.</p>
<p>Each time the snake moves, its <img src='http://l.wordpress.com/latex.php?latex=x%5E%7B%28k%29%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x^{(k)}' title='x^{(k)}' class='latex' /> coordinate will be calculated as <img src='http://l.wordpress.com/latex.php?latex=x_%7Bn%2B1%7D%5E%7B%28k%29%7D+%3D+x_%7Bn%7D%5E%7B%28k%29%7D+%2B+dx_%7B%5Ctext%7Bdir%7D%7D%5E%7B%28k%29%7D+%5Cpmod%7BB%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='x_{n+1}^{(k)} = x_{n}^{(k)} + dx_{\text{dir}}^{(k)} \pmod{B}' title='x_{n+1}^{(k)} = x_{n}^{(k)} + dx_{\text{dir}}^{(k)} \pmod{B}' class='latex' />.</p>
<p>Scoring should be done in such a way that rewards become more valuable as time continues. Since the initial length of the snake is 1, a snake of length <img src='http://l.wordpress.com/latex.php?latex=N&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N' title='N' class='latex' /> will have collected <img src='http://l.wordpress.com/latex.php?latex=N+-+1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N - 1' title='N - 1' class='latex' /> rewards. Thus, let <img src='http://l.wordpress.com/latex.php?latex=S%28N%29+%3D+%5Csum_%7Bn+%3D+0%7D%5E%7BN%7D%7B100+%281+-+e%5E%7B%5Cfrac%7B-%28N+-+1%29%7D%7B10%7D%7D%29%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='S(N) = \sum_{n = 0}^{N}{100 (1 - e^{\frac{-(N - 1)}{10}})}' title='S(N) = \sum_{n = 0}^{N}{100 (1 - e^{\frac{-(N - 1)}{10}})}' class='latex' /> represent the scoring function. Where 100 is maximum score for a reward, -1/10 is the decay factor.</p>
<p>Once a snake has consumed a reward, a new node is added to the tail with a location identical to the tail location.</p>
<p>To determine if a the snake is on top of a reward, each segment&#8217;s position will be compared to the reward&#8217;s position. If a segment and reward are identical then the snake is on top of the reward. If no match is found, then the snake is not on top of the reward. This process can be done in linear time. Constant time, if you choose to generate rewards that are not on top of snake.</p>
<p>When drawing the game it is useful to observe that the only thing that ever changes between time step is the the head and tail of the snake. Thus, it is prudent to only draw the current head position and erase the previous tail position. This will produce a length independent drawing method so that the game does not appear to be slower as the snake gets larger.</p>
<p>Implementations may be written using recursion, but beware that with larger board sizes that you run the risk of a stack overflow on systems that don&#8217;t give you much memory to work with. Using a cursor to search the singly-linked list may be more appropriate when using larger board sizes.</p>
<h2>Implementation</h2>
<p>I decided to go with a Model-View-Controller (MVC) pattern since I&#8217;d like to be able to view the CLI, 2DGUI and 3DGUI all at once. Below is a complete UML class diagram of all the MVC components that I choose to implement. </p>
<p><a href="http://antimatroid.files.wordpress.com/2009/02/snake21.png"><img src="http://antimatroid.wordpress.com/files/2009/02/snake21.png" alt="snake21" title="snake21" width="700" height="548" class="aligncenter size-full wp-image-483" /></a></p>
<p>The following is the core engine of the game; it perform each of the core tasks of performing logic, drawing the board, getting user input and maintaining time.</p>
<pre class="brush: csharp;">
public class Program {
    [STAThread]
    static public void Main(string[] args) {
        List views = new List(new IGameView[] {
            new CLIGameView(),
            new GUI2DGameView(),
            new GUI3DGameView()
        });
        IGameController controller = new CLIGameController();

        int boardSize = 32;
        double maxScore = double.MinValue;

        views.ForEach((view) =&gt; view.initialize(boardSize));

        do {
            SnakeDirection desiredDirection = SnakeDirection.Up;
            SnakePoint reward = SnakePoint.Random(boardSize);
            SnakeSegment snake = new SnakeSegment(SnakePoint.Random(boardSize));

            views.ForEach((view) =&gt; view.drawBoard());

            do {
                if (controller.InputAvailable) {
                    SnakeDirection possible = controller.getDirection();
                    if (possible != SnakeDirection.Nop)
                        desiredDirection = possible;
                }

                if (snake.isOnTopOf(reward)) {
                    snake.grow();

                    if (snake.Length != boardSize * boardSize) {
                        do {
                            reward = SnakePoint.Random(boardSize);
                        } while (snake.isOnTopOf(reward));
                    }

                    maxScore = Math.Max(maxScore, snake.Score);

                    views.ForEach((view) =&gt; view.drawScore(snake.Score, maxScore));
                }

                SnakePoint oldTail = snake.Tail.Location;

                snake.move(desiredDirection, boardSize);

                views.ForEach((view) =&gt; view.drawSnake(snake, oldTail));
                views.ForEach((view) =&gt; view.drawReward(reward));

                System.Threading.Thread.Sleep(1000 / 15);
            } while (!snake.selfCollision());

            views.ForEach((view) =&gt; view.drawGameOver());
            views.ForEach((view) =&gt; view.drawPlayAgain());

        } while (controller.playAgain());

        views.ForEach((view) =&gt; view.deinitialize());
        views.Clear();
    }
}
</pre>
<pre class="brush: csharp;">
public class GUI3DGameView : IGameView {
    private int boardSize;
    private Form canvas;
    private ScoreLabel score;
    private TorusScene scene;

    public int BoardSize {
        get { return boardSize; }
    }

    public GUI3DGameView() {
        canvas = new Form();
        canvas.BackColor = System.Drawing.Color.FromArgb(0x33,0x33,0x33);
        canvas.FormBorderStyle = FormBorderStyle.FixedToolWindow;
        canvas.MaximizeBox = false;
        canvas.MinimizeBox = false;
        canvas.SizeGripStyle = SizeGripStyle.Hide;
        canvas.Text = &quot;GUI3DGameView&quot;;
        canvas.ClientSize = new Size(384, 384);

        ElementHost host = new ElementHost();
        host.Child = scene = new TorusScene();
        host.Dock = DockStyle.Fill;
        canvas.Controls.Add(host);

        score = new ScoreLabel();
        score.Dock = DockStyle.Bottom;

        canvas.Controls.Add(score);
    }

    public void initialize(int boardSize) {
        this.boardSize = boardSize;

        if (!canvas.Visible)
            canvas.Show();
    }

    public void deinitialize() {
        canvas.Dispose();
    }

    public void drawBoard() {
        score.reset();
        scene.removeSnake();
    }

    public void drawGameOver() {

    }

    public void drawPlayAgain() {

    }

    public void drawReward(SnakePoint reward) {
        scene.moveReward(reward.x, reward.y);
    }

    public void drawScore(double current, double max) {
        score.setScore(current, max);
    }

    public void drawSnake(SnakeSegment head, SnakePoint oldTail) {
        scene.addSegment(head.Location.x, head.Location.y, head.Length);
    }
}
</pre>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace Snake.View.GUI3D {
    public class TorusScene : Viewport3D {
        private Queue&lt;ModelVisual3D&gt; patches;
        private ModelVisual3D reward;

        public TorusScene() {
            Camera = new PerspectiveCamera(new Point3D(10, 10, 10), new Vector3D(-10, -10, -10), new Vector3D(0, 1, 0), 60);

            AmbientLight aLight = new AmbientLight(Color.FromRgb(0x33,0x33,0x33));
            ModelVisual3D aLightHost = new ModelVisual3D();
            aLightHost.Content = aLight;
            Children.Add(aLightHost);

            DirectionalLight light = new DirectionalLight(Colors.Orange, new Vector3D(0, -10, 0));
            ModelVisual3D lightHost = new ModelVisual3D();
            lightHost.Content = light;
            Children.Add(lightHost);

            DirectionalLight rearLight = new DirectionalLight(Colors.LightBlue, new Vector3D(0, 10, 0));
            ModelVisual3D rearLightHost = new ModelVisual3D();
            rearLightHost.Content = rearLight;
            Children.Add(rearLightHost);

            Model3DGroup torus = new Model3DGroup();
            double N = 16.0;
            double dTheta = Math.PI / N, dPhi = Math.PI / N;
            double R = 5.0, r = 2.0;

            Color surface = SnakeColors.MGround;

            for (double theta = 0.0; theta &lt;= 2.0 * Math.PI; theta += dTheta) {
                for (double phi = 0.0; phi &lt;= 2.0 * Math.PI; phi += dPhi) {
                    Point3D[] S = square(dTheta, dPhi, R, r, theta, phi);
                    torus.Children.Add(triangle(S[0], S[1], S[3], surface));
                    torus.Children.Add(triangle(S[3], S[2], S[0], surface));
                }
            }

            ModelVisual3D model = new ModelVisual3D();
            model.Content = torus;
            Children.Add(model);

            patches = new Queue&lt;ModelVisual3D&gt;();
        }

        public void addSegment(double u, double v, int max) {
            ModelVisual3D snake = addSphere(u, v, 0.5, SnakeColors.MHead);

            if (patches.Count != 0 &amp;&amp; patches.Count == max)
                Children.Remove(patches.Dequeue());
            patches.Enqueue(snake);

            Point3D[] S = square(Math.PI / 16.0, Math.PI / 16.0, 5.0, 2.5, u / 16.0 * Math.PI, v / 16.0 * Math.PI);
            double r = 30.0 / Math.Sqrt(3.0) / Math.Sqrt(S[0].X * S[0].X + S[0].Y * S[0].Y + S[0].Z * S[0].Z);
            Camera.SetValue(PerspectiveCamera.PositionProperty, new Point3D(r * S[0].X, r * S[0].Y, r * S[0].Z));
            Camera.SetValue(PerspectiveCamera.LookDirectionProperty, new Vector3D(-r * S[0].X, -r * S[0].Y, -r * S[0].Z));
        }

        public void moveReward(double u, double v) {
            if (reward != null) {
                Children.Remove(reward);
                reward = null;
            }

            reward = addSphere(u, v, 0.25, SnakeColors.MReward);
        }

        public void removeSnake() {
            while (patches.Count != 0)
                Children.Remove(patches.Dequeue());
        }

        private ModelVisual3D addSphere(double u, double v, double r, Color color) {
            Model3DGroup sphere = new Model3DGroup();
            Point3D center = parameterized(5.0, 2.0 + r, u / 16.0 * Math.PI, v / 16.0 * Math.PI);
            Vector3D vec = new Vector3D(center.X, center.Y, center.Z);

            double dTheta, dPhi;
            dTheta = dPhi = Math.PI / 3.0;

            for (double theta = 0.0; theta &lt;= 2.0 * Math.PI; theta += dTheta) {
                for (double phi = 0.0; phi &lt;= 2.0 * Math.PI; phi += dPhi) {
                    Point3D[] S = square(dTheta, dPhi, 0, r, theta, phi);
                    for (int n = 0; n &lt; S.Length; n++)
                        S[n] = Point3D.Add(S[n], vec);

                    sphere.Children.Add(triangle(S[0], S[1], S[3], color));
                    sphere.Children.Add(triangle(S[3], S[2], S[0], color));
                }
            }

            ModelVisual3D model = new ModelVisual3D();
            model.Content = sphere;
            Children.Add(model);

            return model;
        }

        private Point3D parameterized(double R, double r, double theta, double phi) {
            return new Point3D(
                (R + r * Math.Cos(phi)) * Math.Cos(theta),
                r * Math.Sin(phi),
                (R + r * Math.Cos(phi)) * Math.Sin(theta)
            );
        }

        private Point3D[] square(double dTheta, double dPhi, double R, double r, double theta, double phi) {
            return new Point3D[] {
                parameterized(R, r, theta, phi),
                parameterized(R, r, theta, phi + dPhi),
                parameterized(R, r, theta + dTheta, phi),
                parameterized(R, r, theta + dTheta, phi + dPhi)
            };
        }

        private Model3DGroup triangle(Point3D a, Point3D b, Point3D c, Color color) {
            MeshGeometry3D mesh = new MeshGeometry3D();
            mesh.Positions.Add(a);
            mesh.Positions.Add(b);
            mesh.Positions.Add(c);
            mesh.TriangleIndices.Add(0);
            mesh.TriangleIndices.Add(1);
            mesh.TriangleIndices.Add(2);

            Material material = new DiffuseMaterial(new SolidColorBrush(color));
            GeometryModel3D model = new GeometryModel3D(mesh, material);
            Model3DGroup group = new Model3DGroup();
            group.Children.Add(model);
            return group;
        }
    }
}
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[.NET 'te Şifreleme Sınıflarını Kullanmak]]></title>
<link>http://ammoti.wordpress.com/2009/01/21/net-te-sifreleme-siniflarini-kullanmak/</link>
<pubDate>Wed, 21 Jan 2009 23:59:19 +0000</pubDate>
<dc:creator>ammoti</dc:creator>
<guid>http://ammoti.wordpress.com/2009/01/21/net-te-sifreleme-siniflarini-kullanmak/</guid>
<description><![CDATA[.NET platformu, kriptografik işlemler için kullanılabilecek zengin sınıflar içerir. .NET Platformund]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;"> .NET platformu, kriptografik işlemler için kullanılabilecek    zengin sınıflar içerir. .NET Platformunda kriptografik sınıfların çoğu, Windows    Cryptographic Service Providers (Windows kriptografik servis sağlayıcılar) için    yönetilen bir pakettir.</p>
<p>Hash Algoritmalarını Kullanmak :</p>
<p>Bir hash algoritması, uzunluğu belli olmayan bir dizenin içeriğini benzersiz  şekilde şifreleyerek bir değer üretir.Hash değerleri bir dosya içindeki  değişiklikleri tespit etmek için kullanışlıdır. Dosyanın durumunun herhangi bir  anda fotoğrafını çekme imkanı sunar. Bu Sayede bir önceki hash değerleri ile  dosyanın o andaki hash değerlerini karşılaştırarak dosyada değişiklik yapılmışmı  yapılmamışmı öğrenebilirsiniz.</p>
<p>.NET platformu içindeki sınıflar, aşağıdaki hash algoritmalarını kullanmaktadır.</span></span></strong></p>
<ul><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"></p>
<li><span style="font-family:Verdana;font-size:x-small;">MD5 &#8211; 128-bit hash değeri üretmektedir. MD5CryptoServiceProvider sınıfı  	tarafından uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">SAH1 &#8211; 160-bit hash değeri üretmektedir. SHA1CryptoServiceProvider ve  	SHA1Managed sınıfları tarafından uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">SHA256 &#8211; 256-bit hash değeri üretmektedir. SHA256CryptoServiceProvider  	ve SHA256Managed sınıfları tarafından uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">SHA384 &#8211; 384-bit hash değeri üretmektedir. SHA384CryptoServiceProvider  	ve SHA384Managed sınıfları tarafından uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">SHA512 &#8211; 512-bit hash değeri üretmektedir. SHA512CryptoServiceProvider  	ve SHA512Managed sınıfları tarafından uygulanmaktadır.</span></li>
<p></span></strong></ul>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Not : MD5 en hızlı fakat en az güvenli algoritmadır. Her SHA algoritması daha  güvenlidir ama daha falza hesaplama gerektirmektedir.</span></span></strong></p>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Örnek:</span></span></strong></p>
<table id="table1" border="0" cellspacing="0" cellpadding="5" width="100%" bgcolor="#ffcc66">
<tbody>
<tr>
<td><span style="color:#ff0000;"><strong><span style="font-size:x-small;">static byte[] ByteDonustur(string deger)<br />
{<br />
char[] arrayChar = deger.ToCharArray();<br />
byte[] arrayByte = new byte[arrayChar.Length];</p>
<p>for (int i = 0; i &#60; arrayByte.Length &#8211; 1; i++)<br />
{<br />
arrayByte[i] =  		Convert.ToByte(arrayChar[i]);<br />
}</p>
<p>return arrayByte;<br />
}</p>
<p>static void Main(string[] args)<br />
{<br />
MD5CryptoServiceProvider md5 = new  		MD5CryptoServiceProvider();<br />
byte[] deger = ByteDonustur(&#8220;ABCDEFG&#8221;);<br />
byte[] sonuc = md5.ComputeHash(deger);</p>
<p>Console.WriteLine(BitConverter.ToString(sonuc));<br />
Console.ReadLine();<br />
}</span></strong></span></td>
</tr>
</tbody>
</table>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;"><img src="http://www.csharpnedir.com/mimages/TugrulUgurlu/mk1_1.gif" border="0" alt="" width="381" height="34" /></span></span></strong></p>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">İşleminden çıkan sonucun değeri.</p>
<p>Burada dikkat edilmesi gereken hususlara gelecek olursak ComputeHash() Metoduna  bir dizeyi doğrudan geçiremezsiniz. ByteDonustur() Metodu kullanılarak dize  ComputeHash() verilmeden önce byte dizisine dönüştürülmektedir.ComputeHash()  metodu tarafından geri döndürülen byte dizisi BitConverter sınıfı ile dizeye  geri dönüştürülmektedir.</p>
<p>SİMETRİK ŞİFRELEME ALGORİTMALARI</p>
<p>Bir veriyi simetrik bir veri algoritması ile şifrelediğinizde gönderici ve  alıcının aynı şifre çözücü anahtara sahip olmak zorundadır.</p>
<p>.NET platformundaki sınıflar aşağıdaki simetrik algoritmaları desteklemektedir.</span></span></strong></p>
<ul><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"></p>
<li><span style="font-family:Verdana;font-size:x-small;">DES &#8211; Birleşik Devletler Veri Şifreleme Standartı (Data Encryption  	Standart) : Bu algoritma DESCryptoServiceProvider sınıfı tarafından  	uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">Triple DES &#8211; DES algoritması sıralı şekilde üç farklı şifreleme anahtarı  	ile uygulanır. Bu algoritma TripleDESCryptoServiceProvider sınıfı tarafından  	uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">RC2 &#8211; RC2 Blok Şifresi (Block Cipher). Bu algoritma  	RC2CryptoServiceProvider sınıfı tarafından uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">Rijndael &#8211; İleri Düzey Şifreleme Standartı tarafından kullanılan  	algoritmadır. Bu algoritma RijndaelManaged sınıfı tarafından  	uygulanmaktadır.</span></li>
<p></span></strong></ul>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Örnek : SimetrikWrite.cs</span></span></strong></p>
<table id="table2" border="0" cellspacing="0" cellpadding="5" width="100%" bgcolor="#ffcc66">
<tbody>
<tr>
<td><span style="color:#ff0000;"><strong><span style="font-size:x-small;">class SimetrikWrite<br />
{<br />
const string desKey = &#8220;12345678&#8243;;<br />
const string desIv = &#8220;ABCDEFGH&#8221;;</p>
<p>static byte[] ByteDonustur(string deger)<br />
{<br />
char[] arrayChar =  		deger.ToCharArray();<br />
byte[] arrayByte = new  		byte[arrayChar.Length];</p>
<p>for (int i = 0; i &#60; arrayByte.Length;  		i++)<br />
{<br />
arrayByte[i]  		= Convert.ToByte(arrayChar[i]);<br />
}</p>
<p>return arrayByte;<br />
}</p>
<p>static void Main(string[] args)<br />
{<br />
byte[] arrayDESKey =  		ByteDonustur(desKey);<br />
byte[] arrayDESIV =  		ByteDonustur(desIv);<br />
byte[] arrayInput =  		ByteDonustur(&#8220;Merhaba Dünya&#8221;);</p>
<p>DESCryptoServiceProvider des = new  		DESCryptoServiceProvider();</p>
<p>//Formun en üstünde desKey ve desIv  		isimli iki tane sabit var. DESCryptoServiceProvider sınıfı ile veriyi  		şifrelediğinizde hem gizli bir anahtar hem de bir ilk değer vektörü  		sağlamalısınız çünkü yarattığınız dosyadaki şifreyi çözmek istediğinizde  		ihtiyaç duyacaksınız. Bu dizilere istediğiniz 8 karakter dizesini  		atayabilirsiniz.<br />
ICryptoTransform cEncryptor =  		des.CreateEncryptor(arrayDESKey, arrayDESIV);<br />
CryptoStream cStream = new  		CryptoStream(new FileStream(&#8220;c:simetrik.text&#8221;, FileMode.Create,  		FileAccess.Write),cEncryptor, CryptoStreamMode.Write);<br />
cStream.Write(arrayInput,0,arrayInput.Length);<br />
cStream.Close();<br />
Console.ReadLine();<br />
}<br />
}</span></strong></span></td>
</tr>
</tbody>
</table>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Örnek : SimetrikRead.cs</span></span></strong></p>
<table id="table3" border="0" cellspacing="0" cellpadding="5" width="100%" bgcolor="#ffcc66">
<tbody>
<tr>
<td><span style="color:#ff0000;"><strong><span style="font-size:x-small;">class SimetrikRead<br />
{<br />
//Bu sabitlerin değeri SimetrikWriter Dosyasındaki desKey ve  		desIv sabitleri ile uyuşmalıdır.<br />
const string desKey = &#8220;12345678&#8243;;<br />
const string desIv = &#8220;ABCDEFGH&#8221;;</p>
<p>static byte[] ByteDonustur(string deger)<br />
{<br />
char[] arrayChar =  		deger.ToCharArray();<br />
byte[] arrayByte = new  		byte[arrayChar.Length];</p>
<p>for (int i = 0; i &#60; arrayByte.Length;  		i++)<br />
{<br />
arrayByte[i]  		= Convert.ToByte(arrayChar[i]);<br />
}</p>
<p>return arrayByte;<br />
}</p>
<p>static void Main(string[] args)<br />
{<br />
byte[] arrayDesKey =  		ByteDonustur(desKey);<br />
byte[] arrayDesIv =  		ByteDonustur(desIv);</p>
<p>DESCryptoServiceProvider des = new  		DESCryptoServiceProvider();<br />
ICryptoTransform cDecryptor =  		des.CreateDecryptor(arrayDesKey,arrayDesIv);<br />
CryptoStream cStream = new  		CryptoStream(new FileStream(&#8220;C:simetrik.text&#8221;,  		FileMode.Open),cDecryptor, CryptoStreamMode.Read);<br />
Console.WriteLine(new  		StreamReader(cStream).ReadToEnd());<br />
Console.ReadLine();<br />
}<br />
}</span></strong></span></td>
</tr>
</tbody>
</table>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">ASİMETRİK ŞİFRELEME KULLANMAK</p>
<p>Simetrik şifreleme algoritması kullandığımız zaman, uygulamayı kullananların  aynı ortak şifre çözücü anahtara sahip olmaları gerekir. Asimetrik şifreleme  algoritması kullandığınız zaman veriyi şifrelemek ve çözmek için kullanılan  anahtar farklıdır. Asimetrik şifreleme algoritmaları bir anahtar çifti kullanır.  Eğer veriyi bir anahtar ile şifrelediyseniz çözmek için diğer anahtarı  kullanırsınız.</p>
<p>.NET platformundaki sınıflar aşağıdaki asimetrik algoritmaları desteklemektedir.</span></span></strong></p>
<ul><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"></p>
<li><span style="font-family:Verdana;font-size:x-small;">DSA &#8211; Dijital İmza Algoritması(Digital Signature Algorithm &#8211; Birleşik  	Devletler Hükümetinin Dijital Doğrulama Standartı). DSACryptoServiceProvider  	sınıfı tarafından uygulanmaktadır.</span></li>
<li><span style="font-family:Verdana;font-size:x-small;">RSA &#8211; Bu Algoritma, RSACryptoServiceProvider sınfı tarafından  	uygulanmaktadır.</span></li>
<p></span></strong></ul>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Her iki metodta AsymmetricAlgorithm sınıfında uygulanmaktadır. Bu yüzden aynı  metod ve özelliklerin bir çoğunu paylaşmaktadırlar. Sınıflardan herhangi  birisini yaratırsanız, genel ve özel anahtarları otomatik olarak üretilir.Genel  veya özel anahtara ToXmlString ya da ExportParameters metotları ile  erişebilirsiniz. ToXmlString metodu, genel ve özel anahtarları XML dizesinde  tutar.</p>
<p>Aşağıdaki örnekte DSACryptoServiceProvider sınıfını yaratıp özel ve genel  anahtarlarını görüntülemektedir.</span></span></strong></p>
<table id="table4" border="0" cellspacing="0" cellpadding="5" width="100%" bgcolor="#ffcc66">
<tbody>
<tr>
<td><span style="color:#ff0000;"><strong><span style="font-size:x-small;">DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();</p>
<p>Console.Write(&#8220;Özel Anahtarlar : &#8220;);<br />
//Özel Anahtarı Görüntülemek İçin true<br />
Console.WriteLine(dsa.ToXmlString(true));</p>
<p>Console.Write(&#8220;Genel Anahtarlar : &#8220;);<br />
//Genel Anahtarı Görüntülemek İçin false<br />
Console.WriteLine(dsa.ToXmlString(false));</span></strong></span></td>
</tr>
</tbody>
</table>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">İşlemin sonucunda aşağıdakine benzer bir çıktı üretecektir.</span></span></strong></p>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;"> <img src="http://www.csharpnedir.com/mimages/TugrulUgurlu/mk1_2.gif" border="0" alt="" width="645" height="319" /></span></span></strong></p>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">örn : AsimetrikWrite.cs</span></span></strong></p>
<table id="table5" border="0" cellspacing="0" cellpadding="5" width="100%" bgcolor="#ffcc66">
<tbody>
<tr>
<td><strong><span style="font-family:Verdana;font-size:x-small;"><span style="color:#ff0000;">class AsimetrikWrite<br />
{<br />
static void Main(string[] args)<br />
{<br />
byte[] dizi = {1,2,3,4,5,6,7};</p>
<p>RSACryptoServiceProvider rsa = new  		RSACryptoServiceProvider();<br />
byte[] sonucEncrypt =  		rsa.Encrypt(dizi,false);</p>
<p>for(int i = 0; i &#60;  		sonucEncrypt.Length; i++)<br />
Console.Write(sonucEncrypt[i] + &#8221; &#8220;);<br />
}</span><br />
}</span></strong></td>
</tr>
</tbody>
</table>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Çıktı Sonucu Aşağıdaki Gibi Olmalıdır.</span></span></strong></p>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;"><img src="http://www.csharpnedir.com/mimages/TugrulUgurlu/mk1_3.gif" border="0" alt="" width="645" height="76" /></span></span></strong></p>
<table id="table6" border="0" cellspacing="0" cellpadding="5" width="100%" bgcolor="#ffcc66">
<tbody>
<tr>
<td><span style="color:#ff0000;"><strong><span style="font-size:x-small;">class AsimetrikRead<br />
{<br />
static void Main(string[] args)<br />
{<br />
byte[] dizi = {1,2,3,4,5,6,7};</p>
<p>RSACryptoServiceProvider rsa = new  		RSACryptoServiceProvider();<br />
byte[] sonucEncrypt =  		rsa.Encrypt(dizi,false);</p>
<p>for(int i = 0; i &#60;  		sonucEncrypt.Length; i++)<br />
Console.Write(sonucEncrypt[i] + &#8221; &#8220;);</p>
<p>Console.WriteLine(&#8220;nn&#8221;);</p>
<p>byte[] sonucDecrypt =  		rsa.Decrypt(sonucEncrypt,false);</p>
<p>for(int i = 0; i &#60;  		sonucDecrypt.Length; i++)<br />
Console.Write(sonucDecrypt[i] + &#8221; &#8220;);</p>
<p>Console.ReadLine();<br />
}<br />
}</span></strong></span></td>
</tr>
</tbody>
</table>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Decrypt İşleminin Sonucu Aşa</span></span><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">ğıdaki Gibi Olmalıdır.</span></span></strong></p>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;"><img src="http://www.csharpnedir.com/mimages/TugrulUgurlu/mk1_4.gif" border="0" alt="" width="135" height="29" /></span></span></strong></p>
<p><strong><span style="font-family:Verdana,Arial,Helvetica,sans-serif;font-size:x-small;"><span style="font-family:Verdana;font-size:x-small;">Tuğrul Uğurlu</span></span></strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[LINQ Resources]]></title>
<link>http://vakul.wordpress.com/2009/01/16/linq-resources/</link>
<pubDate>Sat, 17 Jan 2009 04:16:39 +0000</pubDate>
<dc:creator>Vakul Kumar More</dc:creator>
<guid>http://vakul.wordpress.com/2009/01/16/linq-resources/</guid>
<description><![CDATA[LINQ: Language-Integrated Query (LINQ) is a groundbreaking innovation in Visual Studio 2008 and the ]]></description>
<content:encoded><![CDATA[LINQ: Language-Integrated Query (LINQ) is a groundbreaking innovation in Visual Studio 2008 and the ]]></content:encoded>
</item>
<item>
<title><![CDATA[Anonymous Methods and Lambdas.]]></title>
<link>http://halwagy.wordpress.com/2009/01/10/anonymous-methods-and-lambdas/</link>
<pubDate>Sat, 10 Jan 2009 02:16:29 +0000</pubDate>
<dc:creator>Ahmed</dc:creator>
<guid>http://halwagy.wordpress.com/2009/01/10/anonymous-methods-and-lambdas/</guid>
<description><![CDATA[A while ago, when I posted my last post on this blog which was titles (Delegates and Events &#8211; ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>A while ago, when I posted my last <a href="http://halwagy.wordpress.com/2008/12/11/delegates-and-events-%E2%80%93-a-look-back/">post</a> on this blog which was titles (Delegates and Events &#8211; A Look Back), I stated that it was an introduction to Lambda Expressions. Though it took me more than a month to re-blog again, here i&#8217;m continuing the journey on the C# 3.0 language enhancements features. The first thing we will discuss here is anonymous methods, as you know anonymous methods is just a shorthand way for subscribing to events and providing handlers all in one shot. The following code example shows the old way to subscribe to a Click event on a normal System.Windows.Forms.Button object.</p>
<p><a href="http://halwagy.files.wordpress.com/2009/01/code1.jpg"><img class="alignleft size-full wp-image-75" title="code1" src="http://halwagy.wordpress.com/files/2009/01/code1.jpg" alt="code1" width="480" height="162" /></a></p>
<p>This is the very classic way of subscribing to event. You simply need to provide a pre-defined delegate (in this case EventHandler) that points to a function matching a specific signature (in this case returns void and accepts two input parameters an System.Object parameter, and System.EventArgs parameter) . Using anonymous methods, life can be easier. Check out the next code sample.</p>
<p><a href="http://halwagy.files.wordpress.com/2009/01/code2.jpg"><img class="alignleft size-full wp-image-76" title="code2" src="http://halwagy.wordpress.com/files/2009/01/code2.jpg" alt="code2" /></a></p>
<p>As you can see here, all I needed to do in order to subscribe to the Click event on the Button object is to simply write my code that handles the event without having to define a whole new function just to handle this event, and also without having to know the event&#8217;s delegate signature.</p>
<p><strong>Lambdas </strong></p>
<p>Lambda expressions are another new way in C# 3.0 to substitute delegates in certain places. Now consider the following example, if you have a List&#60;int&#62;  and you want to filter this list and get only all the odd numbers out of it. One solution that might come handy is to use the FindAll method of your generic List&#60;int&#62;. FindAll expects one argument which in fact is of type System.Predicate&#60;T&#62;. System.Predicate&#60;T&#62; is a delegate that can point to any methods returns bool and takes a single argument T. The point is when FindAll was designed it was designed as this(take each item, check it, and then tell me if it should be included in the result set of the call).</p>
<p>The follwoing example illustrates the use of the smart FindAll method, take a look:</p>
<p><a href="http://halwagy.wordpress.com/files/2009/01/code3.jpg"><img class="alignleft size-full wp-image-77" title="code3" src="http://halwagy.wordpress.com/files/2009/01/code3.jpg" alt="code3" /></a></p>
<p>As you see here I&#8217;ve defined a method called IsOdd that takes a single integer parameter and returns a boolean value indicating whether the passed in parameter is odd or not. I then called the FindAll method on my list of integers (numbers) passing in a new Predicated delegate that points to IsOdd. What is going to happen here is my numbers list will take each element of it and pass it to the IsOdd(the method that the Predicate delegate points to) and check the value returned, if true, then the item will be added to the result set. If false then the item will be ignored. If you run the above code you will get the following result.</p>
<p><a href="http://halwagy.wordpress.com/files/2009/01/code41.jpg"><img class="alignleft size-full wp-image-79" title="code41" src="http://halwagy.wordpress.com/files/2009/01/code41.jpg" alt="code41" /></a></p>
<p>Now, what if you don&#8217;t want to define this whole IsOdd method that makes a really tiny job here and will not be reused by any other peace of code? Well, you guessed it, use anonymous method syntax like this:<br />
<a href="http://halwagy.wordpress.com/files/2009/01/code5.jpg"><img src="http://halwagy.wordpress.com/files/2009/01/code5.jpg" alt="code5" title="code5" width="480" height="44" class="alignleft size-full wp-image-80" /></a></p>
<p>A lambda expression is another handy way for providing an anonymous method. The syntax might seem clumsy at first, but once you get it, you never quit it <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </p>
<p><a href="http://halwagy.wordpress.com/files/2009/01/code6.jpg"><img src="http://halwagy.wordpress.com/files/2009/01/code6.jpg" alt="code6" title="code6" class="alignleft size-full wp-image-81" /></a></p>
<p>What you see here is a lambda expression in action. The FindAll method expects a delegate and this time instead of passing it a delegate or an anonymous method I passed in well, a lambda, a lambda that will operate on one single integer parameter and return the the result of the expression x % 2 != 0.<br />
The thing that most people find uncomfortable about lambdas is that, they can&#8217;t pronounce it, yeah, they write it but they can&#8217;t pronounce it. Our above example will be pronounce as follows (My only parameter will be processed this way &#8220;as what between the {} stats&#8221;).<br />
A lambda expression can be in one of two forms; a single line form and a code block form. In our example we wrote a single statement in between two curly brackets, in fact I could have wrote any number of statements as needed. I will show you how lambda expressions can be appeared in a single line form:<br />
<a href="http://halwagy.wordpress.com/files/2009/01/code7.jpg"><img src="http://halwagy.wordpress.com/files/2009/01/code7.jpg" alt="code7" title="code7" class="alignleft size-full wp-image-82" /></a></p>
<p>Well that&#8217;s it for lambdas, any questions or suggestions feel absolutely free to leave a comment.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[C# Extension Method and Lambda Expressions]]></title>
<link>http://johngilliland.wordpress.com/2009/01/07/c-extension-method-and-lambda-expressions/</link>
<pubDate>Wed, 07 Jan 2009 20:40:22 +0000</pubDate>
<dc:creator>John Gilliland</dc:creator>
<guid>http://johngilliland.wordpress.com/2009/01/07/c-extension-method-and-lambda-expressions/</guid>
<description><![CDATA[Recently I have been trying to learn more about the new language features in C# 3.0, and I have enjo]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Recently I have been trying to learn more about the new language features in C# 3.0, and I have enjoyed what I have found thus far.  Especially both the var keyword and extension methods, but I had yet to really implement anything using lambdas.  That is until today&#8230;</p>
<p>One of the things I have done with <a title="Argument Validation using C# Extension Methods" href="http://johngilliland.wordpress.com/2009/01/07/argument-validation-using-c-30-extension-methods/">extension methods</a> was to implement some really sweet method argument validation stuff.  I had read several related blog entries regarding this subject and had whipped up a variation [actually just a much smaller set of what they had already come up with as my needs were much less] of their ideas for use in a project I am working on [and likely in future projects].   And, as it turns out, this same bit of features afforded me the opportunity to check out lambda expressions as well, and to hopefully this time add something of value to build on their work instead of just reusing it.</p>
<p>Okay so the scene is set, with me at my desk at work, coding a unit test for what I hope will be a new feature on my current project [dynamically executed reports from xml definition files, like rdl but much much simpler]&#8230;</p>
<p>I was about to use the argument extension methods to validate an integer that I needed to be in a certain range and it occured to me how nice it would be if I could just pass in an expression that evaluated to a boolean result similar to what I would do if I was writing in javascript.  Yeah, that would be extra nice!  So, off I went back to GOG to do some research on passing an expression as an argument to a function in C#.  My research led me straight to <a title="Lambda Expressions, new C# 3.0 Feature" href="http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx">lambda expressions</a> and exactly what I needed to make my new extension method work.</p>
<p style="padding-left:30px;">My goal was to be able to implement something like the following psuedo-code:</p>
<pre class="brush: csharp;">
public void MyFunction(int myInt)
{
    RequireThat(myInt).MeetsCriteria(&quot;myInt &gt; 0&quot;);
}
</pre>
<p>Thus being able to use some very smooth and descriptive code to validate my integer argument before using it in the function, or atleast something as close to that effect as I could get.</p>
<p>Well lambda expressions were exactly the ticket, specifically the <a title="MSDN Reference for Func&#60;T, TResult&#62; delegate type." href="http://msdn.microsoft.com/en-us/library/bb549151.aspx">Func&#60;T, TResult&#62;</a> delegate type.  Which basically allows me to pass a method that accepts one parameter of type T and returns a result of type TResult as a parameter to another method, without defining a custom delegate type of my own.  A kinda anonymous delegate type construct if you will.  Lambda expressions use this type as an arg for the <a title="Code Project Article on Expressions" href="http://www.codeproject.com/KB/linq/Expressions.aspx">Expression&#60;T&#62;(Func&#60;T, TResult)</a> type constructor.   I have done some of this preliminary reading on Expression Trees and such and it is heady stuff, but interesting none the less.  I look forward to someday being able to apply it to a real world problem.  </p>
<p>But today I was able to apply lambdas to my real world problem like so:</p>
<p>I needed an extension method for my <a title="Argument validation with extension methods." href="http://johngilliland.wordpress.com/2009/01/07/argument-validation-using-c-30-extension-methods/">Generic argument wrapper</a> that would allow me to pass in a simple expression predicate with which to validate the argument.  And here is what I came up with:</p>
<div id="attachment_25" class="wp-caption aligncenter" style="width: 359px"><img class="size-full wp-image-25 " title="Code for MeetsCriteria extension method." src="http://johngilliland.wordpress.com/files/2009/01/meetscriteria.png" alt="Code for MeetsCriteria extension method." width="349" height="281" /><p class="wp-caption-text">Code for MeetsCriteria extension method.</p></div>
<p>Now this code allows me to pass in a lambda expression that I wish to use to validate an integer argument for my method [or any integer for that matter].  This method was added to my existing argument validation extension methods setup as described in a previous post, already linked to a couple of times above, so it follows similar usage syntax, as such:</p>
<pre style="padding-left:30px;">myIntArg.RequireThat(<span style="color:#800000;">"myIntArg"</span>).MeetsCriteria(...);</pre>
<p>I also added a unit test for this new method into my existing test project for the rest of my validation extension methods, and so I will use that test method to show you a contextual usage of MeetsCriteria&#8230;</p>
<div id="attachment_26" class="wp-caption aligncenter" style="width: 391px"><img class="size-full wp-image-26" title="meetscriteria.test.png" src="http://johngilliland.wordpress.com/files/2009/01/meetscriteriatest.png" alt="My unit test for MeetsCriteria method.  Testing that 21 is between 20 and 22." width="381" height="163" /><p class="wp-caption-text">My unit test for MeetsCriteria method.  Testing that 21 is between 20 and 22.</p></div>
<p>So, now I have actually used lambdas in a project at work, I am so very happy with myself.  And my quest to conquer C# 3.0 features continues&#8230; J</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Argument Validation using C# 3.0 extension methods]]></title>
<link>http://johngilliland.wordpress.com/2009/01/07/argument-validation-using-c-30-extension-methods/</link>
<pubDate>Wed, 07 Jan 2009 18:11:38 +0000</pubDate>
<dc:creator>John Gilliland</dc:creator>
<guid>http://johngilliland.wordpress.com/2009/01/07/argument-validation-using-c-30-extension-methods/</guid>
<description><![CDATA[ After some research into reusable arg validation ideas on GOG (good ole google) I have found someth]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p> After some research into reusable arg validation ideas on GOG (good ole google) I have found something that, after some simplification of course, will serve the projects meager argument validation needs. Actually this is a super cool trick that we can reuse any number of places from here on, if we so desire.  Here are the original posts that I read and have taken ideas from, particularly Roger Alsings articles, much thanks to him.  This technique is, IMHO, a nice way to showcase how to combine some of C#&#8217;s new features, specifically Generics from C# 2.0 and Extension methods from C# 3.0, into a nice solution to a frequent problem.  </p>
<blockquote><p>- <a href="http://rogeralsing.com/2008/05/10/followup-how-to-validate-a-methods-arguments/">http://rogeralsing.com/2008/05/10/followup-how-to-validate-a-methods-arguments/</a><br />
- <a href="http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx">http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx<br />
</a>- <a href="http://www.puzzleframework.com/wikiengine/WikiPageViewer.aspx?ID=78">http://www.puzzleframework.com/wikiengine/WikiPageViewer.aspx?ID=78</a></p></blockquote>
<p>Using these posts and the code from a much larger api at the puzzle framework address in the quote above, i have assembled a smaller set of argument validation methods.  Roger Alsing&#8217;s puzzle framework has a full compliment of these validation methods if you are interested.  I, on the other hand swiped just a couple of his and added a couple of my own, but am using the same technique to acheive a fluent interface and also the very ingenius idea he had of using a wrapper class for the extension methods rather than extending each .NET type on its own.  Very nice work by him.  This article is simply an effort to explain how I used these articles to put together a much smaller set of validation methods for my own use in a project.  Hopefully it explains things clearly and pays sufficient homage to the ideas originator.</p>
<p> </p>
<p>The basic premise is that now with generics and extension methods features of C# we are able to add functionality to types/classes. In this case all types, for the purpose of validating method arguments. The articles above explore this in a progressive fashion: First presenting the idea of an ArgumentHelper class that would have lots of overloads for validating various C# types, i.e. int, string, double, etc. Under this scheme you would need a separate method for each type of validation for each type. Such as:</p>
<pre class="brush: csharp;">
public void RequireNotNull(int arg, string argName);
public void RequireNotNull(string arg, string argName);
public void RequireNotNull(DateTime arg, string argName);
...
</pre>
<p>This is not a bad idea, and certainly is better than writing a multiline if statement for each argument in each method in your project. Second Idea: was to use extension methods to facilitate usage syntax like:</p>
<pre class="brush: csharp;">
public void MyMethod(int argument1, string argument2)
{
    // validate args
    argument1.RequireInRange(argument1, 0, 10, &quot;argument1&quot;);
    argument2.RequireNotNull(argument2, &quot;argument2&quot;);
}
</pre>
<p>Now this is starting to look pretty smooth, however we go one step further, combining the new features of Generics(C# 2.0) and Extension methods (C# 3.0) to get something that is SUPER smooth. The idea, which was of course new to me, is to a) create a generic type for argmuments. I used one similar to theirs, basically just a container for name and value of an argument the value being the arg itself of the type &#8220;T&#8221; as defined by the generic. Then b) use extension methods to add validation methods to this generic class, thus making them available to any type. Here is my generic argument container class that is the one extended:</p>
<pre class="brush: csharp;">
public class ArgumentEx&lt;T&gt;
{
    public T Value { get; set; }
    public string Name { get; set; }
    public ArgumentEx(T value, string name)
    {
        this.Value = value;
        this.Name = name;
    }   
    public static implicit operator T(ArgumentEx&lt;T&gt; arg)
    {
        return arg.Value;
    }
}
</pre>
<p>This class simply wraps an argument with a generic container in essence. We set the default operator to return the arg itself (the &#8220;Value&#8221; member) and create a simple ctor. Now instead of having to write an extension method for each type we want to be able to validate (int, string, etc.) we just write one extension method for this class. First we write an extension method for the generic T type of our generic class and that will give us coverage of all types and this will always return us an instance of our new ArgumentEx type:</p>
<pre class="brush: csharp;">
public static class ValidatorExtensions
{
    public static ArgumentEx&lt;T&gt; RequireThat&lt;T&gt;(
        this T arg, string name)&lt;/pre&gt;
&lt;pre style=&quot;padding-left:30px;&quot;&gt;    {
        return new ArgumentEx&lt;T&gt;(arg, name);
    }
}
</pre>
<p>Now we can call this RequireThat method from any argument we pass in to any method and we will get back our ArgumentEx class which we have extended with validation methods such as this:</p>
<pre class="brush: csharp;">
[DebuggerHidden]
public static ArgumentEx&lt;T&gt; NotNull&lt;T&gt;(
    this ArgumentEx&lt;T&gt; arg) where T : class
{           
    if (arg.Value == null)
        throw new ArgumentNullException(arg.Name);
    return arg;     // for fluency
}
</pre>
<p>This method extends the ArgumentEx type rather than the generic T type so we have all of our extension methods hanging off of the wrapper class. This setup is a touch abstract but it allows us to do super pretty things like this:</p>
<pre class="brush: csharp;">
public ReportInfo(string pathToXmlFile)
    : base(null, null)         
{
    // validate args
    pathToXmlFile.RequireThat(&quot;pathToXmlFile&quot;).IsNotNull();           
}
</pre>
<p>not bad in the way of readability and extensibility too. Because the extension methods return the arg instance every time you can chain calls as well.</p>
<p> </p>
<p>Below is the class diagram for the validation/argument extensions.  There are a few string extensions too added for convenience&#8230;</p>
<p> </p>
<div id="attachment_36" class="wp-caption aligncenter" style="width: 420px"><a href="http://johngilliland.files.wordpress.com/2009/01/extensionsclasses.png"><img class="size-full wp-image-36 " title="Validation Extension Classes" src="http://johngilliland.wordpress.com/files/2009/01/extensionsclasses.png" alt="Class diagram for the validation extension classes." width="410" height="350" /></a><p class="wp-caption-text">Class diagram for the validation extension classes.</p></div>
<p> </p>
<p> </p>
<p> </p>
<p>And here is a screenshot of the unit tests all green and pretty!</p>
<p> </p>
<div id="attachment_37" class="wp-caption aligncenter" style="width: 555px"><a href="http://johngilliland.files.wordpress.com/2009/01/extenstionsunittests.png"><img class="size-full wp-image-37 " title="Validation Extension UnitTests" src="http://johngilliland.wordpress.com/files/2009/01/extenstionsunittests.png" alt="A screenshot of the pretty green unit test results!" width="545" height="242" /></a><p class="wp-caption-text">A screenshot of the pretty green unit test results!</p></div>
<p> </p>
<p> </p>
<p> </p>
<p>So now I have an easy to use and further extensible system for validating method arguments with out having to write if/throw constructs over and over inside of each method.  This promotes better code because the easier it is to validate my arguments the more likely it is that I will do a thorough job of it.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Lazy Computation in C# (Ленивые вычисления в C#)]]></title>
<link>http://butaji.wordpress.com/2009/01/02/lazy-computation-in-c-%d0%bb%d0%b5%d0%bd%d0%b8%d0%b2%d1%8b%d0%b5-%d0%b2%d1%8b%d1%87%d0%b8%d1%81%d0%bb%d0%b5%d0%bd%d0%b8%d1%8f-%d0%b2-c/</link>
<pubDate>Fri, 02 Jan 2009 11:11:40 +0000</pubDate>
<dc:creator>butaji</dc:creator>
<guid>http://butaji.wordpress.com/2009/01/02/lazy-computation-in-c-%d0%bb%d0%b5%d0%bd%d0%b8%d0%b2%d1%8b%d0%b5-%d0%b2%d1%8b%d1%87%d0%b8%d1%81%d0%bb%d0%b5%d0%bd%d0%b8%d1%8f-%d0%b2-c/</guid>
<description><![CDATA[Немного теории. Большинство современных языков разработки, используемых на практике (таких как C#, V]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2 style="width:459px;height:28px;">Немного теории.</h2>
<p>Большинство современных языков разработки, используемых на практике (таких как C#, VB.NET, C++, Python и Java) реализуют так называемые <a href="http://en.wikipedia.org/wiki/Eager_evaluation">немедленные вычисления</a>, это означает, что операция выполняется, так только становятся известны значения её операндов. Однако, ясно, что немедленное вычисление многих функций не всегда необходимо и рационально с точки зрения производительности, поэтому само собой напрашивается решение, позволяющее отложить эти вычисления на тот момент, когда они нам будут действительно нужны.</p>
<p>Мартин Фаулер в свой книге <a href="http://www.books.ru/shop/books/156126?partner=butaji">PoEAA</a> вводит понятие паттерна <a href="http://martinfowler.com/eaaCatalog/lazyLoad.html">Lazy Load</a> (загрузка по требованию, ленивая загрузка), суть которого состоит в том, что объект не содержит данные, но знает где их взять, если они ему станут нужны. Это как раз то, о чём мы и ведем речь, следовательно воспользуемся этим шаблоном.</p>
<p>Реализовать данный шаблон можно несколькими различными вариантами:</p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Lazy_loading#Lazy_initialization">Lazy Initialization</a> – Инициализация по требованию. Это самый простой способ – реализовать проверку поля на null и в случае необходимости заполнять его данными. </li>
<li><a href="http://en.wikipedia.org/wiki/Lazy_loading#Virtual_proxy">Virtual Proxy</a> – Виртуальный прокси-объект. Метод несколько усложнен проблемой идентификации объектов, т.к. вместо них, до инициализации, выступают заменители. </li>
<li><a href="http://en.wikipedia.org/wiki/Lazy_loading#Ghost">Ghost</a> – Фиктивный объект, Призрак. Это реальный объект с неполным состоянием. </li>
<li><a href="http://en.wikipedia.org/wiki/Lazy_loading#Value_holder">Value Holder</a> – Диспетчер значения. Объект является оболочкой для некоторого значения. Так же не самый лучший вариант в связи с проблемами типизации. </li>
</ol>
<h2 style="width:445px;height:28px;">Примеры реализации.</h2>
<p>В рассмотренном ниже примере мы воспользуемся первым способом, как наиболее наглядным и простым в реализации.</p>
<p>Мы напишем обобщенный класс Lazy&#60;T&#62;, который будет представлять загрузку по требованию, а так же кэшировать результат вычислений для дальнейших обращений к ним.</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">using</span> System.Linq;
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> Lazy&#60;T&#62; {
<span style="color:#0000ff;">private</span> Func&#60;T&#62; func;
<span style="color:#0000ff;">private</span> T result;
<span style="color:#0000ff;">private</span> <span style="color:#0000ff;">bool</span> hasValue;
<span style="color:#0000ff;">public</span> Lazy(Func&#60;T&#62; func) {
<span style="color:#0000ff;">this</span>.func = func;
<span style="color:#0000ff;">this</span>.hasValue = <span style="color:#0000ff;">false</span>;
  }
<span style="color:#0000ff;">public</span> T Value {
<span style="color:#0000ff;">get</span> {
<span style="color:#0000ff;">if</span> (!<span style="color:#0000ff;">this</span>.hasValue) {
<span style="color:#0000ff;">this</span>.result = <span style="color:#0000ff;">this</span>.func();
<span style="color:#0000ff;">this</span>.hasValue = <span style="color:#0000ff;">true</span>;
      }
<span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>.result;
    }
  }
}</pre>
<p>Данный класс имеет три поля:</p>
<ul>
<li>func – делегат Func&#60;T&#62; инкапсулирующего передаваемый метод (находится в пространстве имён Linq, используется для инкапсуляции метода без параметров); </li>
<li>result – поле для хранения результата вычислений; </li>
<li>hasValue – флаг для обозначния, производились ли уже вычисления. </li>
</ul>
<p>Как же можно использовать данный класс</p>
<pre style="font-size:14px;">Lazy&#60;<span style="color:#0000ff;">int</span>&#62; lazy = <span style="color:#0000ff;">new</span> Lazy&#60;<span style="color:#0000ff;">int</span>&#62;(() =&#62; {
    Console.WriteLine(&#34;<span style="color:#8b0000;">calculating...</span>&#34;);
<span style="color:#0000ff;">return</span> 42;
  });
Console.WriteLine(&#34;<span style="color:#8b0000;">starting...</span>&#34;);
Console.WriteLine(&#34;<span style="color:#8b0000;">result = {0}</span>&#34;, lazy.Value);
Console.WriteLine(&#34;<span style="color:#8b0000;">result (again) = {0}</span>&#34;, lazy.Value);</pre>
<p>Результат работы программы:</p>
<p>starting&#8230;</p>
<p>calculating&#8230;</p>
<p>result = 42</p>
<p>result (again) = 42</p>
<p>Мы наглядно видим, как в поле func заносится лямба-выражение, результат которого выводится после вызова свойства Value. Причём повторный вызов свойства выводит кэшированные данные.</p>
<p>Далее, думаю стоит написать обертку-помощник для нашего класса, с целью повышения наглядности работы с ним.</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">class</span> Lazy {
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> Lazy&#60;T&#62; New&#60;T&#62;(Func&#60;T&#62; func) {
<span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> Lazy&#60;T&#62;(func);
  }
}</pre>
<p>Будет он выглядеть примерно так. Кстати, примерно также выглядит System.Nullable (один из стандартных классов .NET).</p>
<p>Используя класс Lazy мы можем создать экземпляр нашего типа, вызвав метод Lazy.New вместо написания new Lazy&#60;int&#62; к примеру. Для ещё пущего повышения наглядности будем использовать атрибут var.</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">int</span> a = 22, b = 20;
var lazy = Lazy.New(() =&#62; {
    Console.WriteLine(&#34;<span style="color:#8b0000;">calculating...</span>&#34;);
<span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> { Mul = a*b, Sum = a+b };
  });
Console.WriteLine(&#34;<span style="color:#8b0000;">Mul = {0}, Sum = {1}</span>&#34;,
  lazy.Value.Mul, lazy.Value.Sum);</pre>
<p>Все наши приобритения продемонстрированы Выше в примере, расчитывающий сумму и произведения двух чисел.</p>
<p>Далее хотелось бы рассмотреть пример со значениями аргументов в качестве значений, инициализируемых по требованию, что несомненно очень удобно при использовании такого языка, как C#, в котором инициализация аргументов происходит немедленно.</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">static</span> Random rnd = <span style="color:#0000ff;">new</span> Random();
<span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> UseRandomArgument(Lazy&#60;<span style="color:#0000ff;">int</span>&#62; a0, Lazy&#60;<span style="color:#0000ff;">int</span>&#62; a1) {
<span style="color:#0000ff;">int</span> res;
<span style="color:#0000ff;">if</span> (rnd.Next(2) == 0)
    res = a0.Value;
<span style="color:#0000ff;">else</span>
    res = a1.Value;
  Console.WriteLine(&#34;<span style="color:#8b0000;">result = {0}</span>&#34;, res);
}</pre>
<p>Как хорошо видно в данном примере, один из аргументов метода может не использоваться вовсе.</p>
<pre style="font-size:14px;">var calc1 = Lazy.New(() =&#62; {
    Console.WriteLine(&#34;<span style="color:#8b0000;">Calculating #1</span>&#34;);
<span style="color:#0000ff;">return</span> 42;
  });
var calc2 = Lazy.New(() =&#62; {
    Console.WriteLine(&#34;<span style="color:#8b0000;">Calculating #2</span>&#34;);
<span style="color:#0000ff;">return</span> 44;
  });
UseRandomArgument(calc1, calc2);
UseRandomArgument(calc1, calc2);</pre>
<p>Напишем обработчик для данного метода и посмотрим, какие из аргументов будут проинициализированы:</p>
<pre style="font-size:14px;">Calculating #1
Result = 42
Result = 42</pre>
<p>Повторим запуск приложения:</p>
<pre style="font-size:14px;">Calculating #1
Result = 42
Calculating #2
Result = 44</pre>
<p><strong></strong></p>
<h2 style="width:473px;height:29px;">Пример: Список шрифтов с предосмотром.</h2>
<p>&#160;</p>
<p>На картинке ниже представлен эскиз нашего будущего приложения. Он содержит выпадающий список с наименованиями шрифтов, а так же область, в которой будет выводится изображение для выбранного шрифта. Как не трудно догадаться при заполнении списка не очень бы хотелось инициализировать все картинки в память компьютера, в связи с чем мы воспользуемся созданным нами классом Lazy&#60;T&#62;.</p>
<p><img alt="" src="http://i.msdn.microsoft.com/bb870976.Figure1(en-us).png" /></p>
<p>Наш класс для хранения информации о шрифтах будет следующим:</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">private</span> <span style="color:#0000ff;">class</span> FontInfo {
<span style="color:#0000ff;">public</span> Lazy&#60;Bitmap&#62; Preview { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> Name { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }
}</pre>
<p>Метод для генерации и отрисовки изображения шрифта:</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> DrawFontPreview(FontFamily f, Bitmap bmp) {
  Rectangle rc = <span style="color:#0000ff;">new</span> Rectangle(0, 0, 300, 200);
  StringFormat sf = <span style="color:#0000ff;">new</span> StringFormat();
  sf.Alignment = StringAlignment.Center;
  sf.LineAlignment = StringAlignment.Center;
<span style="color:#0000ff;">string</span> lipsum = &#34;<span style="color:#8b0000;">Lorem ipsum dolor sit amet, consectetuer </span>&#34; +
    &#34;<span style="color:#8b0000;">adipiscing elit. Etiam ut mi blandit turpis euismod malesuada. </span>&#34; +
    &#34;<span style="color:#8b0000;">Mauris congue pede vitae lectus. Ut faucibus dignissim diam. </span>&#34;;
<span style="color:#0000ff;">using</span> (Font fnt = <span style="color:#0000ff;">new</span> Font(f, 15, FontStyle.Regular))
<span style="color:#0000ff;">using</span> (Graphics gr = Graphics.FromImage(bmp)) {
    gr.FillRectangle(Brushes.White, rc);
    gr.DrawString(lipsum, fnt, Brushes.Black, rc, sf);
  }
}</pre>
<p>На загрузке формы нашего приложения связываем наши значения с методом выбора шрифта из списка.</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> FontForm_Load(<span style="color:#0000ff;">object</span> sender, EventArgs e) {
  var fontInfo = FontFamily.Families.Select(f =&#62; {
<span style="color:#008000;">// Создаем значение по требованию для картинки</span>
      var preview = Lazy.New(() =&#62; {
          Bitmap bmp = <span style="color:#0000ff;">new</span> Bitmap(300, 200);
          DrawFontPreview(f, bmp);
<span style="color:#0000ff;">return</span> bmp;
        });
<span style="color:#008000;">// Возвращаем шрифт с названием и превьюшкой</span>
      <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> FontInfo { Name = f.Name, Preview = preview };
    });
<span style="color:#008000;">// Используем дата-байдинг для заполнения списка</span>
  fontCombo.DataSource = fontInfo.ToList();
  fontCombo.DisplayMember = &#34;<span style="color:#8b0000;">Name</span>&#34;;
}</pre>
<p>При изменении выбранного шрифта перерисовываем изображение:</p>
<pre style="font-size:14px;"><span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> fontCombo_SelectedIndexChanged(<span style="color:#0000ff;">object</span> sender, EventArgs e) {
  FontInfo fnt = (FontInfo)fontCombo.SelectedItem;
  fontPreview.Image = fnt.Preview.Value;
}</pre>
<h2 style="width:450px;height:28px;">Заключение</h2>
<p>В данной статье Вы ознакомились с реализацией паттерна “загрузка по требованию” на языке C#, данный шаблон предоставляет великолепные возможности откладывать вычисления до того момента, пока они не будут действительно необходимы. Так же вспомнили те возможности C# версии 3.0, которые делают код нагляднее, а его написание проще (Неявное объявление типов, анонимные методы и лямбда-выражения, операторы запросов, и анонимные типы)</p>
<h2 style="width:485px;height:29px;">Материалы</h2>
<p>&#160; </p>
<ol>
<li><a href="http://msdn.microsoft.com/en-us/vcsharp/bb870976.aspx">http://msdn.microsoft.com/en-us/vcsharp/bb870976.aspx</a> (При написании данной статьи я руководствовался данной работой, все рассмотренные примеры, взяты там же) </li>
<li><a href="http://www.books.ru/shop/books/156126?partner=butaji">Мартин Фаулер “Архитектура корпоративных приложений”</a> (Идея данного паттерна изложена М. Фаулером в этой книге) </li>
</ol>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Advanced Bidirectional Silverlight 2.0 to ASP.NET Integration &ndash; Part 1]]></title>
<link>http://team.pushbomb.com/2008/12/23/silverlight_aspnet_bidirectional_integration-2/</link>
<pubDate>Tue, 23 Dec 2008 06:35:43 +0000</pubDate>
<dc:creator>Damon Wilder Carr</dc:creator>
<guid>http://team.pushbomb.com/2008/12/23/silverlight_aspnet_bidirectional_integration-2/</guid>
<description><![CDATA[This is the first post covering techniques for both sending data into your Silverlight environment f]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.domaindotnet.com%2f2008%2f12%2f23%2fsilverlight_aspnet_bidirectional_integration-2%2f"><img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.domaindotnet.com%2f2008%2f12%2f23%2fsilverlight_aspnet_bidirectional_integration-2%2f" /></a></p>
<p><a href="http://digg.com/submit?url=http%3a%2f%2fdcarr.wordpress.com%2f2008%2f12%2f23%2fsilverlight_aspnet_bidirectional_integration-2%2f&#38;title=Advanced+Bidirectional+Silverlight+2.0+to+ASP.NET+Integration+%e2%80%93+Part+1"><img style="border-width:0;" title="Digg This" border="0" alt="Digg This" src="http://digg.com/img/badges/100x20-digg-button.png" width="100" height="20" /></a></p>
<p><a href="http://dcarr.files.wordpress.com/2008/12/silverlight-logo-2.png"><img style="display:inline;border-width:0;" title="Silverlight_Logo_2" border="0" alt="Silverlight_Logo_2" src="http://dcarr.files.wordpress.com/2008/12/silverlight-logo-2-thumb.png?w=244&#038;h=82" width="244" height="82" /></a></p>
<p>This is the first post covering techniques for both sending data into your Silverlight environment from ASP.NET as well as getting data out of Silverlight without resorting to a lot of new elements in your architecture. The goal is to use what you already have with the least fuss.</p>
<p>You may think you need to resort to ‘pushing’ all data from Silverlight into say a service using WCF but that is not the case in many scenarios.</p>
<p>For example, you may have activity which the user creates inside Silverlight 2.0 that results in visual elements you want to send out to ASP.NET for persistence in your ORM environment (where Silverlight has no involvement).</p>
<h2 style="width:380px;height:32px;">From ASP.NET to Silverlight 2.0</h2>
<p>First, let’s quickly review the easiest way to pass information into your Silverlight control.</p>
<h3>InitParamaters</h3>
<p>Here is the on-line help:</p>
<blockquote><p>If parameters are included, they are typically in comma-delimited pairs and are available as a dictionary object in a Silverlight 2 startup event. <strong>These parameters are not used in a Silverlight 1.0-based application.</strong></p>
<p>If an action on an .aspx page causes a postback to occur, the Silverlight plug-in will start again with its content specified in the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.silverlightcontrols.silverlight.source(VS.95).aspx">Source</a> property. The current value of the InitParameters property is sent to the Silverlight plug-in. <strong>This enables you to change the InitParameters property before a postback occurs.</strong></p>
<p>The Silverlight 2 application specified in the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.silverlightcontrols.silverlight.source(VS.95).aspx">Source</a> property can access the initialization parameters specified in the InitParameters property in the <a href="http://msdn.microsoft.com/en-us/library/system.windows.startupeventargs(VS.95).aspx">StartupEventArgs</a> parameter of the Silverlight Application <a href="http://msdn.microsoft.com/en-us/library/system.windows.application.startup(VS.95).aspx">Startup</a> event.</p>
</blockquote>
<p>We will walk through an entire example of this, including some content that will make sense in how we can move data back out of Silverlight 2.0 to ASP.NET.</p>
<h3>Code for this Scenario</h3>
<p>We will be using a web UserControl (.ascx) as our control in this example, because as you will see, we need more than just the Silverlight control to make this work.</p>
<h4>ASCX Host</h4>
<div>
<pre class="code"><span style="background:#151515;color:#f35c47;">&#60;%</span><span style="background:#151515;color:#f2f200;">@ </span><span style="background:#151515;color:#f4503e;">Control </span><span style="background:#151515;color:#f0ec4a;">Language</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;C#&#34; </span><span style="background:#151515;color:#f0ec4a;">AutoEventWireup</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;true&#34; </span><span style="background:#151515;color:#f0ec4a;">CodeBehind</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;SilverlightInt.ascx.cs&#34;
  </span><span style="background:#151515;color:#f0ec4a;">Inherits</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;SilverlightInt&#34; </span><span style="background:#151515;color:#f35c47;">%&#62;
&#60;%</span><span style="background:#151515;color:#f2f200;">@ </span><span style="background:#151515;color:#f4503e;">Register </span><span style="background:#151515;color:#f0ec4a;">Assembly</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;System.Web.Silverlight&#34;</span></pre>
<pre class="code"><span style="background:#151515;color:#a8a8ff;"> </span><span style="background:#151515;color:#f0ec4a;">Namespace</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;System.Web.UI.SilverlightControls&#34;
    </span><span style="background:#151515;color:#f0ec4a;">TagPrefix</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;asp&#34; </span><span style="background:#151515;color:#f35c47;">%&#62;
</span><span style="background:#151515;color:#f2f200;">&#60;</span><span style="background:#151515;color:#f4503e;">asp</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">Silverlight </span><span style="background:#151515;color:#f0ec4a;">ID</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;SilverlightView&#34; </span><span style="background:#151515;color:#f0ec4a;">runat</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;server&#34; </span></pre>
<pre class="code"><span style="background:#151515;color:#a8a8ff;"></span><span style="background:#151515;color:#f0ec4a;">Source</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;~/ClientBin/AspNetIntegration.xap&#34;
    </span><span style="background:#151515;color:#f0ec4a;">MinimumVersion</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;2.0.31005.0&#34; </span><span style="background:#151515;color:#f2f200;">/&#62;
&#60;</span><span style="background:#151515;color:#f4503e;">asp</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">TextBox </span><span style="background:#151515;color:#f0ec4a;">ID</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;SilverOutput&#34; </span><span style="background:#151515;color:#f0ec4a;">runat</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;server&#34;  </span></pre>
<pre class="code"><span style="background:#151515;color:#a8a8ff;"> </span><span style="background:#151515;color:#f0ec4a;">Style</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;</span><span style="background:#151515;color:#f4503e;">display</span><span style="background:#151515;color:white;">: </span><span style="background:#151515;color:#9cf5c0;">none</span><span style="background:#151515;color:#a8a8ff;">&#34;</span><span style="background:#151515;color:#f2f200;">&#62;&#60;/</span><span style="background:#151515;color:#f4503e;">asp</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">TextBox</span><span style="background:#151515;color:#f2f200;">&#62;</span><a href="http://11011.net/software/vspaste"></a></pre>
</div>
<h4>ASCX Code Behind</h4>
<pre class="code"><span style="background:#151515;color:white;">    </span><span style="background:#151515;color:#ecc03e;">public partial class </span><span style="background:#151515;color:#2b91af;">SilverlightInt </span><span style="background:#151515;color:white;">: </span><span style="background:#151515;color:#2b91af;">UserControl
    </span><span style="background:#151515;color:white;">{
        [</span><span style="background:#151515;color:#2b91af;">Browsable</span><span style="background:#151515;color:white;">(</span><span style="background:#151515;color:#ecc03e;">true</span><span style="background:#151515;color:white;">)]
        </span><span style="background:#151515;color:#ecc03e;">public </span><span style="background:#151515;color:#2b91af;">String </span><span style="background:#151515;color:white;">InitialText { </span><span style="background:#151515;color:#ecc03e;">get</span><span style="background:#151515;color:white;">; </span><span style="background:#151515;color:#ecc03e;">set</span><span style="background:#151515;color:white;">; }

        </span><span style="background:#151515;color:#ecc03e;">protected void </span><span style="background:#151515;color:white;">Page_Load(</span><span style="background:#151515;color:#ecc03e;">object </span><span style="background:#151515;color:white;">sender, </span><span style="background:#151515;color:#2b91af;">EventArgs </span><span style="background:#151515;color:white;">e)
        {
            SetSilverlightInitParamaters();
        }

        </span><span style="background:#151515;color:#ecc03e;">void </span><span style="background:#151515;color:white;">SetSilverlightInitParamaters()
        {
            </span><span style="background:#151515;color:#e388dd;">// Note: We need the client ID for later...
            </span><span style="background:#151515;color:#ecc03e;">var </span><span style="background:#151515;color:white;">InitParams = </span><span style="background:#151515;color:#ecc03e;">new </span><span style="background:#151515;color:#2b91af;">Dictionary</span><span style="background:#151515;color:white;">&#60;</span><span style="background:#151515;color:#2b91af;">String</span><span style="background:#151515;color:white;">, </span><span style="background:#151515;color:#2b91af;">String</span><span style="background:#151515;color:white;">&#62;
                             {
                                 {
                                     </span><span style="background:#151515;color:#ecc03e;">&#34;outputcontrol&#34;</span><span style="background:#151515;color:white;">,
                                    SilverOutput.ClientID
                                     },
                                 {
                                     </span><span style="background:#151515;color:#ecc03e;">&#34;InitialText&#34;</span><span style="background:#151515;color:white;">,
                               InitialText ?? </span><span style="background:#151515;color:#ecc03e;">&#34;Hello World&#34;
                                     </span><span style="background:#151515;color:white;">}
                             };

            SilverlightView.InitParameters =          </span></pre>
<pre class="code"><span style="background:#151515;color:white;">         InitParams.ToSilverlightInit();
        }
    }
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You might notice the extension method ToSilverlightInit(). Here is the code:</p>
<pre class="code"><span style="background:#151515;color:white;"> </span><span style="background:#151515;color:#ecc03e;">public static class </span><span style="background:#151515;color:#2b91af;">SilverlightIntegrationExtensions
    </span><span style="background:#151515;color:white;">{
        </span><span style="background:#151515;color:gray;">/// &#60;summary&#62;
        /// </span><span style="background:#151515;color:green;">Parse the dictionary into Silverlight format
        </span><span style="background:#151515;color:gray;">/// </span><span style="background:#151515;color:green;">for InitParams
        </span><span style="background:#151515;color:gray;">/// &#60;/summary&#62;
        /// &#60;param name=&#34;target&#34;&#62;</span><span style="background:#151515;color:green;">The target.</span><span style="background:#151515;color:gray;">&#60;/param&#62;
        /// &#60;returns&#62;&#60;/returns&#62;
        </span><span style="background:#151515;color:#ecc03e;">public static </span><span style="background:#151515;color:#2b91af;">String </span><span style="background:#151515;color:white;">ToSilverlightInit(
             </span><span style="background:#151515;color:#ecc03e;">this </span><span style="background:#151515;color:#9185fa;">IDictionary</span><span style="background:#151515;color:white;">&#60;</span><span style="background:#151515;color:#2b91af;">String</span><span style="background:#151515;color:white;">, </span><span style="background:#151515;color:#2b91af;">String</span><span style="background:#151515;color:white;">&#62; target)
        {
            </span><span style="background:#151515;color:#ecc03e;">if </span><span style="background:#151515;color:white;">(target == </span><span style="background:#151515;color:#ecc03e;">null</span><span style="background:#151515;color:white;">)
                </span><span style="background:#151515;color:#ecc03e;">throw new </span><span style="background:#151515;color:#2b91af;">ArgumentNullException</span><span style="background:#151515;color:white;">(</span><span style="background:#151515;color:#ecc03e;">&#34;target&#34;</span><span style="background:#151515;color:white;">);

            </span><span style="background:#151515;color:#ecc03e;">var </span><span style="background:#151515;color:white;">stringBuffer = </span><span style="background:#151515;color:#ecc03e;">new </span><span style="background:#151515;color:#2b91af;">StringBuilder</span><span style="background:#151515;color:white;">();

            </span><span style="background:#151515;color:#ecc03e;">foreach</span><span style="background:#151515;color:white;">(</span><span style="background:#151515;color:#ecc03e;">var </span><span style="background:#151515;color:white;">kvp </span><span style="background:#151515;color:#ecc03e;">in </span><span style="background:#151515;color:white;">target)
            {
                </span><span style="background:#151515;color:#ecc03e;">if </span><span style="background:#151515;color:white;">(stringBuffer.Length &#62; 0)
                    stringBuffer.Append(</span><span style="background:#151515;color:#ecc03e;">&#34;,&#34;</span><span style="background:#151515;color:white;">);

                </span><span style="background:#151515;color:#e388dd;">// Eliminate case sensitivity
              </span><span style="background:#151515;color:white;">stringBuffer.Append(kvp.Key.ToLower()
                + </span><span style="background:#151515;color:#ecc03e;">&#34;=&#34; </span><span style="background:#151515;color:white;">+ kvp.Value);

            }

            </span><span style="background:#151515;color:#ecc03e;">return </span><span style="background:#151515;color:white;">stringBuffer.ToString();

        }

    }</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This is hosted in a normal ASPX page as follows (surrounding detail omitted):</p>
<pre class="code"><span style="background:#151515;color:white;">  </span><span style="background:#151515;color:#f2f200;">&#60;</span><span style="background:#151515;color:#f4503e;">form </span><span style="background:#151515;color:#f0ec4a;">id</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;form1&#34; </span><span style="background:#151515;color:#f0ec4a;">runat</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;server&#34; </span><span style="background:#151515;color:#f0ec4a;">style</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;</span><span style="background:#151515;color:#f4503e;">height</span><span style="background:#151515;color:white;">: </span><span style="background:#151515;color:#9cf5c0;">100%</span><span style="background:#151515;color:white;">;</span><span style="background:#151515;color:#a8a8ff;">&#34;</span><span style="background:#151515;color:#f2f200;">&#62;
    &#60;</span><span style="background:#151515;color:#f4503e;">asp</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">ScriptManager </span><span style="background:#151515;color:#f0ec4a;">ID</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;ScriptManager1&#34; </span><span style="background:#151515;color:#f0ec4a;">runat</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;server&#34;</span><span style="background:#151515;color:#f2f200;">&#62;
    &#60;/</span><span style="background:#151515;color:#f4503e;">asp</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">ScriptManager</span><span style="background:#151515;color:#f2f200;">&#62;
    &#60;</span><span style="background:#151515;color:#f4503e;">div</span><span style="background:#151515;color:#f2f200;">&#62;
        &#60;</span><span style="background:#151515;color:#f4503e;">asp</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">Image </span><span style="background:#151515;color:#f0ec4a;">Width</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;300px&#34; </span><span style="background:#151515;color:#f0ec4a;">ImageUrl</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;Silverlight_Logo_2.png&#34;
           </span><span style="background:#151515;color:#f0ec4a;">runat</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;server&#34; </span><span style="background:#151515;color:#f2f200;">/&#62;
        &#60;</span><span style="background:#151515;color:#f4503e;">br </span><span style="background:#151515;color:#f2f200;">/&#62;
        &#60;</span><span style="background:#151515;color:#f4503e;">asp</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">Literal </span><span style="background:#151515;color:#f0ec4a;">ID</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;sentText&#34; </span><span style="background:#151515;color:#f0ec4a;">runat</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;server&#34; </span><span style="background:#151515;color:#f2f200;">/&#62;&#60;</span><span style="background:#151515;color:#f4503e;">br </span><span style="background:#151515;color:#f2f200;">/&#62;
        &#60;</span><span style="background:#151515;color:#f4503e;">hr </span><span style="background:#151515;color:#f2f200;">/&#62;
        &#60;</span><span style="background:#151515;color:#f4503e;">integrate</span><span style="background:#151515;color:#ecc03e;">:</span><span style="background:#151515;color:#f4503e;">SilverlightInt </span><span style="background:#151515;color:#f0ec4a;">ID</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;SilverlightInt1&#34;
           </span><span style="background:#151515;color:#f0ec4a;">runat</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;server&#34;     </span><span style="background:#151515;color:#f0ec4a;">InitialText</span><span style="background:#151515;color:#ecc03e;">=</span><span style="background:#151515;color:#a8a8ff;">&#34;This is a Test&#34; </span><span style="background:#151515;color:#f2f200;">/&#62;
    &#60;/</span><span style="background:#151515;color:#f4503e;">div</span><span style="background:#151515;color:#f2f200;">&#62;
    &#60;/</span><span style="background:#151515;color:#f4503e;">form</span><span style="background:#151515;color:#f2f200;">&#62;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>Here is what it looks like:</p>
<p><a href="http://dcarr.files.wordpress.com/2008/12/image1.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://dcarr.files.wordpress.com/2008/12/image-thumb1.png?w=282&#038;h=384" width="282" height="384" /></a></p>
<h3>Silverlight Code for Initialization</h3>
<pre class="code"><span style="background:#151515;color:white;"> </span><span style="background:#151515;color:#ecc03e;">public partial class </span><span style="background:#151515;color:#2b91af;">App </span><span style="background:#151515;color:white;">: </span><span style="background:#151515;color:#2b91af;">Application
    </span><span style="background:#151515;color:white;">{
        </span><span style="background:#151515;color:#ecc03e;">public </span><span style="background:#151515;color:white;">App()
        {
            Startup += Application_Startup;
            UnhandledException += Application_UnhandledException;
            InitializeComponent();
        }

        </span><span style="background:#151515;color:#ecc03e;">void </span><span style="background:#151515;color:white;">Application_Startup(</span><span style="background:#151515;color:#ecc03e;">object </span><span style="background:#151515;color:white;">sender, </span><span style="background:#151515;color:#2b91af;">StartupEventArgs </span><span style="background:#151515;color:white;">e)
        {
            </span><span style="background:#151515;color:#ecc03e;">var </span><span style="background:#151515;color:white;">PassedInArguments = e.InitParams;
            RootVisual = </span><span style="background:#151515;color:#ecc03e;">new </span><span style="background:#151515;color:#2b91af;">SilverlightView</span><span style="background:#151515;color:white;">(PassedInArguments);
        }
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The interesting parts are that we are accessing the InitParams off the Startup’s ‘e’ object. This is a Dictionary&#60;String,String&#62; which is what prompted the ASP.NET design.</p>
<p>Also, we do not use a paramaterless constructor on the initial RootVisual. Instead this is the code:</p>
<h4>Silverlight View</h4>
<pre class="code"><span style="background:#151515;color:#f4503e;">&#60;</span><span style="background:#151515;color:#ecc03e;">UserControl </span><span style="background:#151515;color:#f4503e;">x:Class=</span><span style="background:#151515;color:#a8a8ff;">&#34;AspNetIntegration.SilverlightView&#34;
    </span><span style="background:#151515;color:#f4503e;">xmlns=</span><span style="background:#151515;color:#a8a8ff;">&#34;http://schemas.microsoft.com/winfx/2006/xaml/presentation&#34;
    </span><span style="background:#151515;color:#f4503e;">xmlns:x=</span><span style="background:#151515;color:#a8a8ff;">&#34;http://schemas.microsoft.com/winfx/2006/xaml&#34;</span><span style="background:#151515;color:#f4503e;">&#62;

    &#60;</span><span style="background:#151515;color:#ecc03e;">Grid </span><span style="background:#151515;color:#f4503e;">HorizontalAlignment=</span><span style="background:#151515;color:#a8a8ff;">&#34;Left&#34; </span><span style="background:#151515;color:#f4503e;">VerticalAlignment=</span><span style="background:#151515;color:#a8a8ff;">&#34;Top&#34;
       </span><span style="background:#151515;color:#f4503e;">x:Name=</span><span style="background:#151515;color:#a8a8ff;">&#34;LayoutRoot&#34; </span><span style="background:#151515;color:#f4503e;">Background=</span><span style="background:#151515;color:#a8a8ff;">&#34;Gray&#34;</span><span style="background:#151515;color:#f4503e;">&#62;
        &#60;</span><span style="background:#151515;color:#ecc03e;">Grid.RowDefinitions</span><span style="background:#151515;color:#f4503e;">&#62;
            &#60;</span><span style="background:#151515;color:#ecc03e;">RowDefinition </span><span style="background:#151515;color:#f4503e;">Height=</span><span style="background:#151515;color:#a8a8ff;">&#34;30&#34; </span><span style="background:#151515;color:#f4503e;">/&#62;
            &#60;</span><span style="background:#151515;color:#ecc03e;">RowDefinition </span><span style="background:#151515;color:#f4503e;">Height=</span><span style="background:#151515;color:#a8a8ff;">&#34;30&#34; </span><span style="background:#151515;color:#f4503e;">/&#62;
        &#60;/</span><span style="background:#151515;color:#ecc03e;">Grid.RowDefinitions</span><span style="background:#151515;color:#f4503e;">&#62;
        &#60;</span><span style="background:#151515;color:#ecc03e;">Grid.ColumnDefinitions</span><span style="background:#151515;color:#f4503e;">&#62;
            &#60;</span><span style="background:#151515;color:#ecc03e;">ColumnDefinition </span><span style="background:#151515;color:#f4503e;">Width=</span><span style="background:#151515;color:#a8a8ff;">&#34;150&#34; </span><span style="background:#151515;color:#f4503e;">/&#62;
        &#60;/</span><span style="background:#151515;color:#ecc03e;">Grid.ColumnDefinitions</span><span style="background:#151515;color:#f4503e;">&#62;

        &#60;</span><span style="background:#151515;color:#ecc03e;">TextBlock </span><span style="background:#151515;color:#f4503e;">HorizontalAlignment=</span><span style="background:#151515;color:#a8a8ff;">&#34;Center&#34;       </span></pre>
<pre class="code"><span style="background:#151515;color:#a8a8ff;">     </span><span style="background:#151515;color:#f4503e;">VerticalAlignment=</span><span style="background:#151515;color:#a8a8ff;">&#34;Center&#34;
             </span><span style="background:#151515;color:#f4503e;">Grid.Row=</span><span style="background:#151515;color:#a8a8ff;">&#34;0&#34; </span><span style="background:#151515;color:#f4503e;">Text=</span><span style="background:#151515;color:#a8a8ff;">&#34;Inside Silverlight&#34; </span><span style="background:#151515;color:#f4503e;">/&#62;
        &#60;</span><span style="background:#151515;color:#ecc03e;">TextBox </span><span style="background:#151515;color:#f4503e;">LostFocus=</span><span style="background:#151515;color:#a8a8ff;">&#34;SendResultBackToAspNet&#34; </span><span style="background:#151515;color:#f4503e;">Grid.Row=</span><span style="background:#151515;color:#a8a8ff;">&#34;1&#34;
          </span><span style="background:#151515;color:#f4503e;">BorderThickness=</span><span style="background:#151515;color:#a8a8ff;">&#34;2&#34; </span><span style="background:#151515;color:#f4503e;">BorderBrush=</span><span style="background:#151515;color:#a8a8ff;">&#34;Black&#34;               </span></pre>
<pre class="code"><span style="background:#151515;color:#a8a8ff;">  </span><span style="background:#151515;color:#f4503e;">x:Name=</span><span style="background:#151515;color:#a8a8ff;">&#34;initialText&#34;  </span><span style="background:#151515;color:#f4503e;">/&#62;

    &#60;/</span><span style="background:#151515;color:#ecc03e;">Grid</span><span style="background:#151515;color:#f4503e;">&#62;

&#60;/</span><span style="background:#151515;color:#ecc03e;">UserControl</span><span style="background:#151515;color:#f4503e;">&#62;
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h4>Code Behind</h4>
<pre class="code"><span style="background:#151515;color:#ecc03e;">public partial class </span><span style="background:#151515;color:#2b91af;">SilverlightView </span><span style="background:#151515;color:white;">: </span><span style="background:#151515;color:#2b91af;">UserControl
    </span><span style="background:#151515;color:white;">{
        </span><span style="background:#151515;color:#ecc03e;">readonly </span><span style="background:#151515;color:#9185fa;">IDictionary</span><span style="background:#151515;color:white;">&#60;</span><span style="background:#151515;color:#ecc03e;">string</span><span style="background:#151515;color:white;">, </span><span style="background:#151515;color:#ecc03e;">string</span><span style="background:#151515;color:white;">&#62; _initParamaters;
        </span><span style="background:#151515;color:#ecc03e;">string </span><span style="background:#151515;color:white;">_initialText =               </span></pre>
<pre class="code"><span style="background:#151515;color:white;"> </span><span style="background:#151515;color:#ecc03e;">&#34;Nothing was Passed In - initialtext was empty&#34;</span><span style="background:#151515;color:white;">;

        </span><span style="background:#151515;color:#ecc03e;">public </span><span style="background:#151515;color:white;">SilverlightView(            </span></pre>
<pre class="code"><span style="background:#151515;color:white;">  I</span><span style="background:#151515;color:#9185fa;">Dictionary</span><span style="background:#151515;color:white;">&#60;</span><span style="background:#151515;color:#ecc03e;">string</span><span style="background:#151515;color:white;">, </span><span style="background:#151515;color:#ecc03e;">string</span><span style="background:#151515;color:white;">&#62; passedInArguments)
        {
            _initParamaters = passedInArguments;
            InitializeComponent();
            Loaded += OnLoaded;
        }

        </span><span style="background:#151515;color:#ecc03e;">void </span><span style="background:#151515;color:white;">OnLoaded(</span><span style="background:#151515;color:#ecc03e;">object </span><span style="background:#151515;color:white;">sender, </span><span style="background:#151515;color:#2b91af;">RoutedEventArgs </span><span style="background:#151515;color:white;">e)
        {
            SetInitialText();
        }

        </span><span style="background:#151515;color:#ecc03e;">void </span><span style="background:#151515;color:white;">SetInitialText() {

            </span><span style="background:#151515;color:#ecc03e;">if </span><span style="background:#151515;color:white;">(_initParamaters.ContainsKey(</span><span style="background:#151515;color:#ecc03e;">&#34;initialtext&#34;</span><span style="background:#151515;color:white;">))
            {
                _initialText = _initParamaters[</span><span style="background:#151515;color:#ecc03e;">&#34;initialtext&#34;</span><span style="background:#151515;color:white;">];
            }

            initialText.Text = _initialText;
        }

        </span><span style="background:#151515;color:#ecc03e;">void </span><span style="background:#151515;color:white;">SendResultBackToAspNet(</span><span style="background:#151515;color:#ecc03e;">object </span><span style="background:#151515;color:white;">sender, </span><span style="background:#151515;color:#2b91af;">RoutedEventArgs </span><span style="background:#151515;color:white;">e)
        {

        }
    }</span></pre>
<p>Notice the ‘SendResultBackToAspNet’ is empty.. That is coming next and is the tricky part.</p>
<h3>Coming Next</h3>
<p>The code will all be available for download and the much more interesting aspect of sending data back the other way will be presented.</p>
<p>Damon</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:deef5f6c-9e8f-45ec-beea-78b28996210d" class="wlWriterSmartContent">del.icio.us Tags: <a href="http://del.icio.us/popular/Silverlight" rel="tag">Silverlight</a>,<a href="http://del.icio.us/popular/ASP.NET" rel="tag">ASP.NET</a>,<a href="http://del.icio.us/popular/Bidirectional" rel="tag">Bidirectional</a>,<a href="http://del.icio.us/popular/Integration" rel="tag">Integration</a>,<a href="http://del.icio.us/popular/InitParameters" rel="tag">InitParameters</a>,<a href="http://del.icio.us/popular/InitParams" rel="tag">InitParams</a>,<a href="http://del.icio.us/popular/HtmlBridge" rel="tag">HtmlBridge</a></div>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:eeae14fb-c4b4-4ef0-a063-4007fc457a38" class="wlWriterSmartContent">Technorati Tags: <a href="http://technorati.com/tags/Silverlight" rel="tag">Silverlight</a>,<a href="http://technorati.com/tags/ASP.NET" rel="tag">ASP.NET</a>,<a href="http://technorati.com/tags/Bidirectional" rel="tag">Bidirectional</a>,<a href="http://technorati.com/tags/Integration" rel="tag">Integration</a>,<a href="http://technorati.com/tags/InitParameters" rel="tag">InitParameters</a>,<a href="http://technorati.com/tags/InitParams" rel="tag">InitParams</a>,<a href="http://technorati.com/tags/HtmlBridge" rel="tag">HtmlBridge</a></div>
</div>]]></content:encoded>
</item>

</channel>
</rss>
