<?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; Extension Methods</title>
	<atom:link href="http://elegantcode.com/tag/extension-methods/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Sat, 11 Feb 2012 04:39: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>ASP.Net HierarchicalDataSource&lt;T&gt;</title>
		<link>http://elegantcode.com/2008/04/06/aspnet-hierarchicaldatasourcet/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=aspnet-hierarchicaldatasourcet</link>
		<comments>http://elegantcode.com/2008/04/06/aspnet-hierarchicaldatasourcet/#comments</comments>
		<pubDate>Sun, 06 Apr 2008 06:45:44 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[asp.net]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Extension Methods]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/06/aspnet-hierarchicaldatasourcet/</guid>
		<description><![CDATA[The Asp.net 2.0 tree control, as well as many 3rd party controls binds to hierarchical data via an IHierarchicalDataSource interface. Asp.net provides an implementation OOTB with the HierarchicalDataSourceControl! Easy, let’s hook that up to our… wait this control only takes data in xml format or from a sitemap? Hmm, we don’t want to convert our [...]]]></description>
			<content:encoded><![CDATA[<p>The Asp.net 2.0 tree control, as well as many 3rd party controls binds to hierarchical data via an IHierarchicalDataSource interface. Asp.net provides an implementation OOTB with the HierarchicalDataSourceControl! Easy, let’s hook that up to our… wait this control only takes data in xml format or from a sitemap? Hmm, we don’t want to convert our model to xml, and a sitemap seems inappropriate. We spend a lot time doing great patterns such as MVP &amp; MVC, we should just be able to bind up a list of model objects we already have.
<p>Good thing MS has exposed a set of interfaces and abstract classes in System.Web.UI for us to implement our own IHierarchicalDataSource and HierarchicalDataSourceView and IHierarchicalEnumerable and then IHierarchyData&#8230; geesh.
<p>Data? So let&#8217;s see here, in order to bind our model to the tree control it needs to implement an interface in System.Web.UI? Well that&#8217;s just not going to happen, so its time for some Elegant Code.
<p><strong>Story:</strong>
<p>Dude, as a software developer, needs to create a custom implementation of IHierarchicalDataSource, and the rest of its parts, so that he can bind a list of objects to a tree control in asp.net
<ul>
<li>Use existing model to bind to tree control
<li>Must be able to reuse data source for future models
<li>Model must not contain a reference to System.Web.UI </li>
</ul>
<p>In order to setup our model to address the acceptance criteria we are going to use an interface with a self-referencing generic declaration, where the type will specify itself as the concrete type. This will let us create a nice generic hierarchical model to pass into our datasource without resorting to any sort of base class.
<div>
<pre class="csharpcode"><span class="kwrd">namespace</span> POC.Common
{
    <span class="kwrd">public</span> <span class="kwrd">interface</span> IModelWithHierarchy&lt;T&gt;
    {
        <span class="kwrd">string</span> Name { get; set; }
        T Parent { get; set; }
        List&lt;T&gt; Children { get; set; }
    }
}</pre>
<p><em>Lets note that we have placed the interface in a Common namespace which represents a shared.dll between Web &amp; Model</em> </div>
<p>The UI part of criteria is now a bit more tricky because the HierarchicalDataSourceView expects a IHierarchicalEnumerable datasource which contains IHierarchyData. Said IHierarchyData != IModelWithHierarchy&lt;T&gt;.&nbsp; Luckily someone else has already figured this one out for us. We need an <a href="http://www.dofactory.com/Patterns/PatternAdapter.aspx" target="_blank">adapter</a>. </p>
<p><a href="http://elegantcode.com/wp-content/uploads/2008/04/image7.png" target="_blank"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="123" alt="image" src="http://elegantcode.com/wp-content/uploads/2008/04/image-thumb7.png" width="244" border="0"></a> </p>
<p>To instantiate our HierarchyData adapter objects we will use an extension method and linq &#8216;Select&#8217; to convert our datasource IEnumerable&lt;T&gt; of IModelWithHierarchy&lt;T&gt; &#8216;s to an IHierarchicalEnumerable of IHierarchyData. </p>
<div>
<pre class="csharpcode"><span class="kwrd">namespace</span> POC.Web.HierarchyExtensions
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> HierarchyConverter
    {
        <span class="kwrd">public</span> <span class="kwrd">static</span> HierarchicalModelList
            ToHierarchicalModelList&lt;T&gt;(<span class="kwrd">this</span> IEnumerable&lt;T&gt; modelWithHierarchy)
            <span class="kwrd">where</span> T : IModelWithHierarchy&lt;T&gt;
        {
            <span class="kwrd">return</span> <span class="kwrd">new</span> HierarchicalModelList(
                modelWithHierarchy.Select(m =&gt; <span class="kwrd">new</span> HierarchyData&lt;T&gt;(m) <span class="kwrd">as</span> IHierarchyData));
        }
    }
}</pre>
</div>
<p>I am not going to bore you with the implementation details of the HierarachyData&lt;T&gt; adapter and the .net abstractions, but have dropped the <a href="http://elegantcode.com/wp-content/uploads/2008/04/hierarchydatasourcepoc.zip" target="_blank">source code here</a> if your interested. The end result: </p>
<div>
<pre class="csharpcode">TreeView1.DataSource = <span class="kwrd">new</span> HierarchicalModelDataSource&lt;Category&gt; { DataSource = Categories };
TreeView1.DataBind();
TreeView1.CollapseAll();</pre>
</div>
<p>Story complete!&nbsp; </p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/06/aspnet-hierarchicaldatasourcet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exploring Extension Methods in .Net 3.5</title>
		<link>http://elegantcode.com/2008/04/03/exploring-extension-methods-in-net-35/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=exploring-extension-methods-in-net-35</link>
		<comments>http://elegantcode.com/2008/04/03/exploring-extension-methods-in-net-35/#comments</comments>
		<pubDate>Thu, 03 Apr 2008 16:26:11 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[.Net 3.5]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/03/exploring-extension-methods-in-net-35/</guid>
		<description><![CDATA[Finding extension methods in C# 3.5 is not as intuitive as it should be. Just walking the inheritance chain will not show you all the goodies. There are a few steps using object browser that will make this easier. Pull up object browser, set Browse to only show 3.5. (Will not work if you set [...]]]></description>
			<content:encoded><![CDATA[<p>Finding extension methods in C# 3.5 is not as intuitive as it should be. Just walking the inheritance chain will not show you all the goodies. There are a few steps using object browser that will make this easier.</p>
<p><span id="more-1014"></span></p>
<ul>
<li>Pull up object browser, <strong>set Browse to only show 3.5</strong>. (Will not work if you set to all components)
<li>Set the filter to <strong>&#8216;Show Extension Members&#8217;</strong></li>
</ul>
<p><a href="http://elegantcode.com/wp-content/uploads/2008/04/image.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="114" alt="image" src="http://elegantcode.com/wp-content/uploads/2008/04/image-thumb.png" width="244" border="0"></a> </p>
<ul>
<li>Select a type in the browser
<li>In the right pane you will see an <strong>&#8216;Extension Members&#8217;</strong> folder
<li>Now you can browse the public type extensions</li>
</ul>
<p><a href="http://elegantcode.com/wp-content/uploads/2008/04/image1.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="118" alt="image" src="http://elegantcode.com/wp-content/uploads/2008/04/image-thumb1.png" width="244" border="0"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/03/exploring-extension-methods-in-net-35/feed/</wfw:commentRss>
		<slash:comments>0</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>LINQ Framework Design Guidelines</title>
		<link>http://elegantcode.com/2008/03/18/linq-framework-design-guidelines-2/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=linq-framework-design-guidelines-2</link>
		<comments>http://elegantcode.com/2008/03/18/linq-framework-design-guidelines-2/#comments</comments>
		<pubDate>Wed, 19 Mar 2008 01:53:22 +0000</pubDate>
		<dc:creator>Jarod Ferguson</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Microsoft]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/03/18/linq-framework-design-guidelines-2/</guid>
		<description><![CDATA[Excellent article on design considerations for LINQ. Looks like these concepts will be incorporated into the 2nd Edition of Framework Design Guidelines: Conventions, Idioms, and Patterns for Reuseable .NET Libraries. Cant wait to get my hands on a copy of that!]]></description>
			<content:encoded><![CDATA[<p>Excellent article on <a href="http://blogs.msdn.com/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx" target="_blank">design considerations for LINQ</a>. Looks like these concepts will be incorporated into the 2nd Edition of <a href="http://www.amazon.com/Framework-Design-Guidelines-Conventions-Development/dp/0321545613/ref=pd_bbs_sr_2?ie=UTF8&amp;s=books&amp;qid=1200508590&amp;sr=1-2" target="_blank">Framework Design Guidelines: Conventions, Idioms, and Patterns for Reuseable .NET Libraries</a>. Cant wait to get my hands on a copy of that!</p>
]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/03/18/linq-framework-design-guidelines-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</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>
	</channel>
</rss>

