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

<channel>
	<title>Elegant Code &#187; C# 3.0</title>
	<atom:link href="http://elegantcode.com/tag/c-30/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Sun, 12 Feb 2012 04:40:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Dynamic LINQ</title>
		<link>http://elegantcode.com/2008/04/15/dynamic-linq/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dynamic-linq</link>
		<comments>http://elegantcode.com/2008/04/15/dynamic-linq/#comments</comments>
		<pubDate>Wed, 16 Apr 2008 01:23:13 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[.Net 3.5]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/15/dynamic-linq/</guid>
		<description><![CDATA[Something I just saw for the first time is a Microsoft C# sample application called DynamicQuery.&#160; This allows you to enter part of a LINQ query as a string. If you have Visual Studio 2008 installed, you can find the samples in this directory: C:\Program Files\Microsoft Visual Studio 9.0\Samples\1033.&#160; Then extract the file CSharpSamples.zip.&#160; The [...]]]></description>
			<content:encoded><![CDATA[<p>Something I just saw for the first time is a Microsoft C# sample application called DynamicQuery.&nbsp; This allows you to enter part of a LINQ query as a string.</p>
<p>If you have Visual Studio 2008 installed, you can find the samples in this directory: C:\Program Files\Microsoft Visual Studio 9.0\Samples\1033.&nbsp; Then extract the file CSharpSamples.zip.&nbsp; The sample will be found at CSharpSamples\LinqSamples\DynamicQuery.</p>
<p>From the sample you will see that you can do perform things like this:</p>
<pre class="csharpcode">var query =&nbsp;&nbsp;&nbsp; db.Customers.Where(&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="str">"City == @0 and Orders.Count &gt;= @1"</span>, <span class="str">"London"</span>, 10).
   OrderBy(<span class="str">"CompanyName"</span>).
   Select(<span class="str">"New(CompanyName as Name, Phone)"</span>);
</pre>
<p><style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>All of the heavy lifting happens in the Dynamic.cs file that has 11 classes.&nbsp; The interface happens through DynamicQuery static class, which extends the IQueriable interface with new Where, OrderBy, and Select methods.&nbsp; To use these extensions you have to include this line in your code: <strong>using System.Linq.Dynamic;</strong> along with the Dynamic file in your project.</p>
<p>I don&#8217;t have a use for this quite yet, but I think its time will come.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/15/dynamic-linq/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Partial Mocks explained</title>
		<link>http://elegantcode.com/2008/04/08/partial-mocks-explained/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=partial-mocks-explained</link>
		<comments>http://elegantcode.com/2008/04/08/partial-mocks-explained/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:14:42 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/08/partial-mocks-explained/</guid>
		<description><![CDATA[If you are wondering what is prompting this post, it is the fact that on my last post I got schooled by Jeff Brown of Bits-in-Motion.&#160;&#160; Jeff is also one of the minds behind Gallio and MBUnit.&#160; You can only hope to be told you are completely wrong by such a guy. He was very [...]]]></description>
			<content:encoded><![CDATA[<p>If you are wondering what is prompting this post, it is the fact that on my <a href="http://elegantcode.com/2008/04/07/mocking-nested-methods/">last post</a> I got schooled by Jeff Brown of <a href="http://blog.bits-in-motion.com/">Bits-in-Motion</a>.&nbsp;&nbsp; Jeff is also one of the minds behind <a href="http://www.gallio.org">Gallio</a> and <a href="http://www.mbunit.com/">MBUnit</a>.&nbsp; You can only hope to be told you are completely wrong by such a guy. He was very nice about it actually, just stating a preference for a different way of handling the same problem.&nbsp; My problem was that his solution was better than mine.&nbsp; Much better.</p>
<p>Where it led me was to re-investigate <a href="http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx">Partial Mocks in Rhino Mocks</a>.&nbsp; My original misunderstanding of Partial Mocks was that they would only mock Abstract Classes.&nbsp; A partial mock will mock ANY class &#8212; but only the Partial mock will only mock abstract methods.&nbsp; That small misunderstanding has caused me to loose untold amount of hair and good will towards all men.</p>
<p>So I&#8217;m going to re-implement my class methods.&nbsp; Here you go:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyClass
{
    <span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
    {
        <span class="rem">// stuff happens here</span>
        <span class="kwrd">int</span> i = Bar();
        <span class="rem">// do more stuff here    </span>
        <span class="kwrd">return</span> i + 5;
    }
    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">int</span> Bar()
    {
       <span class="rem">// do some logic</span>
       <span class="kwrd">return</span> 1;
    }
}</pre>
<p><style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>A few changes here.&nbsp; First, I removed the delegate and renamed BarInternal back to <strong>Bar</strong>.&nbsp; Second, I marked the <strong>Bar</strong> method as <a href="http://msdn2.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx">virtual</a>.&nbsp; </p>
<p>They key point about a virtual method is that you can provide an implementation, and then a inherited class can completely override that method.&nbsp; That is what the Partial Mock is allowing us to do.</p>
<p>So how do I write my tests?&nbsp; If you don&#8217;t like using Rhino Mocks you do this:</p>
<pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    <span class="kwrd">int</span> expected = 7;
    <span class="kwrd">int</span> result = 0;
    MockRepository mock = <span class="kwrd">new</span> MockRepository();
    MyClass c = mock.PartialMock&lt;MyClass&gt;();

    <span class="kwrd">using</span> (mock.Record())
    {
        Expect.Call(c.Bar()).Return(2);
    }
    <span class="kwrd">using</span> (mock.Playback())
    {
        result = c.Foo();
    }

    Assert.AreEqual(expected, result);
}</pre>
<p><style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>Obviously, now my test is referencing the Rhino Mocks library.&nbsp; The variable mock is the Mock Repository.&nbsp; Now the big change is that I don&#8217;t create MyClass directly, but through the Rhino Mocks PartialMock method.</p>
<p>Next, I tell the mock repository to expect a call to <strong>c.Bar</strong>, and when called return <strong>2</strong>.&nbsp; That is what is happening in the using (<strong>mock.Record()</strong>) section of the code.&nbsp; Then, in the <strong>mock.Playback</strong> section, I call <strong>Foo().</strong></p>
<p>One other quick note, if we were to rewrite <strong>Foo</strong> such that it no longer called <strong>Bar</strong> this test will fail.&nbsp; The <strong>Expect.Call</strong> part tell the mock repository that the method <strong>Bar</strong> will be called, and if it isn&#8217;t there is a problem.&nbsp; There are ways around that as well, but that is a topic for another day.</p>
<p>Where does that leave us now?&nbsp; Aside from the odd &#8220;<strong>virtual</strong>&#8221; keyword thrown into our production code, this is the code as you would have originally written it, even without TDD.&nbsp; I don&#8217;t like making API changes just to satisfy testing, but I am very OK with this change.</p>
<p>&nbsp;</p>
<p>But what about that new kid on the block?&nbsp; You know, <a href="http://code.google.com/p/moq/">Moq</a>.</p>
<p>I still love Rhino Mocks, but I can&#8217;t help but want to play with a new toy.&nbsp; So here is the same thing, but in Moq:</p>
<pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_moq_test()
{
    Mock&lt;MyClass&gt; mock = <span class="kwrd">new</span> Mock&lt;MyClass&gt;();
    mock.Expect(x =&gt; x.Bar()).Returns(2);

    MyClass c = mock.Object;
    <span class="kwrd">int</span> result = c.Foo();
    Assert.AreEqual(7, result);
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>So as you should be able to see, Moq is a very different animal than RhinoMocks.&nbsp; There is no Record or Playback (the web site calls those confusing, I disagree, but still), and the <strong>Expect</strong> happens with a anonymous delegate (in the form of the Lambda Expression &#8220;<strong>x =&gt; x.Bar()</strong>&#8221; where x is of type <strong>MyClass</strong>).</p>
<p>The cool part is that you can get the same results with less code using Moq.&nbsp; That has been the main advantage all along.&nbsp; My informal testing also reveals that Moq is just a hair faster than Rhino Mocks (but not fast enough to warrant switching frameworks).</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/08/partial-mocks-explained/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How have the new features of C# changed your code?</title>
		<link>http://elegantcode.com/2008/03/31/how-have-the-new-features-of-c-changed-your-code/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-have-the-new-features-of-c-changed-your-code</link>
		<comments>http://elegantcode.com/2008/03/31/how-have-the-new-features-of-c-changed-your-code/#comments</comments>
		<pubDate>Mon, 31 Mar 2008 08:04:02 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/03/31/how-have-the-new-features-of-c-changed-your-code/</guid>
		<description><![CDATA[Here is a simplified example of how the functional programming style of Linq has impacted the way I would do a DDD service implementation. Before: IEnumerable&#60;TDomainEntity&#62; domainEntities = Repository.Find(criteria); IEnumerable&#60;TDto&#62; dtos = Assembler.DomainToService(domainEntities); return new List&#60;TDto&#62;(dtos); After: return Repository .Find(criteria) .ToList() .ConvertAll&#60;TDto&#62;(Assembler.DomainToService); Thoughts? Samples? WTF’s?]]></description>
			<content:encoded><![CDATA[<p>Here is a simplified example of how the functional programming style of Linq has impacted the way I would do a DDD service implementation. </p>
<p><span id="more-978"></span></p>
<p>Before:
<div>
<pre class="csharpcode">IEnumerable&lt;TDomainEntity&gt; domainEntities = Repository.Find(criteria);
IEnumerable&lt;TDto&gt; dtos = Assembler.DomainToService(domainEntities);
<span class="kwrd">return</span> <span class="kwrd">new</span> List&lt;TDto&gt;(dtos);
</pre>
</div>
<div>After:</div>
<div>
<pre class="csharpcode"><span class="kwrd">return</span> Repository
           .Find(criteria)
           .ToList()
           .ConvertAll&lt;TDto&gt;(Assembler.DomainToService);
</pre>
</div>
<div>Thoughts? Samples? WTF’s?</div>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/03/31/how-have-the-new-features-of-c-changed-your-code/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The C# 3.0 Compiler vs. .NET 2.0 Projects</title>
		<link>http://elegantcode.com/2008/03/24/the-c-30-compiler-vs-net-20-projects/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-c-30-compiler-vs-net-20-projects</link>
		<comments>http://elegantcode.com/2008/03/24/the-c-30-compiler-vs-net-20-projects/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 23:32:37 +0000</pubDate>
		<dc:creator>Tony Rasa</dc:creator>
				<category><![CDATA[C# 3.0]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/03/24/the-c-30-compiler-vs-net-20-projects/</guid>
		<description><![CDATA[Hello, Elegant Readers &#8211; to help me figure out how WordPress is put together, I thought I&#8217;d write a quick blog post about a question that came up last week. Recently this situation was discussed: someone had a solution that compiled and ran just fine on Visual Studio 2005, but after they upgraded it to [...]]]></description>
			<content:encoded><![CDATA[<p>Hello, Elegant Readers &#8211; to help me figure out how WordPress is put together, I thought I&#8217;d write a quick blog post about a question that came up last week.  Recently this situation was discussed: someone had a solution that compiled and ran just fine on Visual Studio 2005, but after they upgraded it to Visual Studio 2008, targeting the .NET 2.0 framework, they ran into some major errors.</p>
<p>Comparing the VS2005 vs VS2008 files showed that the only thing changed in those files was the &#8220;solution version&#8221; info from 8 to 9 &#8211; just the basic &#8220;you&#8217;re a now VS2008 project&#8221; information, but nothing vital.  So, if nothing changed in the files, and we&#8217;re still targeting the .NET 2.0 framework, why would the program break?  Shouldn&#8217;t the VS2008 output be identical to VS2005?</p>
<p>The answer is: nope.</p>
<p>Even if you are targeting the .NET 2.0 framework, Visual Studio 2008 <strong>will still use</strong> the C# 3.0 compiler and those .NET 3.5-based tools to do it&#8217;s thing.  In fact, you can even use all of that C# 3.0 syntax in your .NET 2.0-targeted projects without any problems: so &#8220;var,&#8221; anonymous types and properties, and lambda expressions all can be used.  The C# 3.0 compiler just generates standard 2.0 IL for those things.</p>
<p>The only thing you can&#8217;t do is use those .NET 3.0 / 3.5 features that rely on libraries provided by the newer .NET versions &#8211; LINQ, Func&lt;T&gt;, all that functionality that is included in the newer assemblies &#8211; well, you have to have the assemblies for that to work.</p>
<p>The project I used to see this for myself is <a href="http://elegantcode.com/wp-content/uploads/2008/03/whichcsharpcompilerareyou.zip" target="_blank">attached </a>- sometimes the best way to understand something is to do some empirical research, boil an issue down to something that you could test, write a prototype for, or just slap a new project together.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/03/24/the-c-30-compiler-vs-net-20-projects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>New tool: LINQPad</title>
		<link>http://elegantcode.com/2008/02/29/new-tool-linqpad/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=new-tool-linqpad</link>
		<comments>http://elegantcode.com/2008/02/29/new-tool-linqpad/#comments</comments>
		<pubDate>Sat, 01 Mar 2008 04:45:38 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/02/29/new-tool-linqpad/</guid>
		<description><![CDATA[I&#8217;m boning up on my LINQ to SQL skills again for a presentation I&#8217;m giving for Boise Code Camp.&#160; One cool little tool I&#8217;ve been exposed to recently is LINQPad.&#160; LINQPad is a great little tool for messing around with LINQ to SQL queries and testing ideas. Point LINQPad at a SQL Server database and [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m boning up on my LINQ to SQL skills again for a presentation I&#8217;m giving for <a href="http://www.BoiseCodeCamp.com">Boise Code Camp</a>.&nbsp; One cool little tool I&#8217;ve been exposed to recently is <a href="http://www.linqpad.net/">LINQPad</a>.&nbsp; LINQPad is a great little tool for messing around with LINQ to SQL queries and testing ideas.</p>
<p>Point LINQPad at a SQL Server database and then you can write your LINQ queries right in the tool.&nbsp; No having to deal with DataContext objects or any messy stuff like that.&nbsp; It also works with LINQ to Objects and LINQ to XML; plus it comes with about 200 samples.&nbsp;&nbsp; It reminds me a bit of the HQL Query Analyzer of Ayende&#8217;s &#8212; just a lot simpler to use.&nbsp; The main point is that you can get nearly instant results from your query, which defiantly helps in that critical &#8220;getting to know you&#8221; stage with a new technology.</p>
<p>The only gripe I have with it right now is that intellesense isn&#8217;t implemented yet.&nbsp; That is kind of like flying blind these days.&nbsp; But who is to complain over a free tool like this.</p>
<p>Note:LINQPad&nbsp; was written in conjunction with the book <a href="http://www.albahari.com/nutshell/">C# 3.0 in a Nutshell.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/02/29/new-tool-linqpad/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Code Cast 3 &#8211; Chris Brandsma</title>
		<link>http://elegantcode.com/2008/02/18/elegant-code-cast-episode-3-is-online/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=elegant-code-cast-episode-3-is-online</link>
		<comments>http://elegantcode.com/2008/02/18/elegant-code-cast-episode-3-is-online/#comments</comments>
		<pubDate>Mon, 18 Feb 2008 19:33:30 +0000</pubDate>
		<dc:creator>David Starr</dc:creator>
				<category><![CDATA[CodeCast]]></category>
		<category><![CDATA[Architecture and Design]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Code Cast]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Patterns and Practices]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/02/18/elegant-code-cast-episode-3-is-online/</guid>
		<description><![CDATA[In this episode of the Elegant Code Cast, we visit with Elegant Coder Chris Brandsma. Chris is a senior developer at Mobile Data Force in Boise, Idaho. Chris provides some great details on subjects ranging from AJAX and RIA separation of concerns to LINQ and Lambda expressions. He also gives us a glimpse of what [...]]]></description>
			<content:encoded><![CDATA[<p>In this episode of the Elegant Code Cast, we visit with Elegant Coder Chris Brandsma. Chris is a senior developer at Mobile Data Force in Boise, Idaho. Chris provides some great details on subjects ranging from AJAX and RIA separation of concerns to LINQ and Lambda expressions.</p>
<p>He also gives us a glimpse of what it is like to live your life visiting other people&#8217;s development shops. Did you know source control is stil optional in some organizations?</p>
<p>Chris is a true code craftsman and this shows in his clear explanations of some very advanced programming concepts. If you haven&#8217;t played with Lambda expressions, anonymous delegates, or LINQ, start with this podcast.</p>
<p><a href="http://pluralsight-free.s3.amazonaws.com/david-starr/ecc/ECC_03_ChrisBrandsma.mp3">Download the episode MP3</a></p>
<p><a href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=271207118"><img src="http://elegantcode.com/cast/files/images/itunes_button.gif" border="0" alt="View in iTunes" /></a> <a href="http://feeds.feedburner.com/elegantcodecast"><img src="http://elegantcode.com/cast/files/images/rss_podcast.jpg" border="0" alt="Any Podcatcher" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/02/18/elegant-code-cast-episode-3-is-online/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://pluralsight-free.s3.amazonaws.com/david-starr/ecc/ECC_03_ChrisBrandsma.mp3" length="38813673" type="audio/mpeg" />
		</item>
		<item>
		<title>Firing events with Extension Methods</title>
		<link>http://elegantcode.com/2007/12/05/firing-events-with-extension-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=firing-events-with-extension-methods</link>
		<comments>http://elegantcode.com/2007/12/05/firing-events-with-extension-methods/#comments</comments>
		<pubDate>Thu, 06 Dec 2007 05:21:28 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Extension Methods]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2007/12/05/firing-events-with-extension-methods/</guid>
		<description><![CDATA[OK, sometimes you have an idea that is one point (seemingly) brilliant, simple, and kind of stupid all in one shot.  This is one of those.  Actually, I&#8217;m still trying to figure out if this is really a good idea or not &#8212; and what better way to do that than to post the idea [...]]]></description>
			<content:encoded><![CDATA[<p>OK, sometimes you have an idea that is one point (seemingly) brilliant, simple, and kind of stupid all in one shot.  This is one of those.  Actually, I&#8217;m still trying to figure out if this is really a good idea or not &#8212; and what better way to do that than to post the idea on a blog and strike a flame war!  Bring it on.</p>
<p>Lets start with the standard model for creating and firing events.</p>
<h2>Step 1: Create the event</h2>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">event</span>EventHandler&lt;EventArgs&gt; OnLoadData;</pre>
<p>My current method is to always use the generic EventHandler&lt;&gt; instead of the old-school EventHandler.  I think it makes for better-looking code IMHO.</p>
<h2>Step 2: Fire the Event (Old Skool)</h2>
<pre><span class="lnum">   1:  </span><span class="kwrd">if</span>(OnLoadData != <span class="kwrd">null</span>)
<span class="lnum">   2:  </span>{
<span class="lnum">   3:  </span>OnLoadData(<span class="kwrd">this</span>, <span class="kwrd">null</span>);
<span class="lnum">   4:  </span>}</pre>
<style type="text/css">        .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<h2>Step 3: We can do better</h2>
<p>There is a cool feature that you get with extension methods: you can call an extension method on null base object!  So you can now do things that were impossible &#8211; like removing a null check when firing an event and just fire the event!</p>
<h2>Step 4: Create an extension method</h2>
<p>To start you have to create a static class and &#8230; oh forget it, here is the code.</p>
<pre><span class="lnum">   1:  </span><span class="kwrd">using</span> System;
<span class="lnum">   2:  </span> 
<span class="lnum">   3:  </span><span class="kwrd">namespace</span>MyNamespace
<span class="lnum">   4:  </span>{
<span class="lnum">   5:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span>MyExtensions
<span class="lnum">   6:  </span>    {
<span class="lnum">   7:  </span>        <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span>Fire&lt;TEventArgs&gt;(
                     <span class="kwrd">this</span>EventHandler&lt;TEventArgs&gt; myEvent,
                     <span class="kwrd">object</span>sender, TEventArgs e)
                     <span class="kwrd">where</span>TEventArgs: EventArgs
<span class="lnum">   8:  </span>        {
<span class="lnum">   9:  </span>            <span class="kwrd">if</span>(myEvent != <span class="kwrd">null</span>)
<span class="lnum">  10:  </span>myEvent(sender, e);
<span class="lnum">  11:  </span>        }
<span class="lnum">  12:  </span>    }
<span class="lnum">  13:  </span>}</pre>
<pre> </pre>
<h2>Step 5: Refactor Step 2</h2>
<pre><span class="lnum">   1:  </span>OnLoadData.Fire(<span class="kwrd">this</span>, <span class="kwrd">null</span>);</pre>
<style type="text/css">        .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<style type="text/css">        .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<style type="text/css">        .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<p>Done.</p>
<h2>Step 6: Profit</h2>
<p>Well, I will as soon as I figure out how.  I mean really, I save 3 friggen lines of code here.  Big deal&#8211;right?  Well, There are some moral victories in this. </p>
<ol>
<li>I simplified the firing of events ever so slightly by removing previously mandatory logic.</li>
<li>It is reusable.  The Fire extension method can be used with any event that we create with the generic EventHandler.</li>
<li>I have added an ever so small amount of clarity to what the code is doing.  Granted, this will only clear things up for the extreme noob or clueless manager who wants to see the code&#8230;but still. Let&#8217;s not be snobby about this.</li>
<li>I figured out a grand way to use and abuse Extension Methods in a useful way.  It makes me feel special.  What can I say.</li>
<li>And I like it.  Something about always having to check if the EventHander was null -EVERY SINGLE TIME I WANTED TO JUST FIRE A FREEKING EVENT- bugged me for some inexplicable reason.  This little hack sets my soul at ease.  So there.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2007/12/05/firing-events-with-extension-methods/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>SubSonic Collection to CSV</title>
		<link>http://elegantcode.com/2007/11/14/subsonic-collection-to-csv/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=subsonic-collection-to-csv</link>
		<comments>http://elegantcode.com/2007/11/14/subsonic-collection-to-csv/#comments</comments>
		<pubDate>Thu, 15 Nov 2007 03:36:02 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[SubSonic]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2007/11/14/subsonic-collection-to-csv/</guid>
		<description><![CDATA[I had a requirement for a search page that allowed for CSV download.  My web site is built using SubSonic, so I had to recreate that age old code to turn a domain collection into a flat file export.   First note: I wrote this in a couple of hours.  Most of the coding took 30 [...]]]></description>
			<content:encoded><![CDATA[<p>I had a requirement for a search page that allowed for CSV download.  My web site is built using <a href="http://www.subsonicproject.com">SubSonic</a>, so I had to recreate that age old code to turn a domain collection into a flat file export.  </p>
<p>First note: I wrote this in a couple of hours.  Most of the coding took 30 minutes, then about three to four hours to test and tweak.  Also, after you see the main code, I&#8217;m then going to rewrite it with .Net 3.5 in mind &#8212; using an Extension Method.</p>
<p>The hardest part of the project was figuring out what SubSonic object to use, then how to pass a generic reference to the method.  Because of SubSonic&#8217;s heavy use of generics, that did get interesting.  In fact, the primary method looks like this:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">string</span> CreateCsvData&lt;ItemType, ListType&gt;(

           ActiveList&lt;ItemType, ListType&gt; list)

           <span class="kwrd">where</span> ItemType : ActiveRecord&lt;ItemType&gt;, <span class="kwrd">new</span>()

           <span class="kwrd">where</span> ListType : AbstractList&lt;ItemType, ListType&gt;, <span class="kwrd">new</span>()</pre>
<style type="text/css">    .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<p>To decipher for the non-generically inclined: the method name is CreateCsvData.  You can pass in any SubSonic generated collection object as they all inherit from ActiveList.  What makes the code a bit ugly is the fact that ActiveList is a generic object that takes two other objects types in the declaration.  This is where having the source code handy really helps.</p>
<p>Understandably, there is a bit of code to doing this, so you can download it:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2007/11/exporttoexcel_20.zip" title="SubSonic Export To CSV for .Net 2.0">SubSonic Export To CSV for .Net 2.0</a></p>
<p>And if you are using .Net 3.5, here is an extension method version:</p>
<p><a href="http://elegantcode.com/wp-content/uploads/2007/11/exporttoexcel35.zip" title="SubSonic Export To CSV for .Net 3.5">SubSonic Export To CSV for .Net 3.5</a></p>
<h2>Using the code</h2>
<p>First step is to hook up SubSonic to you database (of course).  I use the AdventureWorks LT database myself for most samples, which has a Customer table.  One of the generated SubSonic objects you will get is a CustomerCollection object. </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">string</span> CreateCsv()

{

    CustomerCollection customerList = GetCustomers();

    SubSonicToCsv csv = <span class="kwrd">new</span> SubSonicToCsv();

    <span class="kwrd">return</span> csv.CreateCsvData(customerList);

}</pre>
<style type="text/css">      .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<pre class="csharpcode"> </pre>
<style type="text/css">      .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<p>Here is the code again, but this time using the .Net 3.5 extension method</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">string</span> CreateCsv35()

{

    CustomerCollection customerList = GetCustomers();

    <span class="kwrd">return</span> customerList.CreateCsvData();

}</pre>
<p>You can debate which version you like better yourself but I like the .Net 3.5 better myself.  It is cleaner, and integrates into the SubSonic API beautifully.</p>
<p>Now I just have to replicate this for LINQ For SQL.</p>
<style type="text/css">      .csharpcode, .csharpcode pre  {  	font-size: small;  	color: black;  	font-family: consolas, "Courier New", courier, monospace;  	background-color: #ffffff;  	/*white-space: pre;*/  }  .csharpcode pre { margin: 0em; }  .csharpcode .rem { color: #008000; }  .csharpcode .kwrd { color: #0000ff; }  .csharpcode .str { color: #006080; }  .csharpcode .op { color: #0000c0; }  .csharpcode .preproc { color: #cc6633; }  .csharpcode .asp { background-color: #ffff00; }  .csharpcode .html { color: #800000; }  .csharpcode .attr { color: #ff0000; }  .csharpcode .alt   {  	background-color: #f4f4f4;  	width: 100%;  	margin: 0em;  }  .csharpcode .lnum { color: #606060; }</style>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2felegantcode.com%2f2007%2f11%2f14%2fsubsonic-collection-to-csv%2f"><img border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2felegantcode.com%2f2007%2f11%2f14%2fsubsonic-collection-to-csv%2f" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2007/11/14/subsonic-collection-to-csv/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C# 3.0 Primer: Anonymous Delegates</title>
		<link>http://elegantcode.com/2007/11/06/c-30-primer-anonymous-delegates/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=c-30-primer-anonymous-delegates</link>
		<comments>http://elegantcode.com/2007/11/06/c-30-primer-anonymous-delegates/#comments</comments>
		<pubDate>Wed, 07 Nov 2007 04:38:37 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2007/11/06/c-30-primer-anonymous-delegates/</guid>
		<description><![CDATA[C# 3.0 will be hitting the shelves in a matter of weeks, and with it a host of new features.&#xA0; Features that are grounded on features already in C# 2.0.&#xA0; Skip to the facts: if you don&#8217;t understand generics and anonymous delegates (and ergo predicates) you are not going to understand C# 3.0 as well [...]]]></description>
			<content:encoded><![CDATA[<p>C# 3.0 will be hitting the shelves in a matter of weeks, and with it a host of new features.&#xA0; Features that are grounded on features already in C# 2.0.&#xA0; Skip to the facts: if you don&#8217;t understand generics and anonymous delegates (and ergo predicates) you are not going to understand C# 3.0 as well as you should.</p>
<p>While generics are easy (just start playing with List&lt;&gt; in System.Collections.Generic and feel the love), anonymous delegates and predicates take some getting used to.&#xA0; Mostly because they are not as easy to explain and they look funny.</p>
<p>The basics are this: Anonymous Delegates allow you to pass code into an existing method.&#xA0; You will see specific examples of anonymous delegates in the form of Predicates and Comparision.</p>
<p>The best place to see this in action is in the previously mentioned generic list class &quot;List&lt;T&gt;&quot;.&#xA0; The generic list basically make a dynamic array/collection that is strongly typed to whatever type you give the generic list.&#xA0; So if you want a collection of integers you type:</p>
<p>List&lt;int&gt; myList = new List&lt;int&gt;();</p>
<p>And off you go.&#xA0; But as you go, you should notice a few little gems in the List class.&#xA0; Things like Sort, Find, and Exists.&#xA0; If you lookup the definition of <a href="http://msdn2.microsoft.com/en-us/library/bfed8bca.aspx">Exists</a> (to pick on at random) you will see something like this:</p>
<pre>public bool <b>Exists</b>(Predicate&lt;<a>T</a>&gt; match);</pre>
<p>A predicate is a specific anonymous delegate that take an object and returns a boolean.&#xA0; Its declaration looks like this:</p>
<pre>public delegate bool <b>Predicate</b>&lt;<b>T</b>&gt;(<a>T</a> obj);</pre>
<p>Remember what I said earlier: a predicate allows you to pass in code to an existing method.&#xA0;&#xA0; The delegate Predicate defines what that code must look like.&#xA0;&#xA0; A method that takes an object (as defined by the type passed into the list) and return a boolean. Here is how you use it.</p>
<p>myList.Exists(delegate(int obj) { /<em><strong>* do something cool here */ </strong></em>})</p>
<p>The most common use for an Exists method is to find if a particular value exists in the list.&#xA0; For our case&#8230;say the number 5.&#xA0; You would then write this:</p>
<p>myList.Exists(delegate(int i) { return i == 5; })</p>
<p>So where is the anonymous delegate I was just talking about?&#xA0; Here it is all by itself:</p>
<p>delegate(int i) { return i == 5; }</p>
<p>It should look vaguely like a function declaration if I write it slightly different.&#xA0; Compare an anonymous delegate to a method returning a boolean:</p>
<table cellspacing="0" cellpadding="2" width="400" border="0">
<tbody>
<tr>
<td valign="top" width="200">delegate(int i)<br />
        <br />{ </p>
<p>&#xA0;&#xA0;&#xA0; return i == 5; </p>
<p>}</td>
<td valign="top" width="200">bool MethodName(int i)<br />
        <br />{</p>
<p>&#xA0;&#xA0; return i == 5;</p>
<p>}</td>
</tr>
</tbody>
</table>
<p>Don&#8217;t be fooled to thing we can just see if one value is the same as some other arbitrary value.&#xA0; You just have to return a True or a False.&#xA0; If you want to know if any value is greater than 700, not a problem.&#xA0; Just return True or False.</p>
<h3>What does this buy us?</h3>
<p>While showing the use with a List of integers does make things nice and simple, what if we are dealing with a list of objects?&#xA0; If you have a customer object with a FirstName and LastName, how do you sort it?&#xA0; More importantly, how would a generic list object know how to sort it?&#xA0; It can&#8217;t.&#xA0; Not until that ESP module finally gets finished anyway.</p>
<p>What this buys us is flexibility to perform our esoteric business logic on complex objects.&#xA0; That is where anonymous delegates really start to shine.</p>
<h3>Caution in the wind</h3>
<p>Now that I&#8217;ve talked about the wonders that anonymous delegates can be, please use with caution.&#xA0; When misused they can turn into a 3 headed, fire breathing monster.&#xA0; Specifically I&#8217;ve seen many a developer try to write their own methods that take anonymous delegates to pursue the DRY (don&#8217;t repeat yourself) principle to ends unknown.&#xA0; </p>
<p>For example: if you are writing an anonymous delegate to save yourself a &#8216;for&#8217; loop, you might be a redneck &#8212; wait, that came out wrong.&#xA0; But you will have developers give you dirty looks once you check in, ok.</p>
<p>If you want an example if this, <a href="http://jagid.blogspot.com/2007/10/anonymous-delegate-overuse-anti-pattern.html">Jason Grundy wrote about this a while back.</a>&#xA0;</p>
<h3>Back to C# 3.0</h3>
<p>What does this have to do with C# 3.0?&#xA0; Everything that is Lambda and LINQ.&#xA0; Lambda is nothing but a cleaner way of writing anonymous delegates.&#xA0; Really.&#xA0; That is it.</p>
<p>My previous example moves from </p>
<p>myList.Exists(delegate(int i) { return i == 5; })</p>
<p>to a lambdaified (lambdaified: not a word yet, but it will be)</p>
<p>myList.Exists( x =&gt; x == 5)</p>
<p>Simple, clean, elegant.&#xA0; The lambda version is anyway.&#xA0; Now, if you don&#8217;t understand the x =&gt; x == 5, that is pure Lambda, and you will hearing a lot more about that in the near future.</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2007/11/06/c-30-primer-anonymous-delegates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

