<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Prashant Brall&#039;s Blog</title>
	<atom:link href="http://prashantbrall.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://prashantbrall.wordpress.com</link>
	<description>Every idea is a great idea as long as it is simple.</description>
	<lastBuildDate>Fri, 20 Jan 2012 23:20:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='prashantbrall.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Prashant Brall&#039;s Blog</title>
		<link>http://prashantbrall.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://prashantbrall.wordpress.com/osd.xml" title="Prashant Brall&#039;s Blog" />
	<atom:link rel='hub' href='http://prashantbrall.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Principles of Programming</title>
		<link>http://prashantbrall.wordpress.com/2012/01/20/principles-of-programming/</link>
		<comments>http://prashantbrall.wordpress.com/2012/01/20/principles-of-programming/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 23:18:04 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Motivation]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[Composition over inheritance]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Interface seggregation]]></category>
		<category><![CDATA[Separation Of Concerns]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1191</guid>
		<description><![CDATA[Great video tutorial about principles of programming. Principles of Programming Part 1 Principles of Programming Part 2 Happy Clean Coding !!!<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1191&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Great video tutorial about principles of programming.<br />
<a href="http://www.youtube.com/watch?v=v86fZZ0YpQs" title="Principles of Programming Part 1" target="_blank"><br />
Principles of Programming Part 1 </a></p>
<p><a href="http://www.youtube.com/watch?v=fSWlf56SiW8" title="Principles of Programming Part 2" target="_blank">Principles of Programming Part 2</a></p>
<p>Happy Clean Coding !!!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1191/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1191&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2012/01/20/principles-of-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>
	</item>
		<item>
		<title>Layer Supertype Pattern</title>
		<link>http://prashantbrall.wordpress.com/2011/10/25/layer-supertype-pattern/</link>
		<comments>http://prashantbrall.wordpress.com/2011/10/25/layer-supertype-pattern/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 19:19:10 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[Business Logic Layer]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[Layer Supertype Pattern]]></category>
		<category><![CDATA[SOLID]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1163</guid>
		<description><![CDATA[In this post i am going to show another of my favorite pattern called the Layer Supertype Pattern. It&#8217;s again a very simple but very useful pattern and was described by Martin Fowler in his famous book Patterns of Enterprise Application Architecture. If you haven&#8217;t read this book I strongly recommend you to read this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1163&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post i am going to show another of my favorite pattern called the Layer Supertype Pattern. It&#8217;s again a very simple but very useful pattern and was described by <a href="http://martinfowler.com/" title="Martin Fowler" target="_blank">Martin Fowler</a> in his famous book <a href="http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420/ref=sr_1_1?ie=UTF8&amp;qid=1319090234&amp;sr=8-1" title="Patterns of Enterprise Application Architecture" target="_blank">Patterns of Enterprise Application Architecture</a>. If you haven&#8217;t read this book I strongly recommend you to read this as it will help you in building better Enterprise Applications.</p>
<p>Anyway this is what the definition in the book is :-</p>
<div class="quote-box">
<em>
<p style="margin:5px;">
It&#8217;s not uncommon for all the objects in a layer to have methods you don&#8217;t want to have duplicated throughout the system. You can move all of this behavior into a common Layer Supertype.</em></p>
</div>
<p>&nbsp;</p>
<p>
In the past I have implemented various different implementation of this pattern but the common design pattern is that for a layer or suite of component with specialized behaviour we can abstract some behaviour or attribute to a base class so that we can remove some of the duplications.
</p>
<p>
For example say we are designing a business layer and we have set of business objects the purpose of this layer is to validate domain objects before it can be persisted in a data store. As we can see these business object will encapsulate this functionality from other layers, and its main functionality will be indicate whether the business object itself is valid or not and what the different violation it has from a business rules.
</p>
<p>
Well that&#8217;s a good starting point and things we have identified using our <a href="http://en.wikipedia.org/wiki/OOAD" title="Object Oriented Analysis and Design">Object Oriented Analysis and Design</a> ( OOAD ) are :-</p>
<ul>
<li>Business Rule (holds the rule definition)</li>
<li>A base entity (to state whether the object is valid and what are the violations</li>
<li>Business Object ( will implement the Entity Base )</li>
</ul>
<p>Lets start writing some code :-</p>
<p><u><b>BusinessRule.cs</b></u></p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> BusinessRule
{
   <span class="kwrd">public</span> <span class="kwrd">string</span> Property { get; set; }

   <span class="kwrd">public</span> <span class="kwrd">string</span> Rule { get; set; }

   <span class="kwrd">public</span> BusinessRule(<span class="kwrd">string</span> property, <span class="kwrd">string</span> rule)
   {
      Property = property;
      Rule = rule;
   }
}</pre>
<p><u><strong>EntityBase.cs</strong></u></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> EntityBase&lt;T&gt;
{
   <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;BusinessRule&gt; _brokenRules = <span class="kwrd">new</span> List&lt;BusinessRule&gt;();
   <span class="kwrd">protected</span> <span class="kwrd">abstract</span> <span class="kwrd">void</span> Validate();

   <span class="kwrd">public</span> IEnumerable&lt;BusinessRule&gt; GetBrokenRules()
   {
      _brokenRules.Clear();
      Validate();
      <span class="kwrd">return</span> _brokenRules;
   }

   <span class="kwrd">protected</span> <span class="kwrd">void</span> AddBrokenRule(BusinessRule businessRule)
   {
      _brokenRules.Add(businessRule);
   }
}</pre>
<p>Lets implement a customer class which inherits from the EntityBase class.</p>
<p><u><strong>Customer.cs</strong></u></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer : EntityBase&lt;Int32&gt;
{
   <span class="kwrd">public</span> Int32 Id { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { get; set; }
   <span class="kwrd">public</span> DateTime DOB { get; set; }

   <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Validate()
   {
      <span class="kwrd">if</span> (<span class="kwrd">string</span>.IsNullOrEmpty(FirstName))
      {
         AddBrokenRule(<span class="kwrd">new</span> BusinessRule(<span class="str">"FirstName"</span>,<span class="str">"First name cannot be empty"</span>));
      }

      <span class="kwrd">if</span> (<span class="kwrd">string</span>.IsNullOrEmpty(LastName))
      {
         AddBrokenRule(<span class="kwrd">new</span> BusinessRule(<span class="str">"LastName"</span>, <span class="str">"Last name cannot be empty"</span>));
      }

   }
}</pre>
<p>And to complete the task lets write a unit test to check whether we get the desired result or not.</p>
<p><u><strong>UnitTest.cs</strong></u></p>
<pre class="csharpcode">
[TestClass]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_using_customer
{
   [TestMethod]
   <span class="kwrd">public</span> <span class="kwrd">void</span> Should_ab_able_to_validate_customer()
   {
      <span class="rem">//Arrange</span>
      var customer = <span class="kwrd">new</span> Customer();

      <span class="rem">//Act</span>
      var brokenRules = customer.GetBrokenRules().ToList();

      <span class="rem">//Assert</span>
      Assert.IsTrue(brokenRules.Count &gt; 0);
   }
}</pre>
<p>And now when we run our unit test we get the two broken rules for customer,also if you look at the <strong>EntityBase</strong> class closely we are using <a href="http://prashantbrall.wordpress.com/2010/12/17/template-method-pattern/" title="Template Method Pattern" target="_blank">Template method pattern</a> in the <strong>GetBrokenRules</strong> method which I blogged last year and can be found <a href="http://prashantbrall.wordpress.com/2010/12/17/template-method-pattern/" title="Template Method Pattern" target="_blank">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1163/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1163&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/10/25/layer-supertype-pattern/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting started with NServiceBus</title>
		<link>http://prashantbrall.wordpress.com/2011/09/03/getting-started-with-nservicebus/</link>
		<comments>http://prashantbrall.wordpress.com/2011/09/03/getting-started-with-nservicebus/#comments</comments>
		<pubDate>Sat, 03 Sep 2011 07:44:18 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[NService Bus]]></category>
		<category><![CDATA[Distributed System]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Enterprise Service Bus]]></category>
		<category><![CDATA[MSMQ]]></category>
		<category><![CDATA[Nservice Bus]]></category>
		<category><![CDATA[Reliable Messaging]]></category>
		<category><![CDATA[Reliable System]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1125</guid>
		<description><![CDATA[In this post I am going to give a quick introduction into NServiceBus and how this can change the way you think or design distributed application for an enterprise. Before we get into specifics of NServiceBus lets see what is an Enterprise Service bus and how does it fits into the realm of an enterprise. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1125&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I am going to give a quick introduction into <a href="http://nservicebus.com" title="NService Bus" target="_blank">NServiceBus</a> and how this can change the way you think or design distributed application for an enterprise.</p>
<p>Before we get into specifics of <a href="http://nservicebus.com" title="NService Bus" target="_blank">NServiceBus</a> lets see what is an Enterprise Service bus and how does it fits into the realm of an enterprise. So the Wikipedia definition is</p>
<div class="quote-box">
<p>
<em>&nbsp;&nbsp;&nbsp;An enterprise service bus (ESB) is a software architecture model used for designing and &nbsp;&nbsp;&nbsp;implementing the interaction and communication between mutually interacting software &nbsp;&nbsp;&nbsp;applications in Service Oriented Architecture. As a software architecture model for &nbsp;&nbsp;&nbsp;distributed computing it is a specialty variant of the more general client-server software &nbsp;&nbsp;&nbsp;architecture model and promotes strictly asynchronous message oriented design for &nbsp;&nbsp;&nbsp;communication and interaction between applications. Its primary use is in Enterprise &nbsp;&nbsp;&nbsp;Application Integration of heterogeneous and complex landscapes.</em>
</div>
<p>So here are some of the key features of NServiceBus :-</p>
<ul>
<li>It&#8217;s not a centralized broker like BizTalk or IBM Websphere Message Broker</li>
<li>It&#8217;s not a Service Communication Framework like WCF.</li>
<li>Build on top of MSMQ.</li>
<li>Focuses on messaging and publish/subscribe model.</li>
<li>It&#8217;s very robust and reliable</li>
<li>There is no synchronous communication</li>
<li>The Community Edition of NServiceBus is absolutely free and can handle up to 30 messages/sec which comes out to be around 2.59 million message a day on a decent quad-core server machine.</li>
<li>The licensed version of NService is merely $2000 per license and can handle 100 messages/sec or 86.4 million messages.</li>
<li>Highly extensible</li>
<li>Written by the software simplest the great Udi Dahan.</li>
</ul>
<p>Okay that&#8217;s was like the product overview but if you are like me, you might be itching to go ahead and use this stuff. So here is how you can jump into the NServiceBus wagon (oops the pun ).</p>
<ul>
<li>Go to <a href="http://nservicebus.com" title="NService Bus" target="_blank">http://nservicebus.com</a></li>
<li>Click on &#8220;Download v2.5 SP1&#8243;</li>
<li>Unzip the file and run RunMeFirst.bat as an admin</li>
<li>Install or configure MSMQ</li>
<li>Go to the samples folder and open the Full Duplex project</li>
</ul>
<p>Just to get a feel of what the project structure looks so here it.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-project-structure.png?w=600" alt="Full Duplex Project Structure" class="code-box" /></p>
<p>As you can see the project structure is self-explanatory, there is a client and a server and client is going to send a message and the server will take process the  message and return it back to client.Lets run the project and see what happens.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-console-output.png?w=600" alt="Full Duplex Console Output" class="code-box" /> </p>
<p>and as you can see in the above figure that client and server are launched and ready to exchange messages. Lets hit enter in the Client console window and you will see the message gets send to the server with a Guid, which is received by the server and server sends back the message back to the client.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-message-send-and-recieved.png?w=600" alt="Full Duplex message send and received" class="code-box" /></p>
<p>So till now nothing special but it&#8217;s time to go deeper and start tinkering with <a href="http://nservicebus.com" title="NService Bus" target="_blank">NServiceBus</a> to understand some more. What I&#8217;ll now do is from the solution this time I&#8217;ll run only the client and not the server to mimic <strong>&#8220;a real life distributed application with reliable messaging&#8221;</strong> kind of scenario. So lets run the client project in isolation.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-running-the-client.png?w=600" alt="Running the client in isolation" class="code-box" /></p>
<p>and we see that the client console windows gets launched and let hit enter to send a message to the service.So this is how it looks when we do that.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-sending-message-from-the-client.png?w=600" alt="Full Duplex Sending message from client" /></p>
<p>Now we will look how this message gets routed by NServiceBus. Lets open MSMQ and see where this message is routed and stored in MSMQ.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/msmq-with-client-and-server-input-queues.png?w=600" alt="msmq client and server message queues" /></p>
<p>If you remember from the client console window that a message  with a guid 3e8eeb98-0130-429a-862c-a56f5a02d95b but the message id in the server queue is something different and you must be wondering about this mismatch.</p>
<p>Lets open the message and see what&#8217;s in there.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/msmq-message-body.png?w=600" alt="MSMQ message body" /></p>
<p>So here in the message you can see the Data Id which matches the guid and this is how the server can correlated the incoming messaging and outgoing message to the client.</p>
<p>Now lets run the solution again and see how the NServiceBus will pick up the message process it and send it back to client and client will display the returned message from the server.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-off-line-processing.png?w=600" alt="Full Duplex - Offline processing" class="code-box" /></p>
<p>Viola !!! We see the NServiceBus picks up the message and processes it and return the message back to client and the client receives the processed message.If at this point you open the MSMQ and you will see that the message has been processed from the Server Queue and since the client has received the message the message disappears from the client queue. This is a good project to understand the core of NServiceBus and getting started with it.</p>
<p>One of thing I like about NServiceBus is the documentation is superb and all the sample projects are really good to understand. Hopefully I will able to bring more real-life &amp; complex implementation of NServiceBus as I go my implementing in my current project.Till then &#8230;..</p>
<p>Enjoy !!! </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1125/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1125&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/09/03/getting-started-with-nservicebus/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-project-structure.png" medium="image">
			<media:title type="html">Full Duplex Project Structure</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-console-output.png" medium="image">
			<media:title type="html">Full Duplex Console Output</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-message-send-and-recieved.png" medium="image">
			<media:title type="html">Full Duplex message send and received</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-running-the-client.png" medium="image">
			<media:title type="html">Running the client in isolation</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-sending-message-from-the-client.png" medium="image">
			<media:title type="html">Full Duplex Sending message from client</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/msmq-with-client-and-server-input-queues.png" medium="image">
			<media:title type="html">msmq client and server message queues</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/msmq-message-body.png" medium="image">
			<media:title type="html">MSMQ message body</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/09/fullduplex-off-line-processing.png" medium="image">
			<media:title type="html">Full Duplex - Offline processing</media:title>
		</media:content>
	</item>
		<item>
		<title>Why program against an interface ?</title>
		<link>http://prashantbrall.wordpress.com/2011/07/19/why-program-against-an-interface/</link>
		<comments>http://prashantbrall.wordpress.com/2011/07/19/why-program-against-an-interface/#comments</comments>
		<pubDate>Tue, 19 Jul 2011 21:10:39 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[Composition over inheritance]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Interface seggregation]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Separation Of Concerns]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Windsor Castle]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1101</guid>
		<description><![CDATA[I have done a lot of post regarding interface based programming and we have seen some good benefits of programming against an interface as compare to its concrete implementation. One of the best things it does it that it promotes SOLID design principles and allows us to have a level of abstraction or separation of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1101&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have done a lot of post regarding interface based programming and we have seen some good benefits of programming against an interface as compare to its concrete implementation. One of the best things it does it that it promotes <a href="http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29" title="SOLID Design Principles" target="_blank">SOLID</a> design principles and allows us to have a level of abstraction or separation of concerns.</p>
<p>If you haven’t read my previous post about the benefits of interface I recommend reading them and here are some of those posts.</p>
<ul>
<li><a href="http://prashantbrall.wordpress.com/2010/06/22/interfaces-tdd/" title="Interface and TDD" target="_blank">Interface design promotes better unit testing and TDD</a></li>
<li><a href="http://prashantbrall.wordpress.com/2010/12/01/loosely-coupled-architecture/" title="Loosely coupled Architecture" target="_blank">Building loosely coupled architecture</a></li>
<li><a href="http://prashantbrall.wordpress.com/2011/02/16/decorator-pattern/" title="Decorator Pattern" target="_blank">Decorator Pattern</a></li>
<li><a href="http://prashantbrall.wordpress.com/2010/08/24/getting-started-with-windsor-castle/" title="Getting Started with Castle Windsor" target="_blank">Dependency Injection ( Getting Started with Castle Windsor )</a></li>
<li><a href="http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/" title="Specification Pattern" target="_blank">Specification Pattern</a></li>
<li><a href="http://prashantbrall.wordpress.com/2011/06/05/composite-pattern/" title="Extension by composition" target="_blank">Extension by Composition</a></li>
</ul>
<p>In this post I am going to show another benefit of using interfaces and that is how easy it is to add additional behavior (decorators) without changing the code. With interfaces you are able to provide nice extensibility point and keeping our code SOLID ( yes it is the big &#8216;<a href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Open Closed Principle" target="_blank">O</a>&#8216; in SOLID) and as usual Dependency Injection plays a key role in accomplishing the task with minimal effort.</p>
<p>Let’s start with a simple interface like this one.</p>
<p><strong><u>ICustomerRepository.cs</u></strong></p>
<pre class="csharpcode">

<span class="kwrd">public</span> <span class="kwrd">interface</span> ICustomerRepository
{
   List&lt;Customer&gt; GetCustomers();
}</pre>
<p>And let’s write the CustomerRepository class which implements this interface.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> CustomerRepository : ICustomerRepository
{
   <span class="kwrd">public</span> List&lt;Customer&gt; GetCustomers()
   {
      <span class="kwrd">return</span> <span class="kwrd">new</span> List&lt;Customer&gt;
                {
                   <span class="kwrd">new</span> Customer(1, <span class="str">"Joe"</span>, <span class="str">"Blogg"</span>),
                   <span class="kwrd">new</span> Customer(2, <span class="str">"John"</span>, <span class="str">"Doe"</span>)
                };
   }
}</pre>
<p>And this is our client code that calls the CustomerRepository class, it’s a standard example I have used in most of my posts depicting a real world example of business layer calling the repository layer.</p>
<p><strong><u>CustomerBl.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> CustomerBl : ICustomerBl
{
   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository _customerRepository;
   <span class="kwrd">public</span> CustomerBl(ICustomerRepository customerRepository)
   {
      _customerRepository = customerRepository;
   }

   <span class="kwrd">public</span> List&lt;Customer&gt; GetCustomers()
   {
      <span class="kwrd">return</span> _customerRepository.GetCustomers();
   }
}</pre>
<p>I will add a simple class diagram for people who love to see the class diagram,as I personally favor class diagram over code.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/07/icustomer-repository-interface-1.png?w=600" alt="Customer Repository Injected into Customer Business Layer" /></p>
<p>As you can see nothing special, we are just using constructor injection in our CustomerBl so that through IoC I can decide which class will be injected into the CustomerBl as long as the class implements the ICustomerRepository interface (contract).</p>
<p>So far so good the code is running fine and it’s in production, your customer is happy and you feel good about it. </p>
<p>After some time the customer says that I want to do logging when this function is called and the first thing which comes to your mind is okay I will write a logging code in the CustomerRepository GetCustomers() method.</p>
<p>But wait lets put some thought into this. First as soon as you are modifying the CustomerRepository class you are breaking the Single Responsibility Principle as this class has now 2 reasons to change.</p>
<ul>
<li>If the GetCustomers() method logic changes</li>
<li>If the logging mechanism changes</li>
</ul>
<p>Lets think “<em>does this logging really the CustomerRepository’s  responsibility</em>” and at the same time we don’t want to put the logging code into CustomerBl class as it’s not even its responsibility. And what about the logging it could change in the future.</p>
<p>So let’s abstract the logging responsibility into its own interface like this.</p>
<p><strong><u>ILogger.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">interface</span> ILogger
{
   <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message);
}</pre>
<p>And the class which implements this interface is</p>
<p><strong><u>DebugLogger.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> DebugLogger : ILogger
{
   <span class="kwrd">public</span> <span class="kwrd">void</span> Log(<span class="kwrd">string</span> message)
   {
      Debug.WriteLine(message);
   }
}</pre>
<p>Here I have chosen a simple class which writes to the output window to keep the example as simple as possible and since we are implementing through interface we can easily change it into file based or database based logger using the Dependency Injection Principle.</p>
<p>Here is the interesting part as you can see from our ICustomerRepository interface that the CustomerBl class just care for this interface and has no knowledge of what the actual class does.</p>
<p>This gives us a good opportunity to implement a new class which has the same interface signature but does the logging and then calls our actual CustomerRepository class as is. With this philosophy nothing has changed and the new class would act as a proxy.</p>
<p>Hmmm let me show you the code and see if I can make more sense so I will create a new class called LogCustomerRepository which will implement the ICustomerRepository interface and will have dependency on it as well as on the ILogger interface.</p>
<p><strong><u>LogCustomerRepository.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> LogCustomerRepository : ICustomerRepository
{
   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository _customerRepository;
   <span class="kwrd">private</span> <span class="kwrd">readonly</span> ILogger _logger;

  <span class="kwrd">public</span> LogCustomerRepository(ICustomerRepository customerRepository,
         ILogger logger)
   {
      _customerRepository = customerRepository;
      _logger = logger;
   }

   <span class="kwrd">public</span> List&lt;Customer&gt; GetCustomers()
   {
      _logger.Log(<span class="str">"Before the get customer method"</span>);
      var result = _customerRepository.GetCustomers();
      _logger.Log(<span class="kwrd">string</span>.Format(<span class="str">"Total results found {0}"</span>, result.Count));
      <span class="kwrd">return</span> result;
   }
}</pre>
<p>And an elaborated class diagram.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/07/icustomer-interface-implementation-2.png?w=600" alt="Log Customer Repository Injected into Customer Business Layer" /></p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/07/icustomer-interface-implementation-3.png?w=600" alt="Customer Repository Injected into Log Customer Repository" /><br />
So as you can this class just decorates the CustomerRepository and it shouldn’t make any difference to the client code(CustomerBl) as both the class implement the same interface (contract).</p>
<p>Now only thing left is wire this up in our IoC and I am going to use Castle Windsor Installer to have a nice separation of the configuration from the actual container.</p>
<p>If you are not familiar with Castle Windsor installer class please read my <a href="http://prashantbrall.wordpress.com/2010/09/06/windsor-installer-in-castle-windsor/" title="Installers in Castle Windsor" target="_blank">previous post</a> about it.</p>
<p><strong><u>CustomerInstaller.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> CustomerInstaller : IWindsorInstaller
{
   <span class="kwrd">public</span> <span class="kwrd">void</span> Install(IWindsorContainer container,
                       IConfigurationStore store)
   {
      container.Register(
         Component.For&lt;ILogger&gt;()
            .ImplementedBy&lt;DebugLogger&gt;(),

         Component.For&lt;ICustomerRepository&gt;()
            .ImplementedBy&lt;CustomerRepository&gt;(),

         Component.For&lt;ICustomerRepository&gt;()
            .ImplementedBy&lt;LogCustomerRepository&gt;()
            .Named(<span class="str">"LogCustomerRepository"</span>),

         Component.For&lt;ICustomerBl&gt;()
            .Named(<span class="str">"CustomerBl"</span>)
            .ImplementedBy&lt;CustomerBl&gt;()
            .ServiceOverrides
            (
               ServiceOverride
                  .ForKey(<span class="str">"customerRepository"</span>)
                  .Eq(<span class="str">"LogCustomerRepository"</span>)
            )
      );
   }
}</pre>
<p>This is the core of how registration and components works in Castle Windsor. The important thing to notice here is I am using named component registration as I want to make sure that when my CustomerBl class asks CastleWindsor to resolve for an implementation of type of ICustomerRepository it will return the LogCustomerRepository class instead of CustomerRepository and this way I am making sure that the decorators are invoked in the right order.</p>
<p>So in the ServiceOverrides method I am telling CastleWindsor that CustomerBl has a Dependency on ICustomerRepository and the <strong><u>name of the variable</u></strong> which is passed into the constructor is &#8220;customerRepository&#8221; and when you come across this variable then invoked the registered component which has been tagged as &#8220;LogCustomerRepository&#8221; rather than the default registered component CustomerRepository.</p>
<p>Although this syntax is very specific to Castle Windsor but the concept is quite uniform across all the IoC containers.</p>
<p>Let’s write a unit test to see how this all comes together.</p>
<p><strong><u>UnitTest.cs</u></strong></p>
<pre class="csharpcode">
[TestClass]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_using_CustomerBl
{
   <span class="kwrd">private</span> IWindsorContainer _container;
   [TestInitialize]
   <span class="kwrd">public</span> <span class="kwrd">void</span> Setup()
   {
      _container = <span class="kwrd">new</span> WindsorContainer();
      _container.Install(<span class="kwrd">new</span> CustomerInstaller());
   }

   [TestMethod]
   <span class="kwrd">public</span> <span class="kwrd">void</span> Should_be_able_to_get_customers()
   {
      var customerBl = _container
                        .Resolve&lt;ICustomerBl&gt;
                        (<span class="str">"CustomerBl"</span>);

      var result = customerBl.GetCustomers();
      Assert.IsTrue(result.Count &gt; 0);
   }
}</pre>
<p>And when I run the test it passes with the desired result and in the output window I do see the messages I expect.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/07/unit-test-for-log-customer-repository.png?w=600" alt="Unit Test " /></p>
<p>As you can see from the Watch window that how these interfaces are resolved by Castle Windsor and how I am getting the correct type when I need it. </p>
<p>This way of decorating interfaces and creating decorators is a nice and easy pattern but it also gives us some insight into <a href="http://en.wikipedia.org/wiki/Aspect-oriented_software_development">Aspect Oriented Programming</a> as these decorators are merely cross cutting aspects.</p>
<p>For example we can easily create Logging,Security,Caching,Instrumentation etc decorators and Inject them with Castle Windsor.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1101/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1101/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1101/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1101&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/07/19/why-program-against-an-interface/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/07/icustomer-repository-interface-1.png" medium="image">
			<media:title type="html">Customer Repository Injected into Customer Business Layer</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/07/icustomer-interface-implementation-2.png" medium="image">
			<media:title type="html">Log Customer Repository Injected into Customer Business Layer</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/07/icustomer-interface-implementation-3.png" medium="image">
			<media:title type="html">Customer Repository Injected into Log Customer Repository</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/07/unit-test-for-log-customer-repository.png" medium="image">
			<media:title type="html">Unit Test </media:title>
		</media:content>
	</item>
		<item>
		<title>Writing Rule Specification for the Composite Pattern</title>
		<link>http://prashantbrall.wordpress.com/2011/07/09/writing-rule-specification-for-the-composite-pattern/</link>
		<comments>http://prashantbrall.wordpress.com/2011/07/09/writing-rule-specification-for-the-composite-pattern/#comments</comments>
		<pubDate>Sat, 09 Jul 2011 07:14:39 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[Composition over inheritance]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Separation Of Concerns]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1095</guid>
		<description><![CDATA[In the last post we build a nice fluent interface to use composite pattern with Linq Expression. The idea was to use composite pattern to chain these conditions (specification) and Linq helped us a lot in accomplishing that. We also unit tested some of these expression to see how the linq expression are built for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1095&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://prashantbrall.wordpress.com/2011/06/21/composite-pattern-using-linq-expressions/" title="Composition Pattern" target="_blank">last post</a> we build a nice <a href="http://en.wikipedia.org/wiki/Fluent_interface" title="Fluent Interface" target="_blank">fluent interface</a> to use composite pattern with <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" title="Linq" target="_blank">Linq</a> Expression. The idea was to use composite pattern to chain these conditions (specification) and Linq helped us a lot in accomplishing that.</p>
<p>We also unit tested some of these expression to see how the linq expression are built for And,Or, Not conditions and had that flexibility to apply them using lambada expression. </p>
<p>So in this post I will show you how we should write these specification like a rule specification to mimic a real life application. </p>
<p>As a good designed of any framework or API our main goal is to hide the inner complexity and workings from consuming code and try to expose them with easy interfaces and write some unit test to show how these API&#8217;s will be consumed.</p>
<p>Lets look at the employee class we created in our previous post and build some rule specifications.</p>
<p><strong><u>Employee.cs</u></strong></p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Employee
{
   <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">virtual</span> IList&lt;Address&gt; Address { get; set; }
}</pre>
<p>And say the rule specifications for granting a leave are as follows :-</p>
<ul>
<li> <strong><em>If an employee has an address then he/she is preferred for taking a leave</em></strong></li>
<li> <strong><em>If an employee&#8217;s First Name starts with the letter &#8216;T&#8217; then they are considered highly experienced </em></strong></li>
<li> <strong><em>And an employee satisfies the above 2 condition then only they can take a leave</em></strong> </li>
</ul>
<p>I know these rules sounds really ridiculous but I just wanted to show the gravity of the rules, as I have always seen developers complaining that they couldn&#8217;t write a <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?ie=UTF8&amp;qid=1310250640&amp;sr=8-1" title="Clean Code" target="_blank">Clean Code</a> or <a href="http://en.wikipedia.org/wiki/SOLID" title="SOLID" target="_blank">SOLID</a> code because the business rules were way too complex and weird, or the client couldn&#8217;t make up their mind and kept on chopping and changing.</p>
<p>Yes I have faced the same situation before and in my opinion it is these confusing complex rules and inadequate unit test are the <u>main culprit of bad design and failure of a system</u>.Anyway that&#8217;s my personal opinion and let&#8217;s get back to writing these specification.</p>
<p><strong><u>Employee Rule Specification</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> EmployeeRuleSpecification
   {
      <span class="kwrd">public</span> CompositionWithExpression&lt;Employee&gt; IsPreferred
      {
         get
         {
            <span class="kwrd">return</span> <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
               (
                  e =&gt; e.Address.Count &gt; 0
               );
         }
      }

      <span class="kwrd">public</span> CompositionWithExpression&lt;Employee&gt; IsExperienced
      {
         get
         {
            <span class="kwrd">return</span> <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
               (
                  e =&gt; e.FirstName.StartsWith(<span class="str">"T"</span>)
               );
         }
      }

      <span class="kwrd">public</span> CompositionWithExpression&lt;Employee&gt; And(
                     CompositionWithExpression&lt;Employee&gt; other)
      {
         <span class="kwrd">return</span>
            <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
                                    (
                                       other.Predicate
                                    );
      }

      <span class="kwrd">public</span> ISpecificationWithExpression&lt;Employee&gt; PreferredAndExperienced
      {
         get
         {
            <span class="kwrd">return</span> (
                     <span class="kwrd">this</span>.IsPreferred.And(<span class="kwrd">this</span>.IsExperienced)
                   );
         }
      }
   }</pre>
<p>[<em>Pardon my indentation as I wanted to fit the long names and parameters with in the code box.</em>]</p>
<p>So here what we have done is we have moved the responsibility of specifying the rules into its own class and which is good design practice (<a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Single Responsibility Principle" target="_blank">Single Responsibility Principle</a>) and also the code looks very neat. </p>
<p>First If I am working on a huge project with the above code I don&#8217;t have to crawl though 1000 line to find out what this if else condition is trying to do.</p>
<p>Second if the rules changes or more rules need to be added I have to change only this class and that too because of the specification interface I am just adding a new specification and using composition compose a complex(compound) business rules.</p>
<p>Third important thing is that since I can do isolation testing on each expression as well as compound condition, I don&#8217;t have to go through 1000 lines of debugging to find out what condition is being invoked by the current state of the employee object. Otherwise we all have heard this thing <strong><u>&#8220;why it works in dev environment but fails in production&#8221;</u></strong> etc.</p>
<p>Lets plug this into our original Employee class by adding a new method CanTakeLeave.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> Employee
   {
      <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; set; }
      <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { get; set; }
      <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { get; set; }

      <span class="kwrd">public</span> <span class="kwrd">virtual</span> IList&lt;Address&gt; Address { get; set; }

      <span class="kwrd">public</span> <span class="kwrd">bool</span> CanTakeLeave()
      {
         var specification = <span class="kwrd">new</span> EmployeeRuleSpecification();
         <span class="kwrd">return</span> specification.IsExperienced
                             .And(specification.IsPreferred)
                             .IsSatisfiedBy(<span class="kwrd">this</span>);
      }
   }</pre>
<p>As you can see the class still looks neat and compact and there is no ugly if/else/switch etc.Lets write a unit test to see how this method will be called and test what result are expected under what circumstances.</p>
<p><strong><u>UnitTest.cs</u> </strong></p>
<pre class="csharpcode">
[TestClass]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_using_Employee_Rule_Specification
{
   [TestMethod]
   <span class="kwrd">public</span> <span class="kwrd">void</span> Should_be_able_to_take_leave()
   {
      var employee = BuildData.GetEmployeeWithAddress();
      var result = employee.CanTakeLeave();

      Assert.AreEqual(<span class="kwrd">true</span>, result);
   }
}</pre>
<p>As you can see for this test to verify correctly I am calling the GetEmployeeWithAddress static on the static BuildData class which return an employee with his/her address and in this case my test passes with flying colors.</p>
<p>I hope this post will help you write complex specification and rules for a real life project as you can specify any number of these rules specification and compose them together to build complex rules.</p>
<p>Last but not the least is if you like you can this further and decouple the dependency of rule specification object and the business object i.e pass an interface to your business object, something like this.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> Employee
{
   <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">virtual</span> IList&lt;Address&gt; Address { get; set; }

   <span class="kwrd">public</span> Employee(IEmployeeRuleSpecification employeeRuleSpecification)
   {

   }
}</pre>
<p>and then you can use <a href="http://en.wikipedia.org/wiki/Dependency_injection" title="Dependency Injection" target="_blank">Dependency Injection</a> to inject the rule specification which you might have boot strapped it your project.( May be I should leave that up to you guys <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  )</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1095/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1095/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1095/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1095&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/07/09/writing-rule-specification-for-the-composite-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>
	</item>
		<item>
		<title>Composite Pattern using Linq Expressions</title>
		<link>http://prashantbrall.wordpress.com/2011/06/21/composite-pattern-using-linq-expressions/</link>
		<comments>http://prashantbrall.wordpress.com/2011/06/21/composite-pattern-using-linq-expressions/#comments</comments>
		<pubDate>Tue, 21 Jun 2011 12:14:52 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Composition]]></category>
		<category><![CDATA[Composition over inheritance]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Expression Tree]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Linq Expression]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1071</guid>
		<description><![CDATA[I hope you guys have enjoyed by previous posts on Specification Pattern and the Composition Pattern as this post is an extension to those post and I recommend you read those post before you read this one. Composition Pattern Specification Pattern In this post I am going to take both patterns and apply some Linq [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1071&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I hope you guys have enjoyed by previous posts on Specification Pattern and the Composition Pattern as this post is an extension to those post and I recommend you read those post before you read this one.</p>
<p><a href="http://prashantbrall.wordpress.com/2011/06/05/composite-pattern/" title="Composition Pattern" target="_blank">Composition Pattern </a></p>
<p><a href="http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/" title="Specification Pattern" target="_blank">Specification Pattern</a></p>
<p>In this post I am going to take both patterns and apply some Linq expression as I always try to refactoring code and improve coding style every time I get a chance.</p>
<p>In the Specification Pattern post we started with a simple interface ISpecification as following:</p>
<p><strong><u>ISpecification.cs</u></strong></p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> ISpecification&lt;T&gt;
{
    <span class="kwrd">bool</span> IsSatisfiedBy(T candidate);
    ISpecification&lt;T&gt; And(ISpecification&lt;T&gt; other);
    ISpecification&lt;T&gt; Or(ISpecification&lt;T&gt; other);
    ISpecification&lt;T&gt; Not();
}</pre>
<p>And this interface is the core of the Composition Pattern so lets modify this interface so that we can use the Linq Expression provided by .NET.</p>
<p><strong><u>ISpecificationWithExpression.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">interface</span> ISpecificationWithExpression&lt;T&gt;
{
   Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; Predicate { get; }
   <span class="kwrd">bool</span> IsSatisfiedBy(T candidate);
   ISpecificationWithExpression&lt;T&gt; And(ISpecificationWithExpression&lt;T&gt; other);
   ISpecificationWithExpression&lt;T&gt; Or(ISpecificationWithExpression&lt;T&gt; other);
   ISpecificationWithExpression&lt;T&gt; Not();
}</pre>
<p>The idea is that we are going to use Linq Expression and its internal expression building logic to chain our conditions and because we are using Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt;</span> we can specify our criteria (condition) as a lambada Expression.</p>
<p>Lets move on and first implement the interface to see how our code structure looks like, I always prefer it this way so that I can see the bigger picture without getting into implementation specifics.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> CompositionWithExpression&lt;T&gt; : ISpecificationWithExpression&lt;T&gt;
{
   <span class="kwrd">public</span> Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; Predicate { get {  } }

   <span class="kwrd">public</span> <span class="kwrd">bool</span> IsSatisfiedBy(T candidate)
   {

   }

   <span class="kwrd">public</span> ISpecificationWithExpression&lt;T&gt; And(ISpecificationWithExpression&lt;T&gt; other)
   {

   }

   <span class="kwrd">public</span> ISpecificationWithExpression&lt;T&gt; Or(ISpecificationWithExpression&lt;T&gt; other)
   {

   }

   <span class="kwrd">public</span> ISpecificationWithExpression&lt;T&gt; Not()
   {

   }
}</pre>
<p>So this gives us a base structure of our class and now all what we have to do is implement the And(), Or() and the Not() methods using Linq Expressions and its compositions.</p>
<p><strong><u>CompositionWithExpression.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> CompositionWithExpression&lt;T&gt; : ISpecificationWithExpression&lt;T&gt;
{
   <span class="kwrd">private</span> <span class="kwrd">readonly</span> Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; _predicate;

   <span class="kwrd">public</span> CompositionWithExpression(Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; <span class="hiddenGrammarError">predicate)
   {
      _predicate</span> = predicate;
   }

   <span class="kwrd">public</span> Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt; Predicate
   {
      get { <span class="kwrd">return</span> _predicate; }
   }

   <span class="kwrd">public</span> <span class="kwrd">bool</span> IsSatisfiedBy(T entity)
   {
      <span class="kwrd">return</span> _predicate.Compile().Invoke(entity);
   }

   <span class="kwrd">public</span> ISpecificationWithExpression&lt;T&gt; And (ISpecificationWithExpression&lt;T&gt; other)
   {
      var otherInvoke = Expression.Invoke( other.Predicate,
                                           <span class="kwrd">this</span>._predicate.Parameters);

      var newExpression = Expression.MakeBinary(ExpressionType.AndAlso,
                                                _predicate.Body, otherInvoke);

      <span class="kwrd">return</span>
      <span class="kwrd">new</span> CompositionWithExpression&lt;T&gt;(Expression.Lambda&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt;
                                                   (newExpression,
                                                   _predicate.Parameters));
   }

   <span class="kwrd">public</span> ISpecificationWithExpression&lt;T&gt; Or(ISpecificationWithExpression&lt;T&gt; other)
   {
      var otherInvoke = Expression.Invoke(other.Predicate,
                                          <span class="kwrd">this</span>._predicate.Parameters);

      var newExpression = Expression.MakeBinary(ExpressionType.OrElse,
                                                _predicate.Body, otherInvoke);

      <span class="kwrd">return</span>
      <span class="kwrd">new</span> CompositionWithExpression&lt;T&gt;(Expression.Lambda&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt;
                                                   (newExpression,
                                                   _predicate.Parameters));
   }

   <span class="kwrd">public</span> ISpecificationWithExpression&lt;T&gt; Not()
   {
      var negateExpression = Expression.Lambda&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt;
                                          (Expression.Not(_predicate.Body),
                                           _predicate.Parameters);

      <span class="kwrd">return</span> <span class="kwrd">new</span> CompositionWithExpression&lt;T&gt;(negateExpression);
   }
}</pre>
<p>So far what we have done is that we have combined Lambada Expression based on method operation like Or,And and Not.</p>
<p>Lets write some unit test and see how we can use lambada expression to specify the condition.</p>
<pre class="csharpcode">
[TestClass]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_using_Specification_With_Expression
{
   [TestMethod]
   <span class="kwrd">public</span> <span class="kwrd">void</span> Should_be_able_to_invoke_or_condition()
   {
      var employee = BuildData.GetEmployee;

      var specification = <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
                                 (e =&gt; e.FirstName.StartsWith(<span class="str">"T"</span>));

      var anotherSpecification = <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
                                             (e =&gt; e.Address.Count &gt; 0);

      var newExpression = specification.Or(anotherSpecification);

      Assert.AreEqual(<span class="kwrd">true</span>, newExpression.IsSatisfiedBy(employee));
   }

   [TestMethod]
   <span class="kwrd">public</span> <span class="kwrd">void</span> Should_be_able_to_invoke_an_and_condition()
   {
      var employee = BuildData.GetEmployee;
      employee.Address = BuildData.GetAddress;

      var specification = <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
                                 (e =&gt; e.FirstName.StartsWith(<span class="str">"T"</span>));

      var andSpecification = <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
                                          (e =&gt; e.Address.Count &gt; 0);

      var compositeSpecification = specification.And(andSpecification);
      Assert.AreEqual(<span class="kwrd">true</span>, compositeSpecification.IsSatisfiedBy(employee));
   }

   [TestMethod]
   <span class="kwrd">public</span> <span class="kwrd">void</span> Should_be_able_to_invoke_a_not_condition()
   {
      var employee = BuildData.GetEmployee;
      employee.Address = BuildData.GetAddress;

      var specification = <span class="kwrd">new</span> CompositionWithExpression&lt;Employee&gt;
                                 (e =&gt; e.FirstName.StartsWith(<span class="str">"T"</span>));

      var negateSpecification = specification.Not();
      Assert.AreEqual(<span class="kwrd">false</span>, negateSpecification.IsSatisfiedBy(employee));
   }

}</pre>
<p>and this is how the employee class looks like</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> Employee
{
   <span class="kwrd">public</span> <span class="kwrd">int</span> Id { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> FirstName { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">string</span> LastName { get; set; }
   <span class="kwrd">public</span> <span class="kwrd">virtual</span> IList&lt;Address&gt; Address { get; set; }
}</pre>
<p>As you can see by the virtue of the fact that the CompositionWithExpression takes a Expression&lt;Func&lt;T, <span class="kwrd">bool</span>&gt;&gt;</span> as constructor parameter,I can pass a lambada expression to specify the condition and it&#8217;s so easy to understand.</p>
<p>I think this has been a very lengthy post in terms of code so I will break it up into another post where I will revisit creating different specification and chain them in our entity class the way we did it for Customer class in the <a href="http://prashantbrall.wordpress.com/2011/06/05/composite-pattern/" title="Composition Pattern" target="_blank">Composition Pattern post</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1071/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1071/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1071/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1071/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1071/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1071/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1071/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1071/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1071/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1071/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1071/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1071/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1071/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1071/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1071&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/06/21/composite-pattern-using-linq-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>
	</item>
		<item>
		<title>Composite Pattern</title>
		<link>http://prashantbrall.wordpress.com/2011/06/05/composite-pattern/</link>
		<comments>http://prashantbrall.wordpress.com/2011/06/05/composite-pattern/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 01:19:21 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[Composite Pattern]]></category>
		<category><![CDATA[Composition over inheritance]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Interface seggregation]]></category>
		<category><![CDATA[Separation Of Concerns]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1046</guid>
		<description><![CDATA[This post is continuation of my previous post on Specification Pattern and in this post we will see how we can chain these Specifications (the interface) to build more complex rule with help of Composition. First lets see the pattern statement The composite pattern describes that a group of objects are to be treated in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1046&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post is continuation of my previous post on <a href="http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/" title="Specification Pattern">Specification Pattern</a> and in this post we will see how we can chain these Specifications (the interface) to build more complex rule with help of Composition.</p>
<p>First lets see the pattern statement</p>
<div class="quote-box">
<div style="margin:10px;"><em>The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to &#8220;compose&#8221; objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.</em></div>
</div>
<p>
The reason why we choose composition is that the interface we define in our Specification looks like a Predicate i.e. it takes an object as argument and returns a Boolean so if we chain multiple specification together it should still return a Boolean i.e. multiple specification can be together to yield whether the compound condition is true or not.</p>
<p>Lets look at three possible ways to combine these condition :-</p>
<ol>
<li> And Specification</li>
<li> Or Specification</li>
<li>Not Specification</li>
</ol>
<p>And lets add the above three specification to our ISpecification interface we created in the <a href="http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/" title="Specification Pattern">Specification Pattern</a> post.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> ISpecification&lt;T&gt;
{
    <span class="kwrd">bool</span> IsSatisfiedBy(T candidate);
    ISpecification&lt;T&gt; And(ISpecification&lt;T&gt; other);
    ISpecification&lt;T&gt; Or(ISpecification&lt;T&gt; other);
    ISpecification&lt;T&gt; Not();
}</pre>
<p>
Now you can see how we are composing things together, in the interface since all the other specification have the same signature and the same return type we can combine them together without breaking the contract(interface) and this is the core principle of Composite Pattern.</p>
<p>Lets write a class which will implement this interface and will help us compose specifications.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> CompositeSpecification&lt;T&gt; : ISpecification&lt;T&gt;
{
    <span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">bool</span> IsSatisfiedBy(T candidate);

    <span class="kwrd">public</span> ISpecification&lt;T&gt; And(ISpecification&lt;T&gt; other)
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> AndSpecification&lt;T&gt;(<span class="kwrd">this</span>, other);
    }

    <span class="kwrd">public</span> ISpecification&lt;T&gt; Or(ISpecification&lt;T&gt; other)
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> OrSpecification&lt;T&gt;(<span class="kwrd">this</span>, other);
    }

    <span class="kwrd">public</span> ISpecification&lt;T&gt; Not()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> NotSpecification&lt;T&gt;(<span class="kwrd">this</span>);
    }
}</pre>
<p>
The important thing is that since the class has been designed using Generics it can be applied to any class. Lets write code for each of these Condition Specification.
</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> AndSpecification&lt;T&gt; : CompositeSpecification&lt;T&gt;
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;T&gt; left;
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;T&gt; right;

    <span class="kwrd">public</span> AndSpecification(ISpecification&lt;T&gt; left, ISpecification&lt;T&gt; right)
    {
        <span class="kwrd">this</span>.left = left;
        <span class="kwrd">this</span>.right = right;
    }

    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">bool</span> IsSatisfiedBy(T candidate)
    {
        <span class="kwrd">return</span> left.IsSatisfiedBy(candidate) &amp;&amp; right.IsSatisfiedBy(candidate);
    }
}</pre>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> NotSpecification&lt;T&gt; : CompositeSpecification&lt;T&gt;
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;T&gt; other;

    <span class="kwrd">public</span> NotSpecification(ISpecification&lt;T&gt; other)
    {
        <span class="kwrd">this</span>.other = other;
    }

    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">bool</span> IsSatisfiedBy(T candidate)
    {
        <span class="kwrd">return</span> !other.IsSatisfiedBy(candidate);
    }
}</pre>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> OrSpecification&lt;T&gt; : CompositeSpecification&lt;T&gt;
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;T&gt; left;
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;T&gt; right;

    <span class="kwrd">public</span> OrSpecification(ISpecification&lt;T&gt; left, ISpecification&lt;T&gt; right)
    {
        <span class="kwrd">this</span>.left = left;
        <span class="kwrd">this</span>.right = right;
    }

    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">bool</span> IsSatisfiedBy(T candidate)
    {
        <span class="kwrd">return</span> left.IsSatisfiedBy(candidate)
                  || right.IsSatisfiedBy(candidate);
    }
}</pre>
<p>
Lets visualize it in a class diagram and see all the code we have written so far.</p>
<p><img src="http://prashantbrall.files.wordpress.com/2011/06/composite-pattern.png?w=600" alt="Composite Pattern" class="code-box" /></p>
<p>Lets modify the ApplicationLoanSpecification class we created in the <a href="http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/" title="Specification Pattern" target="_blank">previous post</a> to implement the CompositePattern class.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> ApplicantLoanSpecification : CompositeSpecification&lt;Applicant&gt;
{
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">bool</span> IsSatisfiedBy(Applicant candidate)
    {
        <span class="kwrd">return</span> (candidate.CreditRating == 10 &amp;&amp; candidate.TotalEquity &gt; 45000);
    }
}</pre>
<p>
So far nothing has change drastically and now we will start creating some more specifications.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> SalarySpecification : CompositeSpecification&lt;Applicant&gt;
{
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">bool</span> IsSatisfiedBy(Applicant candidate)
    {
        <span class="kwrd">return</span> (candidate.Salary &gt; 100000);
    }
}
</pre>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> AgeSpecification : CompositeSpecification&lt;Applicant&gt;
{
    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">bool</span> IsSatisfiedBy(Applicant candidate)
    {
        <span class="kwrd">return</span> (candidate.Age &lt; 80);
    }
}</pre>
<p>
So here I just created some fictitious conditions to create a real life complex business rules, the important thing is that because of using the pattern each of my class are very small and very specific(pardon the pun). And it&#8217;s another good example of Single Responsibility principle.Lets put it all together in our Applicant class and see how the method chaining looks like.</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> Applicant
{
    <span class="kwrd">public</span> Int32 Id { get; set; }
    <span class="kwrd">public</span> Int32 Age { get; set; }
    <span class="kwrd">public</span> Int32 CreditRating { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">decimal</span> TotalEquity { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">decimal</span> Salary { get; set; }

    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;Applicant&gt; isQualifiedForLoan;
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;Applicant&gt; salaryIsQualified;
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ISpecification&lt;Applicant&gt; ageIsLessthanEighty;

    <span class="kwrd">public</span> Applicant()
    {
        isQualifiedForLoan = <span class="kwrd">new</span> ApplicantLoanSpecification();
        salaryIsQualified = <span class="kwrd">new</span> SalarySpecification();
        ageIsLessthanEighty = <span class="kwrd">new</span> AgeSpecification();

    }
    <span class="kwrd">public</span> <span class="kwrd">bool</span> CanApplyForLoan()
    {
        var canApplyForLoan = isQualifiedForLoan.
                               And(salaryIsQualified.
                               And(ageIsLessthanEighty));

        <span class="kwrd">return</span> canApplyForLoan.IsSatisfiedBy(<span class="kwrd">this</span>);
    }
}</pre>
<p>You can see how our applicant business object encapsulates the business logic but have a nice separation of concern with these specifications. Also you might have noticed that the method chaining is done through a <a href="http://en.wikipedia.org/wiki/Fluent_interface" title="Fluent interface" target="_blank">fluent interface</a>.The whole condition can be read as <strong><em>&#8220;Is Qualified for Loan and Salary is qualitified and Age is less than Eighty&#8221;</em></strong>.</p>
<p>Lets see how we will invoke our applicant class from outside and I know I should have written a unit test, but hey its a blog post and sometimes even I feel lazy <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .</p>
<pre class="csharpcode"><span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
{
    var applicant = <span class="kwrd">new</span> Applicant()
                        {
                            Salary = 150000,
                            Age = 25,
                            CreditRating = 10,
                            TotalEquity = 55000
                        };

    Console.WriteLine(<span class="str">&quot;Can apply for loan:{0}&quot;</span>,applicant.CanApplyForLoan());
    Console.ReadKey();
}</pre>
<p>And when we run the program we get a true result as this applicant instance does satisfy all the conditions.I encourage you to get a full depth of this concept  and try experiment with other Specification like the &#8220;Or&#8221; and &#8220;Not&#8221;. If you have any problem understanding or chaining other specification please feel to get in touch with me.</p>
<p>Last but not the least if you are designing any layered application/core framework for your application,it will be great if you can provide a nice fluent interface to other programmers.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1046/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1046/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1046/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1046/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1046/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1046/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1046/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1046/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1046/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1046/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1046/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1046/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1046/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1046/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1046&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/06/05/composite-pattern/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/06/composite-pattern.png" medium="image">
			<media:title type="html">Composite Pattern</media:title>
		</media:content>
	</item>
		<item>
		<title>Debugger Canvas</title>
		<link>http://prashantbrall.wordpress.com/2011/05/26/debugger-canvas/</link>
		<comments>http://prashantbrall.wordpress.com/2011/05/26/debugger-canvas/#comments</comments>
		<pubDate>Thu, 26 May 2011 20:56:13 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[Debugger Canvas]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Productivity Tools]]></category>
		<category><![CDATA[VS 2010 Plugin]]></category>
		<category><![CDATA[VS Tools]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1034</guid>
		<description><![CDATA[I am really excited to post about this new tool called Debugger Canvas which adds an awesome visual experience to your debugging. Here is a quick video demo and it is planned to be shipped around June. For more information please visit the Microsoft Research website.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1034&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I am really excited to post about this new tool called <a href="http://research.microsoft.com/en-us/projects/debuggercanvas/" title="Debugger Canvas" target="_blank">Debugger Canvas</a> which adds an awesome visual experience to your debugging.</p>
<p>Here is a quick video demo and it is planned to be shipped around June.</p>
<p><a href="http://www.youtube.com/watch?v=3p9XUwIlhJg" target="_blank"><img src="http://prashantbrall.files.wordpress.com/2011/05/debugger-canvas.png?w=600" alt="Debugger Canvas" class="code-box" style="width:80%;" /></a></p>
<p>For more information please visit the <a href="http://research.microsoft.com/en-us/projects/debuggercanvas/" title="Debugger Canvas" target="_blank">Microsoft Research </a>website.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1034/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1034/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1034/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1034&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/05/26/debugger-canvas/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/05/debugger-canvas.png" medium="image">
			<media:title type="html">Debugger Canvas</media:title>
		</media:content>
	</item>
		<item>
		<title>Specification Pattern</title>
		<link>http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/</link>
		<comments>http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/#comments</comments>
		<pubDate>Sun, 22 May 2011 20:56:40 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[SOLID]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Interface seggregation]]></category>
		<category><![CDATA[Separation Of Concerns]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=1000</guid>
		<description><![CDATA[In this post I am going to show you what is a specification pattern and you will see how this pattern is so simple but yet so powerful and useful. This pattern is not part of the Gang of Four Pattern and was proposed by Martin Fowler and Eric Evans. The paper can be found [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1000&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I am going to show you what is a specification pattern and you will see how this pattern is so simple but yet so powerful and useful. This pattern is not part of the<a href="http://en.wikipedia.org/wiki/Gang_of_Four_%28software%29" title="Gang of Four" target="_blank"> Gang of Four Pattern</a> and was proposed by Martin Fowler and Eric Evans. The paper can be found  <a href="http://www.martinfowler.com/apsupp/spec.pdf" title="Martin Fowler" target="_blank">here</a> and I recommend to read it as the entire website is a great source of design patterns .</p>
<p>Anyway this is statement that <a href="http://www.martinfowler.com" target="_blank">Martin Fowler</a> and <a href="http://domaindrivendesign.org/" target="_blank">Eric Evans</a> stated in the paper.</p>
<div class="quote-box">
<div class="quote-line"><i>The central idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched against. As well as its usefulness in selection, it is also valuable for validation and for building to order.</i>
</div>
</div>
<p>Yes I agree that statement is too abstract and I need to show some code before we enter into the world of specification pattern.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> ISpecification
{
    <span class="kwrd">bool</span> IsSatisfiedBy(<span class="kwrd">object</span> candidate);
}</pre>
<p>Aha so this is a simple interface which talks about how a candidate(entity) can be plugged in and the class which implements this interface will specify the satisfying condition for that candidate(entity).</p>
<p>This is again a good example of <a href="http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29" title="SOLID Programming" target="_blank">SOLID programming</a> as we are seeing Interface, <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" title="Separation Of Concerns" target="_blank">Separation of Concern</a> and <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="SRP" target="_blank">Single Responsibility Principle</a> hmmm so far so good lets dig deeper.</p>
<p>Suppose you are building a loan approval application and the business rules states that <em><u>a customer can apply for loan if a customer has good credit rating and have an equity more than $ 45,000</u></em>. </p>
<p>Generally when we start writing a code in a hurry or not using good design principles we will be tempted either to put this business rule directly in our UI layer or in the Applicant entity. With out thinking that very soon this simple <strong>&#8220;if else&#8221;</strong> logic can grow complex and will have a code smell in which ever place we write, as there is no separation of concern and both the class(either UI or Entity ) will have more than one reason to change if had to change the business rules.</p>
<p>Now we know what the problem is and lets apply the pattern in practice to simplify the problem.So I will use the interface signature and use some generics to make it more sophisticated.<br />
<strong><br />
<u>ISpecification.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">interface</span> ISpecification&lt;T&gt;
{
    <span class="kwrd">bool</span> IsSatisfiedBy(T candidate);
}</pre>
<p>As you can see using generics makes this interface much reusable and can be used for any class.Lets implement the specification class first</p>
<p><strong><u>ApplicantLoanSpecification.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> ApplicantLoanSpecification : ISpecification&lt;Applicant&gt;
{
    <span class="kwrd">public</span> <span class="kwrd">bool</span> IsSatisfiedBy(Applicant candidate)
    {
        <span class="kwrd">return</span> (candidate.CreditRating == 10 &amp;&amp; candidate.TotalEquity &gt; 45000);
    }
}</pre>
<p>As you can see now we have a nice separation of concern and we have wrapped the condition logic(specification) into its own class.</p>
<p><strong><u>Application.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">class</span> Applicant
{
    <span class="kwrd">public</span> Int32 Id { get; set; }
    <span class="kwrd">public</span> Int32 Age { get; set; }
    <span class="kwrd">public</span> Int32 CreditRating { get; set; }
    <span class="kwrd">public</span> <span class="kwrd">decimal</span> TotalEquity { get; set; }
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ApplicantLoanSpecification isQualitifiedForloan;

    <span class="kwrd">public</span> Applicant()
    {
        isQualitifiedForloan = <span class="kwrd">new</span> ApplicantLoanSpecification();
    }
    <span class="kwrd">public</span> <span class="kwrd">bool</span> CanApplyForLoan()
    {
        <span class="kwrd">return</span> isQualitifiedForloan.IsSatisfiedBy(<span class="kwrd">this</span>);
    }
}</pre>
<p>This is how the class diagrams looks like.</p>
<p><img class="code-box" src="http://prashantbrall.files.wordpress.com/2011/05/specification-pattern-applicant-class-diagram.png?w=600" alt="Specification Pattern - Applicant Class Diagram" style="width:90%;" /></p>
<p>As you can see the Applicant Entity just invokes the Loan Specification class and calls <strong>IsSatisfiedBy </strong>method now our Applicant class has just one responsibility and we are not coding the &#8220;if else&#8221; logic inside this class.</p>
<p>If in the future we need to change the business rule we will be changing the ApplicantLoanSpecification class and build the complex logic inside the class.Rest of  the method signature (the contract) and the implementation remains the same and it also promotes less code smell, clean code and unit testing.</p>
<p>In the next post I&#8217;ll talk about Composition Pattern which will help us combine and chain specification pattern into a compound specification so that we can build complex business rules with out polluting the code and promote the practice of writing <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1306096974&amp;sr=1-1" title="Clean Code" target="_blank">&#8220;Clean Code&#8221;</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/1000/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/1000/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/1000/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/1000/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/1000/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/1000/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/1000/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/1000/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/1000/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/1000/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/1000/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/1000/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/1000/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/1000/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=1000&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/05/22/specification-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>

		<media:content url="http://prashantbrall.files.wordpress.com/2011/05/specification-pattern-applicant-class-diagram.png" medium="image">
			<media:title type="html">Specification Pattern - Applicant Class Diagram</media:title>
		</media:content>
	</item>
		<item>
		<title>EF Code First:Executing Stored Procedure</title>
		<link>http://prashantbrall.wordpress.com/2011/05/10/ef-code-firstexecuting-stored-procedure/</link>
		<comments>http://prashantbrall.wordpress.com/2011/05/10/ef-code-firstexecuting-stored-procedure/#comments</comments>
		<pubDate>Tue, 10 May 2011 07:29:13 +0000</pubDate>
		<dc:creator>prashantbrall</dc:creator>
				<category><![CDATA[dotnet 4]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[EF]]></category>
		<category><![CDATA[EF Code First]]></category>
		<category><![CDATA[Entity framework]]></category>
		<category><![CDATA[Entity Framework 4.1]]></category>
		<category><![CDATA[Entity framework and POCO]]></category>
		<category><![CDATA[POCO]]></category>

		<guid isPermaLink="false">http://prashantbrall.wordpress.com/?p=995</guid>
		<description><![CDATA[In this post I am going to show you how to use stored procedure with Entity Framework 4.1 even though it is official that Entity Framework 4.1 doesn&#8217;t support stored procedure and this was announced by the ADO.NET team at the time of the release. What it means that you can&#8217;t write stored procedure which [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=995&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I am going to show you how to use stored procedure with Entity Framework 4.1 even though it is official that Entity Framework 4.1 doesn&#8217;t support stored procedure and this was announced by the ADO.NET team at the time of the release. What it means that you can&#8217;t write stored procedure which return different data structure other than your entity wrapped in with DbSet and currently there is no way to map it a different entity which is not a database table.</p>
<p>Anyway without going into much details that why this feature didn&#8217;t make it to its first release, lets focus on how we can execute stored procedure which maps to a table.</p>
<p>I recommend you read my <a href="http://prashantbrall.wordpress.com/2011/05/05/ef-code-firstrunning-sql-scripts/" title="Running sql scripts" target="_blank">previous post</a> which explains the idea behind POCOContextScript class, so we will add 2 more constants which has the DML for the stored procedures. </p>
<p><strong><u>POCOContextScript.cs</u></strong></p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> POCOContextScript
{
   <span class="kwrd">public</span> <span class="kwrd">const</span> <span class="kwrd">string</span> CreateProcGetAllProducts
      = <span class="str">@"create procedure [dbo].[GetAllProducts]
            as
            begin
                set nocount on;
                select * from product
            end"</span>;

   <span class="kwrd">public</span> <span class="kwrd">const</span> <span class="kwrd">string</span> CreateProcGetProductById
      = <span class="str">@"create procedure [dbo].[GetByProductId]
             @productid int
           as
           begin
               set nocount on;
               select * from product p
               where p.id = @productid
           end"</span>;
}</pre>
<p>Nothing special just 2 sql procedure statement to get all products and get a specific product by id. Now we will follow the way we used in the <a href="http://prashantbrall.wordpress.com/2011/05/05/ef-code-firstrunning-sql-scripts/" title="EF Code First:Running SQL Scripts" target="_blank">previous post</a> we can hook this into a class which implements the <a href="http://prashantbrall.wordpress.com/2011/05/05/ef-code-firstrunning-sql-scripts/" title="EF Code First:Running SQL Scripts" target="_blank">IDatabaseInitializer</a> interface and lets run a unit test to see how we can invoke them.<br />
<strong><br />
<u>GetAllProduct</u></strong></p>
<pre class="csharpcode">
[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> Should_be_able_to_execute_sql()
{
   var context = <span class="kwrd">new</span> POCOContext();
   var result = context.Product.SqlQuery(<span class="str">"GetAllProducts"</span>).ToList();
   Assert.IsTrue(result.Count &gt; 0);
}</pre>
<p><strong><br />
<u>GetByProductId</u></strong><br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> Should_be_able_to_get_product_by_id()
{
   var context = <span class="kwrd">new</span> POCOContext();
   var parameter = <span class="kwrd">new</span> SqlParameter
   {
      DbType = DbType.Int32,
      ParameterName = <span class="str">"ProductId"</span>,
      Value = 1
   };

   var result = context.Product.SqlQuery
                                (<span class="str">"GetByProductId @ProductId"</span>,
                                   parameter
                                ).FirstOrDefault();

   Assert.AreEqual(1, result.Id);
}</pre>
<p>That&#8217;s it for now and I hope the ADO.Net team is working on this feature for the next release and along with bulk copy and other features the next version will be even better.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/prashantbrall.wordpress.com/995/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/prashantbrall.wordpress.com/995/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/prashantbrall.wordpress.com/995/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/prashantbrall.wordpress.com/995/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/prashantbrall.wordpress.com/995/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/prashantbrall.wordpress.com/995/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/prashantbrall.wordpress.com/995/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/prashantbrall.wordpress.com/995/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/prashantbrall.wordpress.com/995/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/prashantbrall.wordpress.com/995/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/prashantbrall.wordpress.com/995/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/prashantbrall.wordpress.com/995/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/prashantbrall.wordpress.com/995/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/prashantbrall.wordpress.com/995/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=prashantbrall.wordpress.com&amp;blog=13983672&amp;post=995&amp;subd=prashantbrall&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://prashantbrall.wordpress.com/2011/05/10/ef-code-firstexecuting-stored-procedure/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/eb280c8942c401fbe70e383edb3fd950?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">prashantbrall</media:title>
		</media:content>
	</item>
	</channel>
</rss>
