<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2enclosuresfull.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Jorge Fioranelli</title><link>http://blog.jorgef.net/</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/jorgef" /><description></description><language>en</language><managingEditor>noreply@blogger.com (Jorge Fioranelli)</managingEditor><lastBuildDate>Thu, 16 Feb 2012 19:24:07 PST</lastBuildDate><generator>Blogger http://www.blogger.com</generator><openSearch:totalResults xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">34</openSearch:totalResults><openSearch:startIndex xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">1</openSearch:startIndex><openSearch:itemsPerPage xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">25</openSearch:itemsPerPage><feedburner:info uri="jorgef" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><itunes:owner><itunes:email>noreply@blogger.com</itunes:email></itunes:owner><itunes:explicit>no</itunes:explicit><itunes:subtitle></itunes:subtitle><feedburner:emailServiceId>jorgef</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item><title>Metrics in Brownfield Applications</title><link>http://feedproxy.google.com/~r/jorgef/~3/5jXIbXVcQrY/metrics-in-brownfield-applications.html</link><category>Brownfield Applications</category><category>Metrics</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Tue, 13 Dec 2011 16:59:20 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-76682941409661822</guid><description>Brownfield applications are everywhere, and as we all know, in most of the cases their codebases are quite messy.&lt;br /&gt;
&lt;br /&gt;
&lt;table&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;&lt;a href="http://www.manning.com/baley/" target="_blank"&gt;&lt;img height="120" src="http://www.manning.com/baley/baley_cover150.jpg" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;During the last weeks, I have been reading a really nice book called "Brownfield Application Development in .Net" (by Kyle Baley and Donald Belcham). If you are currently working in a brownfield project and have the feeling that you could improve your career finding another job, I would recommend you to read this book first. And then, if after reading it you can't improve the application, you can go and find a better job. As they say, "change the environment, or change the environment" :).&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;br /&gt;
Working in a brownfield project means that you have a version of the application running in production, probably a large amount of bugs to fix, some new features to add and a lot of places where the code could be improved.&lt;br /&gt;
&lt;br /&gt;
So now the question is: how can we convince our manager to let us spend some of our time improving the existing code instead of adding new features?&lt;br /&gt;
&lt;br /&gt;
Certainly that is not an easy task, but here there are some good reasons to do it:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Experienced developers don't want to touch messy codebases, so your manager will end up having a lot of junior developers and staff turnover.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Changing existing features or adding new ones is easier when the codebase is clean (and probably the amount of time required is less).&amp;nbsp;&lt;/li&gt;
&lt;li&gt;When developers are proud of the codebase, they are more committed with the quality and don't let anyone to mess it up.&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
So, how do metrics can help to achieve this? Well, managers love numbers, if they see numbers, they can&amp;nbsp;measure&amp;nbsp;progress, they can show graphs to their bosses and they can understand (or at least try to) how the application is improved.&lt;br /&gt;
&lt;br /&gt;
Here you have a list of metrics that can be useful in a brownfield application (for more details, see chapter 5 of the book):&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;b&gt;&lt;i&gt;Code Coverage&lt;/i&gt;&lt;/b&gt;: percentage of the code that is covered by tests.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;i&gt;Cyclomatic Complexity&lt;/i&gt;&lt;/b&gt;: how complex is the application,&amp;nbsp;measuring&amp;nbsp;the numbers of paths in the code (if, loops).&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;i&gt;Class Coupling&lt;/i&gt;&lt;/b&gt;: how dependent are the classes on other classes (there are two types: afferent and efferent).&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;i&gt;Cohesion&lt;/i&gt;&lt;/b&gt;: how strongly-related are functions and&amp;nbsp;responsibilities.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;i&gt;Distance form the main sequence&lt;/i&gt;&lt;/b&gt;: using abstractness and instability determines which classes are in the zone of pain and which ones are in the zone of uselessness.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;i&gt;Depth of inheritance&lt;/i&gt;&lt;/b&gt;: how many levels of inheritance the classes have.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;i&gt;Maintainability Index&lt;/i&gt;&lt;/b&gt;: using complexity and lines of code determines &amp;nbsp;how maintainable the code is.&amp;nbsp;
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;
&lt;img border="0" height="249" src="http://2.bp.blogspot.com/-VRbRpHRaKHo/TuaDul-9GZI/AAAAAAAAAQA/ZKkJztXAG_Y/s320/distancefrommainsequence.png" width="320" /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
Selecting and&amp;nbsp;measuring&amp;nbsp;some of these metrics will help you to understand which are the pain points and will allow you to show your manager the improvements the team has done.&lt;br /&gt;
&lt;br /&gt;
For more information about metrics you can check &lt;a href="http://www.hanselman.com/blog/ExitingTheZoneOfPainStaticAnalysisWithNDepend.aspx"&gt;this post&lt;/a&gt;&amp;nbsp;of Scott Hanselman and &lt;a href="http://files.jorgef.net/slides/NDependmetricsplacemats1.1.pdf"&gt;this document&lt;/a&gt; about NDepend metrics.&lt;br /&gt;
&lt;br /&gt;
As a final thought, just a warning, metrics are just that: metrics. They should be applied with common sense. Be careful managing the manager's expectations and be sure that the entire team agrees with them.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-76682941409661822?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/5jXIbXVcQrY" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-14T11:59:20.726+11:00</app:edited><media:thumbnail url="http://2.bp.blogspot.com/-VRbRpHRaKHo/TuaDul-9GZI/AAAAAAAAAQA/ZKkJztXAG_Y/s72-c/distancefrommainsequence.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2011/12/metrics-in-brownfield-applications.html</feedburner:origLink></item><item><title>MsmqException (0xC00E0051) 60 seconds after a WCF Service is executed</title><link>http://feedproxy.google.com/~r/jorgef/~3/GNarPo96LM0/msmqexception.html</link><category>.Net 4.0</category><category>Msmq</category><category>WCF</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Wed, 20 Jul 2011 21:26:53 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-7558820355803835544</guid><description>&lt;table border="0" cellpadding="2" cellspacing="2" style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; border-right: #aaaaaa 1px solid; border-top: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; margin-right: auto;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td valign="top"&gt;I know that this is the type of posts that only few people will find interesting.&lt;br /&gt;
But so many times I googled about some weird exception message, found that another developer wrote about it and saved me hours of work, that now, after spending several days trying to solve this issue, I feel an obligation to post about it.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Symptoms&lt;/h2&gt;&lt;br /&gt;
When using NetMsmqBinding with a transactional queue and a Service is exposed with more than one Endpoint (two o more svc files with the same service type defined in the markup),  a MsmqException is sometimes thrown just 60 seconds after the message is processed.&lt;br /&gt;
&lt;br /&gt;
MyService1.svc&lt;br /&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;%@ServiceHost language="c#" Debug="true" Service="Service" %&amp;gt;&lt;/pre&gt;&lt;br /&gt;
MyService2.svc&lt;br /&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;%@ServiceHost language="c#" Debug="true" Service="Service" %&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Web.config&lt;br /&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;service name="Service"&amp;gt;
  &amp;lt;endpoint contract="IService1" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service1.svc" /&amp;gt;
  &amp;lt;endpoint contract="IService2" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service2.svc" /&amp;gt;
&amp;lt;/service&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Code&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class Service : IService1, IService2 {...}
&lt;/pre&gt;&lt;br /&gt;
Exception&lt;br /&gt;
&lt;i&gt;&lt;span class="Apple-style-span" style="color: #444444;"&gt;System.ServiceModel.MsmqException (0xC00E0051): An error occurred while receiving a message from the queue: Unrecognized error -1072824239 (0xc00e0051). Ensure that MSMQ is installed and running. Make sure the queue is available to receive from. at System.ServiceModel.Channels.MsmqInputChannelBase.TryReceive(TimeSpan timeout, Message&amp;amp; message) at System.ServiceModel.Dispatcher.InputChannelBinder.TryReceive(TimeSpan timeout, RequestContext&amp;amp; requestContext) at System.ServiceModel.Dispatcher.ErrorHandlingReceiver.TryReceive(TimeSpan timeout, RequestContext&amp;amp; requestContext)&lt;/span&gt;&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;table border="0" cellpadding="2" cellspacing="2" style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; border-right: #aaaaaa 1px solid; border-top: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; margin-right: auto;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td valign="top"&gt;&lt;b&gt;Note:&lt;/b&gt; You won't see the exception unless you enable the &lt;a href="http://msdn.microsoft.com/en-us/library/ms733025.aspx"&gt;WCF Trace&lt;/a&gt; (system.diagnostics) or add an IErrorHandler.&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Cause&lt;/h2&gt;&lt;br /&gt;
This issue occurs because the SMSvcHost.exe is activating two ServiceHost instances using the *same* endpoint when a new message arrives.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-CfxBL5elm6I/TiZOXM2VIDI/AAAAAAAAAPQ/06qWwoJEYOQ/s1600/wcftrace.png" /&gt;&lt;/div&gt;&lt;br /&gt;
While the first instance receives and process the message, committing the corresponding COM+ transaction,  the second instance creates another COM+ transaction and waits for another incoming message.&lt;br /&gt;
&lt;br /&gt;
After 60 seconds, the second transaction is aborted (COM+ timeout error 0xC00E0051) and the exception is thrown.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Resolution&lt;/h2&gt;&lt;br /&gt;
Instead of creating one Service with two Endpoints, you need to create two separate Services with just one Endpoint each of them.&lt;br /&gt;
&lt;br /&gt;
MyService1.svc&lt;br /&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;%@ServiceHost language="c#" Debug="true" Service="Service1"%&amp;gt;&lt;/pre&gt;&lt;br /&gt;
MyService2.svc&lt;br /&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;%@ServiceHost language="c#" Debug="true" Service="Service2"%&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Web.config&lt;br /&gt;
&lt;pre class="brush: xml;"&gt;&amp;lt;service name="Service1"&amp;gt;
  &amp;lt;endpoint contract="IService1" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service1.svc" /&amp;gt;
&amp;lt;/service&amp;gt;
&amp;lt;service name="Service2"&amp;gt;
  &amp;lt;endpoint contract="IService2" binding="netMsmqBinding" 
    address="net.msmq://localhost/private/MsmqService/Service2.svc" /&amp;gt;
&amp;lt;/service&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Code&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class Service1 : IService1 {...}
public class Service2 : IService2 {...}
&lt;/pre&gt;&lt;br /&gt;
After doing that, only one instance of the ServiceHost is created, so the COM+ timeout exception is not thrown anymore.&lt;br /&gt;
&lt;br /&gt;
&lt;table border="0" cellpadding="2" cellspacing="2" style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; border-right: #aaaaaa 1px solid; border-top: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; margin-right: auto;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td valign="top"&gt;I have created a bug in connect.microsoft.com: &lt;a href="http://connect.microsoft.com/wcf/feedback/details/680020/msmqexception-0xc00e0051-60-seconds-after-a-wcf-service-is-executed"&gt;http://connect.microsoft.com/wcf/feedback/details/680020/msmqexception-0xc00e0051-60-seconds-after-a-wcf-service-is-executed&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Additional Information&lt;/h2&gt;&lt;br /&gt;
When the exception is thrown, sometimes the ServiceHost faults and the SMSvcHost.exe process doesn't call it again.&lt;br /&gt;
&lt;br /&gt;
The following fix seems to solve this issue: &lt;a href="http://support.microsoft.com/kb/2504602"&gt;2504602&lt;/a&gt; (&lt;a href="http://archive.msdn.microsoft.com/KB2504602/Release/ProjectReleases.aspx?ReleaseId=5585"&gt;download&lt;/a&gt;).&lt;br /&gt;
&lt;br /&gt;
Another way to solve this is to attach a handler to the ServiceHost.Faulted event and re-create the ServiceHost every time this happens (for more details see this &lt;a href="http://nerdwords.blogspot.com/2011/02/wcfmsmqnet-40-stops-processing.html"&gt;link&lt;/a&gt;).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-7558820355803835544?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/GNarPo96LM0" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-07-21T14:26:53.378+10:00</app:edited><media:thumbnail url="http://2.bp.blogspot.com/-CfxBL5elm6I/TiZOXM2VIDI/AAAAAAAAAPQ/06qWwoJEYOQ/s72-c/wcftrace.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2011/07/msmqexception.html</feedburner:origLink></item><item><title>Converting any object to dynamic</title><link>http://feedproxy.google.com/~r/jorgef/~3/1DvujX8Bj14/converting-any-object-to-dynamic.html</link><category>dynamic .net4</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Mon, 20 Jun 2011 23:18:26 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-683890669119026873</guid><description>There are some scenarios in which it is useful to convert an already created object to a dynamic one, so then we can take advantage of the Dynamic Language Runtime introduced in .Net 4.0.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-W78WFjreOJA/Tf8V6kEuadI/AAAAAAAAAO4/V-RSeSk5QL4/s400/dynamic.png" /&gt;&lt;/div&gt;&lt;br /&gt;
Two common scenarios where this conversion is useful are:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Passing an anonymous type to another method/object.&lt;/li&gt;
&lt;li&gt;Adding a new property to an existing object.&lt;/li&gt;
&lt;/ul&gt;The following code converts any object to an ExpandoObject reading all the properties of the former and adding them to the latter.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public static class DynamicExtensions
{
    public static dynamic ToDynamic(this object value)
    {
        IDictionary&amp;lt;string, object&amp;gt; expando = new ExpandoObject();

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
            expando.Add(property.Name, property.GetValue(value));

        return expando as ExpandoObject;
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;h3&gt;Using ToDynamic() to pass an anonymous type to another method&lt;/h3&gt;&lt;pre class="brush: csharp;"&gt;IEnumerable&amp;lt;dynamic&amp;gt; goldCustomersWithZipCode = Customers
  .Where(c =&amp;gt; c.Type == CustomerType.Gold)
  .Select(c =&amp;gt; new { c.Id, c.Name, c.Address.ZipCode  }.ToDynamic());

ListCustomersByZipCode(goldCustomersWithZipCode);
&lt;/pre&gt;&lt;br /&gt;
&lt;h3&gt;Using ToDynamic() to add a new property&lt;/h3&gt;&lt;pre class="brush: csharp;"&gt;Customer customer = Customers.First(c =&amp;gt; c.Id == 1);
dynamic customerWithLastPurchase = customer.ToDynamic();
customerWithLastPurchase.LastPurchase = customer.Purchases.Last();

DisplayCustomerSummary(customerWithLastPurchase);&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-683890669119026873?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/1DvujX8Bj14" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-06-21T16:18:26.232+10:00</app:edited><media:thumbnail url="http://2.bp.blogspot.com/-W78WFjreOJA/Tf8V6kEuadI/AAAAAAAAAO4/V-RSeSk5QL4/s72-c/dynamic.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2011/06/converting-any-object-to-dynamic.html</feedburner:origLink></item><item><title>Entity Framework POCO Proxies in Asp.Net MVC</title><link>http://feedproxy.google.com/~r/jorgef/~3/0MO8NTiPKD4/ef-poco-proxies-in-mvc.html</link><category>POCO</category><category>Proxies</category><category>Asp.Net MVC</category><category>Entity Framework</category><category>ModelBinder</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Tue, 17 May 2011 16:22:39 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-7160074685284883706</guid><description>As many of you already know, the asp.net MVC framework has the ability of creating a model instance each time an http post is executed. In the following picture you can see that the component that performs that task is the ModelBinder.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://1.bp.blogspot.com/-l08Wg67d8JY/Ta4Mlk4qvyI/AAAAAAAAAOM/Vwe9NiqzgEA/s400/ModelBinder.png" /&gt;&lt;/div&gt;&lt;br /&gt;
It is also true that the way in which Entity Framework implements "lazy load" on POCOs is replacing the real objects with proxies. So when the context returns an entity from the database, a proxy is returned instead of the real entity (for more information about EF proxies just follow this &lt;a href="http://blogs.msdn.com/b/adonet/archive/2009/12/22/poco-proxies-part-1.aspx"&gt;link&lt;/a&gt;).&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-qWymdD1uiRA/Ta6D6_TEp4I/AAAAAAAAAOk/fy7HLf4RTdQ/s400/Proxies.png" /&gt;&lt;/div&gt;&lt;br /&gt;
But, what if the entity is not created by the context? How can the ModelBinder create a proxy instead of the real entity?&lt;br /&gt;
&lt;br /&gt;
In order to do that, we need to call the Create method of the EF DbSet and it will create the proxy for us. The following snippet shows how:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;var productProxy = modelContext.Products.Create();
&lt;/pre&gt;&lt;br /&gt;
Now let's put this behavior inside our own ModelBinder:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class EntityModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext,
                                          ModelBindingContext bindingContext, 
                                          Type modelType)
    {
        // Get the EF context using an IoC container
        var modelContext = DependencyResolver.Current.GetService&amp;lt;IModelContext&amp;gt;();

        var set = modelContext.Set(modelType);

        if (set != null)
            return set.Create(modelType);

        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://4.bp.blogspot.com/-ipQgxbP17jA/Ta6EbxJMadI/AAAAAAAAAOs/CoZiWHitcOY/s400/MVC-EF.png" /&gt;&lt;/div&gt;&lt;br /&gt;
Finally, we need to configure our new ModelBinder in the Application_Start (Global.asax).&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ...
        ModelBinders.Binders.DefaultBinder = new EntityModelBinder();
    }
}
&lt;/pre&gt;&lt;br /&gt;
So now, we can use the lazy load feature inside our controllers:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class ProductController : Controller
{
    [HttpPost]
    public ActionResult Edit(Product product)
    {
        modelContext.Entry(product).State = EntityState.Modified;

        // Use &amp;quot;lazy load&amp;quot; to get the Category object from the DB
        var threshold = product.Category.PriceThreshold;

        ...
    }
}
&lt;/pre&gt;&lt;br /&gt;
The source code of this sample can be downloaded from this &lt;a href="http://files.jorgef.net/code/EFMVCModelBinder.zip"&gt;link&lt;/a&gt; (MVC v3 + EF v4.1).&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-7160074685284883706?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/0MO8NTiPKD4" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-05-18T09:22:39.594+10:00</app:edited><media:thumbnail url="http://1.bp.blogspot.com/-l08Wg67d8JY/Ta4Mlk4qvyI/AAAAAAAAAOM/Vwe9NiqzgEA/s72-c/ModelBinder.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">4</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/k1Eu2mpkpjk/EFMVCModelBinder.zip" fileSize="2951562" type="application/zip; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>As many of you already know, the asp.net MVC framework has the ability of creating a model instance each time an http post is executed. In the following picture you can see that the component that performs that task is the ModelBinder. It is also true tha</itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary>As many of you already know, the asp.net MVC framework has the ability of creating a model instance each time an http post is executed. In the following picture you can see that the component that performs that task is the ModelBinder. It is also true that the way in which Entity Framework implements "lazy load" on POCOs is replacing the real objects with proxies. So when the context returns an entity from the database, a proxy is returned instead of the real entity (for more information about EF proxies just follow this link). But, what if the entity is not created by the context? How can the ModelBinder create a proxy instead of the real entity? In order to do that, we need to call the Create method of the EF DbSet and it will create the proxy for us. The following snippet shows how: var productProxy = modelContext.Products.Create(); Now let's put this behavior inside our own ModelBinder: public class EntityModelBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { // Get the EF context using an IoC container var modelContext = DependencyResolver.Current.GetService&amp;lt;IModelContext&amp;gt;(); var set = modelContext.Set(modelType); if (set != null) return set.Create(modelType); return base.CreateModel(controllerContext, bindingContext, modelType); } } Finally, we need to configure our new ModelBinder in the Application_Start (Global.asax). public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ... ModelBinders.Binders.DefaultBinder = new EntityModelBinder(); } } So now, we can use the lazy load feature inside our controllers: public class ProductController : Controller { [HttpPost] public ActionResult Edit(Product product) { modelContext.Entry(product).State = EntityState.Modified; // Use &amp;quot;lazy load&amp;quot; to get the Category object from the DB var threshold = product.Category.PriceThreshold; ... } } The source code of this sample can be downloaded from this link (MVC v3 + EF v4.1). &amp;nbsp;</itunes:summary><itunes:keywords>POCO, Proxies, Asp.Net MVC, Entity Framework, ModelBinder</itunes:keywords><feedburner:origLink>http://blog.jorgef.net/2011/04/ef-poco-proxies-in-mvc.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/k1Eu2mpkpjk/EFMVCModelBinder.zip" length="2951562" type="application/zip; charset=UTF-8" /><feedburner:origEnclosureLink>http://files.jorgef.net/code/EFMVCModelBinder.zip</feedburner:origEnclosureLink></item><item><title>N-Tiers using POCOs and Entity Framework - Part Six: Source Code</title><link>http://feedproxy.google.com/~r/jorgef/~3/cvc2tYlvZSI/n-tiers-pocos-ef-6.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 17 Feb 2011 20:49:24 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-8734069402211607736</guid><description>I have finally managed to find some time to publish the source code of the &lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html"&gt;post series&lt;/a&gt; I wrote some months ago (about how to build an n-tier application using Entity Framework and POCOs).&lt;br /&gt;
&lt;br /&gt;
As this is a complete solution integrated with an IoC container (in this case, MEF), some of the already published code has changed. I have updated the previous posts so that both the source code and the snippets are synchronized.&lt;br /&gt;
&lt;br /&gt;
You can download the source code from here:&amp;nbsp;&lt;br /&gt;
&lt;a href="http://files.jorgef.net/code/EFNTiers.zip"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-dCny2b3FcjY/TV36LSfxchI/AAAAAAAAANo/ioXVPcEg0Ts/s400/code-icon.png" /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
Hope this helps.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Posts in this series:&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html"&gt;Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html"&gt;Model and Entities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-3.html"&gt;Presentation Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-4.html"&gt;Business Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html"&gt;DataAccess Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Source Code&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-8734069402211607736?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/cvc2tYlvZSI" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-02-18T15:49:24.041+11:00</app:edited><media:thumbnail url="http://2.bp.blogspot.com/-dCny2b3FcjY/TV36LSfxchI/AAAAAAAAANo/ioXVPcEg0Ts/s72-c/code-icon.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/oZtVd2zx0Mk/EFNTiers.zip" fileSize="754483" type="application/zip; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>I have finally managed to find some time to publish the source code of the post series I wrote some months ago (about how to build an n-tier application using Entity Framework and POCOs). As this is a complete solution integrated with an IoC container (in</itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary>I have finally managed to find some time to publish the source code of the post series I wrote some months ago (about how to build an n-tier application using Entity Framework and POCOs). As this is a complete solution integrated with an IoC container (in this case, MEF), some of the already published code has changed. I have updated the previous posts so that both the source code and the snippets are synchronized. You can download the source code from here:&amp;nbsp; Hope this helps. Posts in this series:Architecture Model and Entities Presentation Layer Business Layer DataAccess Layer Source Code </itunes:summary><itunes:keywords>.Net 4.0, Entity Framework</itunes:keywords><feedburner:origLink>http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/oZtVd2zx0Mk/EFNTiers.zip" length="754483" type="application/zip; charset=UTF-8" /><feedburner:origEnclosureLink>http://files.jorgef.net/code/EFNTiers.zip</feedburner:origEnclosureLink></item><item><title>OData validation using DataAnnotations</title><link>http://feedproxy.google.com/~r/jorgef/~3/pbLdMSxdZ3Q/odata-dataannotations.html</link><category>WCF DataServices</category><category>DataAnnotations</category><category>OData</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Wed, 23 Feb 2011 22:07:19 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-7952465307848655558</guid><description>WCF DataServices (&lt;a href="http://www.odata.org/"&gt;OData&lt;/a&gt;) becomes more popular every day. If you need to expose data between different applications or even between different tiers of the same application, it is definitely a really good option.&lt;br /&gt;
&lt;br /&gt;
Unfortunately, one of the missing features of the current version (v4.0) is the validation using &lt;a href="http://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx"&gt;DataAnnotations&lt;/a&gt; (if you want that feature to be implemented in the next version, just vote for it &lt;a href="http://data.uservoice.com/forums/72027-wcf-data-services-feature-suggestions/suggestions/1012623-better-validation-support?ref=title"&gt;here&lt;/a&gt;). In this post I am going to show how to implement this validation using a &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.services.changeinterceptorattribute.aspx"&gt;ChangeInterceptor&lt;/a&gt;. I hope it helps you.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Update&lt;/b&gt; [24 Feb 2011]: OData team is working in a better solution to this scenario, for more details click &lt;a href="http://www.odata.org/blog/2011/2/21/vocabularies"&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://1.bp.blogspot.com/_3OJ07UNFNWY/TS1DVztmIpI/AAAAAAAAAMk/U60QeR9m6l4/s400/ODataValidation.png" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
Here we have a Customer object (POCO) that is mapped in the Entity Framework model:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class Customer
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}&lt;/pre&gt;&lt;br /&gt;
As you can see, the Name property is decorated with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx"&gt;Required&lt;/a&gt; attribute (&lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx"&gt;DataAnnotations&lt;/a&gt;).&lt;br /&gt;
&lt;br /&gt;
In the following code snippet&amp;nbsp;we can see the WCF DataService that is exposing the Customers EntitySet:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class WcfDataService : DataService&amp;lt;DatabaseEntities&amp;gt;
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("Customers", EntitySetRights.All);
        config.DataServiceBehavior.MaxProtocolVersion =
                                          DataServiceProtocolVersion.V2;
    }
}&lt;/pre&gt;&lt;br /&gt;
So far nothing new. The first thing we need to do in order to add the validation logic is to create a &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.services.changeinterceptorattribute.aspx"&gt;ChangeInterceptor&lt;/a&gt; method:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;public class WcfDataService : DataService&amp;lt;DatabaseEntities&amp;gt;
{
    ...

    [ChangeInterceptor("Customers")]
    public void ValidateCustomers(Customer customer, UpdateOperations operation)
    {
       // Validation logic
    }
}&lt;/pre&gt;&lt;br /&gt;
After that, we just need to add the following validation logic:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;[ChangeInterceptor("Customers")]
public void ValidateCustomers(Customer customer, UpdateOperations operation)
{
    // Only validates on inserts and updates
    if (operation != UpdateOperations.Add &amp;&amp; 
        operation != UpdateOperations.Change)
        return;

    // Validation
    var validationContext = new ValidationContext(customer, null, null);
    var result = new List&lt;validationresult&gt;();
    Validator.TryValidateObject(customer, validationContext, result, true);

    if(result.Any())
        throw new DataServiceException(
            result
            .Select(r =&gt; r.ErrorMessage)
            .Aggregate((m1, m2) =&gt; String.Concat(m1, Environment.NewLine, m2)));
}&lt;/pre&gt;&lt;br /&gt;
As you can see I am using the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.aspx"&gt;Validator&lt;/a&gt; class (&lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx"&gt;System.ComponentModel.DataAnnotations&lt;/a&gt; namespace) and I am throwing a &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.services.dataserviceexception.aspx"&gt;DataServiceException&lt;/a&gt; in case the validator finds any error.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Edit:&lt;/b&gt; The last parameter of the TryValidateObject method (validateAllProperties) should be set to true, otherwise it will only validate the [Required] attribute. More about this issue &lt;a href="http://connect.microsoft.com/VisualStudio/feedback/details/605635/missleading-parametername-validateallproperties-in-validator-try-validate-componentemodel-dataannotations"&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
If you are using the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx"&gt;MetadataType&lt;/a&gt; attribute instead of having the DataAnnotation attributes in your POCO, you need to add some&amp;nbsp;additional lines of code in order to support that. Check the attached source code to see how to do it.&lt;br /&gt;
&lt;br /&gt;
Finally, in the client we are going to receive a &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicerequestexception.aspx"&gt;DataServiceRequestException&lt;/a&gt; that will contain the error we sent from the server.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;try
{
    var serviceUri = new Uri("http://localhost:4799/WcfDataService.svc")
    
    var context = new DatabaseEntities(serviceUri);

    var customer = new Customer();

    context.AddToCustomers(customer);

    Console.WriteLine("Calling data service...");

    context.SaveChanges();

    Console.WriteLine("Insert successful");

}
catch (DataServiceRequestException ex)
{
    if(ex.InnerException != null &amp;&amp; ex.InnerException.Message != null)
        Console.WriteLine(ex.InnerException.Message);
    else
        Console.WriteLine(ex.ToString());
}&lt;/pre&gt;&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/_3OJ07UNFNWY/TS1GsCBuLAI/AAAAAAAAAM8/0OGhAJw51uI/s400/ODataValidationResult.png" /&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
As you can see, our original error message is now wrapped inside an xml document (the serialized original exception). If you need to get the original message from there, you can either read the xml or use the code shown by &lt;a href="http://blogs.msdn.com/b/phaniraj/"&gt;Phani Raj&lt;/a&gt;&amp;nbsp;in this &lt;a href="http://blogs.msdn.com/b/phaniraj/archive/2009/11/14/ado-net-data-services-efficient-error-handling-across-application-tiers.aspx"&gt;post&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
To download the source code, just click &lt;a href="http://files.jorgef.net/code/ODataValidation.zip?attredirects=0&amp;d=1"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-7952465307848655558?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/pbLdMSxdZ3Q" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-02-24T17:07:19.252+11:00</app:edited><media:thumbnail url="http://1.bp.blogspot.com/_3OJ07UNFNWY/TS1DVztmIpI/AAAAAAAAAMk/U60QeR9m6l4/s72-c/ODataValidation.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/J6uiMZXCyzQ/ODataValidation.zip" fileSize="445370" type="application/x-zip-compressed; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>WCF DataServices (OData) becomes more popular every day. If you need to expose data between different applications or even between different tiers of the same application, it is definitely a really good option. Unfortunately, one of the missing features o</itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary>WCF DataServices (OData) becomes more popular every day. If you need to expose data between different applications or even between different tiers of the same application, it is definitely a really good option. Unfortunately, one of the missing features of the current version (v4.0) is the validation using DataAnnotations (if you want that feature to be implemented in the next version, just vote for it here). In this post I am going to show how to implement this validation using a ChangeInterceptor. I hope it helps you. Update [24 Feb 2011]: OData team is working in a better solution to this scenario, for more details click here. Here we have a Customer object (POCO) that is mapped in the Entity Framework model: public class Customer { public int Id { get; set; } [Required] public string Name { get; set; } } As you can see, the Name property is decorated with the Required attribute (DataAnnotations). In the following code snippet&amp;nbsp;we can see the WCF DataService that is exposing the Customers EntitySet: public class WcfDataService : DataService&amp;lt;DatabaseEntities&amp;gt; { public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("Customers", EntitySetRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } } So far nothing new. The first thing we need to do in order to add the validation logic is to create a ChangeInterceptor method: public class WcfDataService : DataService&amp;lt;DatabaseEntities&amp;gt; { ... [ChangeInterceptor("Customers")] public void ValidateCustomers(Customer customer, UpdateOperations operation) { // Validation logic } } After that, we just need to add the following validation logic: [ChangeInterceptor("Customers")] public void ValidateCustomers(Customer customer, UpdateOperations operation) { // Only validates on inserts and updates if (operation != UpdateOperations.Add &amp;&amp; operation != UpdateOperations.Change) return; // Validation var validationContext = new ValidationContext(customer, null, null); var result = new List(); Validator.TryValidateObject(customer, validationContext, result, true); if(result.Any()) throw new DataServiceException( result .Select(r = r.ErrorMessage) .Aggregate((m1, m2) = String.Concat(m1, Environment.NewLine, m2))); } As you can see I am using the Validator class (System.ComponentModel.DataAnnotations namespace) and I am throwing a DataServiceException in case the validator finds any error. Edit: The last parameter of the TryValidateObject method (validateAllProperties) should be set to true, otherwise it will only validate the [Required] attribute. More about this issue here. If you are using the MetadataType attribute instead of having the DataAnnotation attributes in your POCO, you need to add some&amp;nbsp;additional lines of code in order to support that. Check the attached source code to see how to do it. Finally, in the client we are going to receive a DataServiceRequestException that will contain the error we sent from the server. try { var serviceUri = new Uri("http://localhost:4799/WcfDataService.svc") var context = new DatabaseEntities(serviceUri); var customer = new Customer(); context.AddToCustomers(customer); Console.WriteLine("Calling data service..."); context.SaveChanges(); Console.WriteLine("Insert successful"); } catch (DataServiceRequestException ex) { if(ex.InnerException != null &amp;&amp; ex.InnerException.Message != null) Console.WriteLine(ex.InnerException.Message); else Console.WriteLine(ex.ToString()); } As you can see, our original error message is now wrapped inside an xml document (the serialized original exception). If you need to get the original message from there, you can either read the xml or use the code shown by Phani Raj&amp;nbsp;in this post. To download the source code, just click here.</itunes:summary><itunes:keywords>WCF DataServices, DataAnnotations, OData</itunes:keywords><feedburner:origLink>http://blog.jorgef.net/2011/01/odata-dataannotations.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/J6uiMZXCyzQ/ODataValidation.zip" length="445370" type="application/x-zip-compressed; charset=UTF-8" /><feedburner:origEnclosureLink>http://files.jorgef.net/code/ODataValidation.zip?attredirects=0&amp;d=1</feedburner:origEnclosureLink></item><item><title>Soft-Delete and Entity Framework</title><link>http://feedproxy.google.com/~r/jorgef/~3/1SNknIMz3WE/ef-soft-delete.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Mon, 13 Dec 2010 20:15:37 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-8797322292049844692</guid><description>It is very common to find enterprise applications where entities shouldn't be removed from the database, but just "marked" as deleted. If you are using Entity Framework, you can use the following approach. I hope this post helps you!&lt;br /&gt;&lt;br /&gt;Firstly, we need to identify which entities are the ones that should support the soft-delete behavior. In order to do that we can use the following interface:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: csharp;"&gt;public interface ISoftDeleteEntity&lt;br /&gt;{&lt;br /&gt;    bool Deleted { get; set; }&lt;br /&gt;}&lt;/pre&gt;We can use partial classes in order to implement the interface, so there is no need to modify the auto-generated classes.&lt;br /&gt;&lt;br /&gt;&lt;img style="TEXT-ALIGN: center; MARGIN: 0px auto 10px; WIDTH: 150px; DISPLAY: block; HEIGHT: 159px" id="BLOGGER_PHOTO_ID_5549644565989574690" border="0" alt="" src="http://3.bp.blogspot.com/_3OJ07UNFNWY/TQRMVFl8SCI/AAAAAAAAAL0/Kpo6M40oHJE/s400/Customer.png" /&gt;&lt;br /&gt;&lt;pre class="brush: csharp;"&gt;public partial class Customer : ISoftDeleteEntity&lt;br /&gt;{&lt;br /&gt;}&lt;/pre&gt;Finally, we need to override the SaveChanges of the ObjectContext in order to get the deleted entities and run the soft-delete logic.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: csharp;"&gt;public partial class DatabaseEntities&lt;br /&gt;{&lt;br /&gt;    public override int SaveChanges(SaveOptions options)&lt;br /&gt;    {&lt;br /&gt;        var deletedEntities = GetDeletedEntities();&lt;br /&gt;&lt;br /&gt;        SoftDelete(deletedEntities);&lt;br /&gt;&lt;br /&gt;        return base.SaveChanges(options);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private List&amp;lt;ISoftDeleteEntity&amp;gt; GetDeletedEntities()&lt;br /&gt;    {&lt;br /&gt;        return ObjectStateManager&lt;br /&gt;            .GetObjectStateEntries(EntityState.Deleted)&lt;br /&gt;            .Select(entry =&amp;gt; entry.Entity)&lt;br /&gt;            .OfType&amp;lt;ISoftDeleteEntity&amp;gt;()&lt;br /&gt;            .ToList();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void SoftDelete(List&amp;lt;ISoftDeleteEntity&amp;gt; deletedEntities)&lt;br /&gt;    {&lt;br /&gt;        deletedEntities.ForEach(e =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            ObjectStateManager.ChangeObjectState(e, EntityState.Modified);&lt;br /&gt;            e.Deleted = true;&lt;br /&gt;        });&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;As you can see in the code snippet, first of all we are obtaining all the entities that are going to be deleted and that implement the ISoftDeleteEntity interface. After that, we are changing their state to &lt;b&gt;modified&lt;/b&gt; and setting the Deleted property.&lt;br /&gt;&lt;br /&gt;&lt;table style="BORDER-BOTTOM: #aaaaaa 1px solid; BORDER-LEFT: #aaaaaa 1px solid; DISPLAY: block; FLOAT: none; MARGIN-LEFT: auto; BORDER-TOP: #aaaaaa 1px solid; MARGIN-RIGHT: auto; BORDER-RIGHT: #aaaaaa 1px solid" border="0" cellspacing="2" cellpadding="2" width="90%"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;b&gt;Note:&lt;/b&gt; If the changes were not detected yet (WCF DataServices scenario), you should call the DetectChanges method before obtaining the deleted entities. The attached source code shows how to do it.&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;You can download the sample code from &lt;a href="http://files.jorgef.com.ar/code/EFSoftDelete.zip"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-8797322292049844692?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/1SNknIMz3WE" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2010-12-14T15:15:37.397+11:00</app:edited><media:thumbnail url="http://3.bp.blogspot.com/_3OJ07UNFNWY/TQRMVFl8SCI/AAAAAAAAAL0/Kpo6M40oHJE/s72-c/Customer.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">9</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/FNqXju5IOSc/EFSoftDelete.zip" fileSize="32349" type="application/x-zip-compressed; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>It is very common to find enterprise applications where entities shouldn't be removed from the database, but just "marked" as deleted. If you are using Entity Framework, you can use the following approach. I hope this post helps you! Firstly, we need to i</itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary>It is very common to find enterprise applications where entities shouldn't be removed from the database, but just "marked" as deleted. If you are using Entity Framework, you can use the following approach. I hope this post helps you! Firstly, we need to identify which entities are the ones that should support the soft-delete behavior. In order to do that we can use the following interface: public interface ISoftDeleteEntity { bool Deleted { get; set; } }We can use partial classes in order to implement the interface, so there is no need to modify the auto-generated classes. public partial class Customer : ISoftDeleteEntity { }Finally, we need to override the SaveChanges of the ObjectContext in order to get the deleted entities and run the soft-delete logic. public partial class DatabaseEntities { public override int SaveChanges(SaveOptions options) { var deletedEntities = GetDeletedEntities(); SoftDelete(deletedEntities); return base.SaveChanges(options); } private List&amp;lt;ISoftDeleteEntity&amp;gt; GetDeletedEntities() { return ObjectStateManager .GetObjectStateEntries(EntityState.Deleted) .Select(entry =&amp;gt; entry.Entity) .OfType&amp;lt;ISoftDeleteEntity&amp;gt;() .ToList(); } private void SoftDelete(List&amp;lt;ISoftDeleteEntity&amp;gt; deletedEntities) { deletedEntities.ForEach(e =&amp;gt; { ObjectStateManager.ChangeObjectState(e, EntityState.Modified); e.Deleted = true; }); } }As you can see in the code snippet, first of all we are obtaining all the entities that are going to be deleted and that implement the ISoftDeleteEntity interface. After that, we are changing their state to modified and setting the Deleted property. Note: If the changes were not detected yet (WCF DataServices scenario), you should call the DetectChanges method before obtaining the deleted entities. The attached source code shows how to do it. You can download the sample code from here.</itunes:summary><itunes:keywords>.Net 4.0, Entity Framework</itunes:keywords><feedburner:origLink>http://blog.jorgef.net/2010/12/ef-soft-delete.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/FNqXju5IOSc/EFSoftDelete.zip" length="32349" type="application/x-zip-compressed; charset=UTF-8" /><feedburner:origEnclosureLink>http://files.jorgef.com.ar/code/EFSoftDelete.zip</feedburner:origEnclosureLink></item><item><title>Entity Framework at Alt.Net Hispano</title><link>http://feedproxy.google.com/~r/jorgef/~3/P2VviqblAY4/ef-van.html</link><category>.Net 4.0</category><category>Video</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Tue, 07 Dec 2010 22:07:05 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-2795849586351993887</guid><description>On 17th November I had the pleasure of participating as speaker in a virtual alt.net meeting (VAN) about Entity Framework. The meeting was organized by the &lt;a href="http://altnethispano.org/"&gt;alt.net hispano community&lt;/a&gt; (spanish language).&lt;br /&gt;&lt;br /&gt;The video of the meeting (in spanish language) can be downloaded from here: &lt;a href="http://content.screencast.com/users/AltNetHispano/folders/VAN/media/ab791542-b438-46a9-9fe9-87cf8279e1b2/van-2010-11-13.flv?downloadOnly=true"&gt;&lt;img src="http://3.bp.blogspot.com/_3OJ07UNFNWY/TP8fkBV5KQI/AAAAAAAAALs/tjvAzkQ4aOA/s1600/video-icon.png" width="30" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The slides and the code can be downloaded from the following links:&lt;br /&gt;- &lt;a href="http://files.jorgef.com.ar/presentations/VANEntityFramework.pptx"&gt;Slides&lt;/a&gt; &lt;br /&gt;- &lt;a href="http://files.jorgef.com.ar/code/DemosVANEF.zip"&gt;Code&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;object id="scPlayer" class="embeddedObject" width="600" height="393" type="application/x-shockwave-flash" data="http://content.screencast.com/users/AltNetHispano/folders/VAN/media/ab791542-b438-46a9-9fe9-87cf8279e1b2/flvplayer.swf"&gt;&lt;param name="movie" value="http://content.screencast.com/users/AltNetHispano/folders/VAN/media/ab791542-b438-46a9-9fe9-87cf8279e1b2/flvplayer.swf" /&gt;&lt;param name="quality" value="high" /&gt;&lt;param name="bgcolor" value="#FFFFFF" /&gt;&lt;param name="flashVars" value="thumb=http://content.screencast.com/users/AltNetHispano/folders/VAN/media/ab791542-b438-46a9-9fe9-87cf8279e1b2/FirstFrame.jpg&amp;containerwidth=600&amp;containerheight=393&amp;content=http://content.screencast.com/users/AltNetHispano/folders/VAN/media/ab791542-b438-46a9-9fe9-87cf8279e1b2/van-2010-11-13.flv&amp;blurover=false" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;param name="scale" value="showall" /&gt;&lt;param name="allowScriptAccess" value="always" /&gt;&lt;param name="base" value="http://content.screencast.com/users/AltNetHispano/folders/VAN/media/ab791542-b438-46a9-9fe9-87cf8279e1b2/"/&gt;  Unable to display content. Adobe Flash is required. &lt;/object&gt;&lt;br /&gt;&lt;br /&gt;I would like to thank &lt;a href="http://www.jorgegamba.com/blog/"&gt;Jorge Gamba&lt;/a&gt; (@jorgegamba) for the organization and &lt;a href="http://fabiomaulo.blogspot.com/"&gt;Fabio Maulo&lt;/a&gt; (@fabiomaulo) for his collaboration.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-2795849586351993887?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/P2VviqblAY4" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2010-12-08T17:07:05.176+11:00</app:edited><media:thumbnail url="http://3.bp.blogspot.com/_3OJ07UNFNWY/TP8fkBV5KQI/AAAAAAAAALs/tjvAzkQ4aOA/s72-c/video-icon.png" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/qIR4yX4NoQ4/van-2010-11-13.flv" fileSize="592444017" type="video/x-flv" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>On 17th November I had the pleasure of participating as speaker in a virtual alt.net meeting (VAN) about Entity Framework. The meeting was organized by the alt.net hispano community (spanish language). The video of the meeting (in spanish language) can be</itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary>On 17th November I had the pleasure of participating as speaker in a virtual alt.net meeting (VAN) about Entity Framework. The meeting was organized by the alt.net hispano community (spanish language). The video of the meeting (in spanish language) can be downloaded from here: The slides and the code can be downloaded from the following links: - Slides - Code Unable to display content. Adobe Flash is required. I would like to thank Jorge Gamba (@jorgegamba) for the organization and Fabio Maulo (@fabiomaulo) for his collaboration.</itunes:summary><itunes:keywords>.Net 4.0, Video, Entity Framework</itunes:keywords><feedburner:origLink>http://blog.jorgef.net/2010/12/ef-van.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/qIR4yX4NoQ4/van-2010-11-13.flv" length="592444017" type="video/x-flv" /><feedburner:origEnclosureLink>http://content.screencast.com/users/AltNetHispano/folders/VAN/media/ab791542-b438-46a9-9fe9-87cf8279e1b2/van-2010-11-13.flv?downloadOnly=true</feedburner:origEnclosureLink></item><item><title>N-Tiers using POCOs and Entity Framework - Part Five: DataAccess Layer</title><link>http://feedproxy.google.com/~r/jorgef/~3/JeZgUGb2mYw/n-tiers-pocos-ef-5.html</link><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 17 Feb 2011 20:46:12 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-4333176627904185952</guid><description>&lt;p&gt;&lt;b&gt;Edit: &lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Code&lt;/a&gt; updated&lt;/b&gt;&lt;/p&gt;&lt;p&gt;This layer has the responsibility to manage the database-related operations. It access to the Entity Framework context in order to query, update, add and delete Entities.&lt;/p&gt;&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="DataAccessLayer" border="0" alt="DataAccessLayer" src="http://lh5.ggpht.com/_3OJ07UNFNWY/TKFtWTemZrI/AAAAAAAAALo/bfTav7DegPQ/DataAccessLayer%5B5%5D.png?imgmax=800" width="300" height="296"&gt;&lt;/p&gt;&lt;p&gt;Since the domain objects shouldn’t have access to the EF context, they must call the Repositories to perform all data-related operations. Repositories have the responsibility to manage the entity’s CRUD operations (Create, Read, Update and Delete).&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;namespace Business.Infrastructure.Repositories
{
  public class OrderRepository : IOrderRepository
  {
    private readonly ModelContext context;

    public OrderRepository(ModelContext context)
    {
      this.context = context;
    }

    public Order Get(int id)
    {
      return context.Orders.Include(&amp;quot;Product&amp;quot;)
          .Single(o =&amp;gt; o.Id == id);
    }

    public Order Update(Order order, bool loadOriginal = false)
    {
      if (loadOriginal)
        context.Orders.FirstOrDefault(o =&amp;gt; o.Id == order.Id);

      var updatedOrder = context.Orders.ApplyCurrentValues(order);

      LoadProduct(updatedOrder);
            
      return updatedOrder;
    }

    private void LoadProduct(Order order)
    {
      if(order.Product == null)
        context.LoadProperty(order, o =&amp;gt; o.Product);
    }
    ...
  }
}&lt;/pre&gt;&lt;p&gt;In the above code snippet we can see the Update() method implementation of the OrderRepository. Once this method is called it will apply the new values received from the business layer using the&amp;nbsp; ApplyCurrentValues() that EF provides to update disconnected Entities. Then, after applying these new values, the Repository will load from the database the Product associated to the Order (see note about the Lazy Load EF feature).&lt;br /&gt;
&lt;br /&gt;
The ApplyCurrentValues() method doesn’t persist the domain changes, they are going to be persisted when the Unit Of Work’s Save() method is executed by the Application Service.&lt;br /&gt;
&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;namespace Business.Infrastructure.UnitOfWork
{
  public class ModelContext : ObjectContext, IUnitOfWork
  {
    public ModelContext() 
    : base(&amp;quot;name=ShopEntities&amp;quot;, &amp;quot;ShopEntities&amp;quot;)
    {
      ContextOptions.LazyLoadingEnabled = false;
    }

    private ObjectSet&amp;lt;Product&amp;gt; products;
    public ObjectSet&amp;lt;Product&amp;gt; Products
    {
      get
      {
        return products 
          ?? (products = CreateObjectSet&amp;lt;Product&amp;gt;());
      }
    }

    private ObjectSet&amp;lt;Order&amp;gt; orders;
    public ObjectSet&amp;lt;Order&amp;gt; Orders
    {
      get
      {
        return orders
          ?? (orders = CreateObjectSet&amp;lt;Order&amp;gt;());
      }
    }

    public void Save()
    {
      SaveChanges();
    }
    ...
  }

  public interface IUnitOfWork : IDisposable
  {
    void Save();
  }
}&lt;/pre&gt;&lt;p&gt;Finally, it is important to mention that the EF context should have the LazyLoadingEnabled option set to false. Since the POCOs are accessed from different tiers, the Lazy Load feature shouldn’t be enabled.&lt;/p&gt;&lt;br /&gt;
&lt;table style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; border-top: #aaaaaa 1px solid; margin-right: auto; border-right: #aaaaaa 1px solid" border="0" cellspacing="2" cellpadding="2" width="90%"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td valign="top"&gt;&lt;b&gt;Note:&lt;/b&gt; The Lazy Load EF feature allows us to automatically request associations to the database when their properties are accessed [Fowler, PEAA].&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;p&gt;&lt;br /&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;Developing n-tier applications is not an easy task; most scenarios use customized DTOs and translators in order share data between the tiers. &lt;p&gt;On the other hand, trying to reuse same objects in both tiers usually forces us to put state and behavior in different objects. &lt;br /&gt;
&lt;p&gt;But combining POCOs, extension methods and Entity Framework in an n-tier application we can obtain the following benefits: &lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Entities with state and behavior (properties + extension methods) &lt;br /&gt;
&lt;li&gt;Reuse of Entities in both tiers (as presentation model and business entities) &lt;br /&gt;
&lt;li&gt;No mapping/translation needed&lt;/li&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;/ul&gt;&lt;p&gt;&lt;h2&gt;References:&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;Fowler, PEAA: Fowler, Martin. Patterns of Enterprise Application Architecture, Boston, MA: Addison-Wesley 2003.&lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;&lt;p&gt;&lt;h2&gt;Posts in this series:&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html"&gt;Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html"&gt;Model and Entities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-3.html"&gt;Presentation Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-4.html"&gt;Business Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html"&gt;DataAccess Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Source Code&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-4333176627904185952?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/JeZgUGb2mYw" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-02-18T15:46:12.967+11:00</app:edited><media:thumbnail url="http://lh5.ggpht.com/_3OJ07UNFNWY/TKFtWTemZrI/AAAAAAAAALo/bfTav7DegPQ/s72-c/DataAccessLayer%5B5%5D.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">7</thr:total><feedburner:origLink>http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html</feedburner:origLink></item><item><title>N-Tiers using POCOs and Entity Framework - Part Four: Business Layer</title><link>http://feedproxy.google.com/~r/jorgef/~3/ou9yNBS6Frw/n-tiers-pocos-ef-4.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 17 Feb 2011 20:45:13 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-1247211234953550090</guid><description>&lt;p&gt;&lt;b&gt;Edit: &lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Code&lt;/a&gt; updated&lt;/b&gt;&lt;/p&gt;&lt;p&gt;The business layer will receive the POCO from the presentation layer and it will execute all the business logic applicable, calling the data access layer when it is necessary.&lt;/p&gt;&lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="BusinessLayer" border="0" alt="BusinessLayer" src="http://lh3.ggpht.com/_3OJ07UNFNWY/TJkpReXUnCI/AAAAAAAAALc/wReOpm_wSa8/BusinessLayer_thumb%5B2%5D.png?imgmax=800" width="400" height="189"&gt;&lt;/p&gt;&lt;p&gt;In order to communicate both tiers, the business layer exposes Application Services implemented using Windows Communication Foundation (WCF). These Application Services shouldn’t have any business logic; they have the responsibility to expose business operations to the presentation layer. The only two things that they should do are to call the business domain and to coordinate the Unit of Work pattern in order to persist all entities’ changes in a centralized point per WCF request.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp;"&gt;namespace Business.Application.Services
{
  public class SalesModuleAppService : ISalesModuleAppService
  {
    private readonly IShopDomainService shopDomainService;
    private readonly IUnitOfWork unitOfWork;

    public SalesModuleAppService()
    {
        shopDomainService = // Get IShopDomainService from IoC Container
        unitOfWork = // Get IUnitOfWork from IoC Container
    }

    public void ProcessOrder(Order order)
    {
      shopDomainService.ConfirmOrder(order);

      unitOfWork.Save();
    }
    ...
  }
}&lt;/pre&gt;&lt;br /&gt;
&lt;table style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; border-top: #aaaaaa 1px solid; margin-right: auto; border-right: #aaaaaa 1px solid" border="0" cellSpacing=2 cellPadding=2 width="90%"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td valign="top"&gt;&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Since this example is about updating an existing Order, if the Application Service receives a DTO instead of the Entity, you should retrieve the original Order and then set its properties using the values of the DTO.&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;p&gt;As we can see, the Application Service is calling the ConfirmOrder() method of the Domain Service in order to execute the business logic. This method has the responsibility to coordinate the cancellation of the old order and the confirmation of the new one. In order to do that, it has to obtain the already persisted Order and cancel it, then to apply the new values in the ORM context (using the OrderRepository) and finally to execute the confirmation logic of the new Order.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;namespace Business.Domain.Services
{
  public class ShopDomainService : IShopDomainService
  {
    private readonly IOrderRepository orderRepository;

    public ShopDomainService(IOrderRepository orderRepository)
    {
      this.orderRepository = orderRepository;
    }

    public void ConfirmOrder(Order order)
    {
      if (!order.IsNew())
      {
        var originalOrder = orderRepository.Get(order.Id);
        originalOrder.Cancel();
      }

      var currentOrder = order.IsNew() 
        ? orderRepository.Insert(order) 
        : orderRepository.Update(order);

      currentOrder.Confirm();
    }
    ...
  }
}&lt;/pre&gt;&lt;br /&gt;
&lt;table style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; border-top: #aaaaaa 1px solid; margin-right: auto; border-right: #aaaaaa 1px solid" border="0" cellSpacing=2 cellPadding=2 width="90%"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td valign="top"&gt;&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Domain Services (ShopDomainService) have different purpose than Application Services (SalesModuleAppService). While the first ones are business-oriented, providing stateless business operations, the second ones act as boundary to the business layer, exposing its operations to other tiers.&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;br /&gt;
&lt;p&gt;In the following code snippets we can see a partial implementation of the extension methods applicable to the Order and the Product Entities, containing their corresponding business logic.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;namespace Business.Domain.Entities
{
  public static class OrderExtensions
  {
    public static void Confirm(this Order order)
    {
      // Here run the business rules 
      // (e.g. to verify the customer's status)

      order.Product.SubstractStock(order.Quantity);
      ...
    }

    public static void Cancel(this Order order)
    {
      order.Product.RestoreStock(order.Quantity);
      ...
    }
    ...
  }
}&lt;/pre&gt;&lt;pre class="brush: csharp;"&gt;namespace Business.Domain.Entities
{
  public static class ProductExtensions
  {
    public static void SubstractStock(this Product product, int quantity)
    {  
      if(quantity &gt; product.Stock)
        throw new InvalidOperationException("Insufficient stock");

      product.Stock -= quantity;
      ...
    }

    public static void RestoreStock(this Product product, int quantity)
    {
      product.Stock += quantity;
      ...
    }
    ...
  }
}&lt;/pre&gt;&lt;br /&gt;
&lt;h2&gt;References:&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;Evans, DDD: Evans, Eric. Domain-Driven Design: Tackling Complexity in the Heart of Software, Boston, MA: Addison-Wesley 2004.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;h2&gt;Posts in this series:&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html"&gt;Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html"&gt;Model and Entities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-3.html"&gt;Presentation Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-4.html"&gt;Business Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html"&gt;DataAccess Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Source Code&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-1247211234953550090?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/ou9yNBS6Frw" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-02-18T15:45:13.597+11:00</app:edited><media:thumbnail url="http://lh3.ggpht.com/_3OJ07UNFNWY/TJkpReXUnCI/AAAAAAAAALc/wReOpm_wSa8/s72-c/BusinessLayer_thumb%5B2%5D.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-4.html</feedburner:origLink></item><item><title>N-Tiers using POCOs and Entity Framework - Part Three: Presentation Layer</title><link>http://feedproxy.google.com/~r/jorgef/~3/BswGu3bhbRQ/n-tiers-pocos-ef-3.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 17 Feb 2011 20:44:32 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-7811913326598036455</guid><description>&lt;p&gt;&lt;b&gt;Edit: &lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Code&lt;/a&gt; updated&lt;/b&gt;&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;The presentation tier is a web application implemented using ASP.NET MVC. It has the goal of interacting with the user, executing only the logic related to the user interface.&lt;/p&gt;&lt;p&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="PresentationLayer" border="0" alt="PresentationLayer" src="http://lh4.ggpht.com/_3OJ07UNFNWY/TJktIDQKY3I/AAAAAAAAALk/Ajwwp-H7tes/PresentationLayer_thumb%5B2%5D.png?imgmax=800" width="350" height="202"&gt;&lt;/p&gt;&lt;p&gt;In the Model-View-Controller (MVC) pattern, the View has the responsibility to render the model to the user while the Controller has the ability to obtain the user’s input and to process it. &lt;/p&gt;&lt;pre class="brush: xml;"&gt;@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    &amp;lt;fieldset&amp;gt;
        &amp;lt;legend&amp;gt;Order&amp;lt;/legend&amp;gt;

        &amp;lt;div class=&amp;quot;editor-label&amp;quot;&amp;gt;
            @Html.LabelFor(model =&amp;gt; model.Product)
        &amp;lt;/div&amp;gt;
        &amp;lt;div class=&amp;quot;editor-field&amp;quot;&amp;gt;
            @Html.DropDownListFor(model =&amp;gt; model.Product_Id, 
              new SelectList(ViewBag.Products, &amp;quot;Id&amp;quot;, &amp;quot;Description&amp;quot;), 
              &amp;quot;- Select -&amp;quot;)
            @Html.ValidationMessageFor(model =&amp;gt; model.Product_Id)
        &amp;lt;/div&amp;gt;

        &amp;lt;div class=&amp;quot;editor-label&amp;quot;&amp;gt;
            @Html.LabelFor(model =&amp;gt; model.Quantity)
        &amp;lt;/div&amp;gt;
        &amp;lt;div class=&amp;quot;editor-field&amp;quot;&amp;gt;
            @Html.EditorFor(model =&amp;gt; model.Quantity)
            @Html.ValidationMessageFor(model =&amp;gt; model.Quantity)
        &amp;lt;/div&amp;gt;

        &amp;lt;p&amp;gt;
            &amp;lt;input type=&amp;quot;submit&amp;quot; value=&amp;quot;Create&amp;quot; /&amp;gt;
        &amp;lt;/p&amp;gt;
    &amp;lt;/fieldset&amp;gt;
}&lt;/pre&gt;&lt;pre class="brush: csharp;"&gt;namespace Presentation.Controllers
{
  public class OrderController : Controller
  {
    private readonly ISalesModuleAppService salesModuleAppService;

    public OrderController(ISalesModuleAppService salesModuleAppService)
    {
      this.salesModuleAppService = salesModuleAppService;
    }

    [HttpPost]
    public ActionResult Edit(Order order)
    {
      salesModuleAppService.ProcessOrder(order); // WCF Call

      return RedirectToAction(&amp;quot;Index&amp;quot;);
    }
    ...
  }
}&lt;/pre&gt;&lt;p&gt;In the previous code snippet we can see how the Controller is calling the method ProcessOrder() of the of the Application Service (located in the business tier) in order to execute the corresponding business logic. We can also see that the Controller is sending the recently updated Order (POCO) as parameter.&lt;/p&gt;&lt;br /&gt;
&lt;h2&gt;References:&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;Fowler, PEAA: Fowler, Martin. Patterns of Enterprise Application Architecture, Boston, MA: Addison-Wesley 2003.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;h2&gt;Posts in this series:&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html"&gt;Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html"&gt;Model and Entities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-3.html"&gt;Presentation Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-4.html"&gt;Business Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html"&gt;DataAccess Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Source Code&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-7811913326598036455?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/BswGu3bhbRQ" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-02-18T15:44:32.781+11:00</app:edited><media:thumbnail url="http://lh4.ggpht.com/_3OJ07UNFNWY/TJktIDQKY3I/AAAAAAAAALk/Ajwwp-H7tes/s72-c/PresentationLayer_thumb%5B2%5D.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-3.html</feedburner:origLink></item><item><title>N-Tiers using POCOs and Entity Framework - Part Two: Model and Entities</title><link>http://feedproxy.google.com/~r/jorgef/~3/kG1jzAB-6g8/n-tiers-pocos-ef-2.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Mon, 27 Sep 2010 21:29:09 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-1601336511344026018</guid><description>&lt;p&gt;Following Domain Driven Design (DDD) principles [Evans, DDD], the domain should be represented by objects with state and behavior, using a rich object-oriented model. Additionally, in n-tier applications it is ideal to reuse as many objects as you could in order to reduce code duplication.&lt;br&gt;&lt;/p&gt; &lt;p&gt;However, the object’s behavior is usually very different in each tier; for example, in the business tier the behavior is often business-oriented and it shouldn’t be executed in the presentation tier.&lt;br&gt;&lt;/p&gt; &lt;p&gt;To solve this problem, we can use POCOs with only state (properties), and add behavior to them using extension methods in the business tier.&lt;/p&gt; &lt;p&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Model-Entities" border="0" alt="Model-Entities" src="http://lh5.ggpht.com/_3OJ07UNFNWY/TIHuEs0t5NI/AAAAAAAAAKI/0qIlvVfeVVw/ModelEntities10.png?imgmax=800" width="380" height="158"&gt; &lt;/p&gt; &lt;table style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; border-top: #aaaaaa 1px solid; margin-right: auto; border-right: #aaaaaa 1px solid" cellspacing="2" cellpadding="2" width="90%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td valign="top"&gt;&lt;strong&gt;Note&lt;/strong&gt;: Although extension methods provide a good extensibility mechanism, they have some limitations. For example, they don’t support late-bound polymorphism (virtual methods).&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;In the following code snippet we can see the Order and Product POCOs, related each other through the Product and the Product_ID properties.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;namespace Common.Domain.Entities&lt;br /&gt;{&lt;br /&gt;  public class Order&lt;br /&gt;  {&lt;br /&gt;    public int Id { get; set; }&lt;br /&gt;    public Product Product { get; set; }&lt;br /&gt;    public int Product_ID { get; set; }&lt;br /&gt;    public int Quantity { get; set; }&lt;br /&gt;    ...&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public class Product&lt;br /&gt;  {&lt;br /&gt;    public int Id { get; set; }&lt;br /&gt;    public string Description { get; set; }&lt;br /&gt;    public int Stock { get; set; }&lt;br /&gt;    ...&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;table style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; border-top: #aaaaaa 1px solid; margin-right: auto; border-right: #aaaaaa 1px solid" cellspacing="2" cellpadding="2" width="90%"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;strong&gt;Note&lt;/strong&gt;: EF supports two types of associations: Navigation Properties (Product property) and Foreign Key Properties (Product_ID property). While the first ones allow you to “navigate” from one object to the other, the second ones are very useful in “disconnected” scenarios.&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;And as we mentioned before, the behavior of both objects is added using the extension methods defined in the following classes.&lt;/p&gt;&lt;pre class="brush: csharp;"&gt;namespace Business.Domain.Entities&lt;br /&gt;{&lt;br /&gt;  public static class OrderExtensions&lt;br /&gt;  {&lt;br /&gt;    public static void Confirm(this Order order) { ... }&lt;br /&gt;    public static void Cancel(this Order order) { ... }&lt;br /&gt;    ...&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public static class ProductExtensions&lt;br /&gt;  {&lt;br /&gt;    public static void SubstractStock(this Product product) { ... }&lt;br /&gt;    public static void RestoreStock(this Product product) { ... }&lt;br /&gt;    ...&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;This allows us to call the specific domain behavior using the entity instance.&lt;/p&gt;&lt;br /&gt;&lt;pre class="brush: csharp;"&gt;using Common.Domain.Entities;&lt;br /&gt;using Business.Domain.Entities;&lt;br /&gt;...&lt;br /&gt;&lt;br /&gt;order.Confirm();&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;It is also important to mention that there are some scenarios where the entity does not match with the data that should be shown in the presentation layer, e.g. let’s say it is required to show the customer’s name and the description of the latest ten products that he or she ordered. In those cases it could be a better option to create a customized Data Transfer Object (DTO) in order to transfer over the wire only the data needed.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="DTO" border="0" alt="DTO" src="http://lh5.ggpht.com/_3OJ07UNFNWY/TIHuFiJp3EI/AAAAAAAAAKM/wwYsfNNTDjY/DTO%5B5%5D.png?imgmax=800" width="231" height="227"&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;table style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; border-top: #aaaaaa 1px solid; margin-right: auto; border-right: #aaaaaa 1px solid" cellspacing="2" cellpadding="2" width="90%"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td valign="top"&gt;&lt;strong&gt;Note&lt;/strong&gt;: If your architecture must support “cross-process change tracking”, I recommend you to use the “self-tracking entities” EF feature, an excellent feature designed for n-tier applications. Since it increases the amount of data that is sent over the wire, you should use this feature only if it is required.&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;References:&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;Evans, DDD: Evans, Eric. Domain-Driven Design: Tackling Complexity in the Heart of Software, Boston, MA: Addison-Wesley 2004.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;Posts in this series:&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html"&gt;Architecture&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html"&gt;Model and Entities&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-3.html"&gt;Presentation Layer&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-4.html"&gt;Business Layer&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html"&gt;DataAccess Layer&lt;/a&gt;&lt;/li&gt;&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-1601336511344026018?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/kG1jzAB-6g8" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-28T14:29:09.803+10:00</app:edited><media:thumbnail url="http://lh5.ggpht.com/_3OJ07UNFNWY/TIHuEs0t5NI/AAAAAAAAAKI/0qIlvVfeVVw/s72-c/ModelEntities10.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html</feedburner:origLink></item><item><title>N-Tiers using POCOs and Entity Framework - Part One: Architecture</title><link>http://feedproxy.google.com/~r/jorgef/~3/f-TwuSf8NVQ/n-tiers-pocos-ef-1.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 17 Feb 2011 20:42:41 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-6370180792654247813</guid><description>&lt;p&gt;The ADO.NET Entity Framework comes with features like “persistence ignorance” and “POCO support” which allow the use of simple objects as persistent entities and the development of n-tier applications in an easier way. &lt;/p&gt;&lt;p&gt;The purpose of these post series is to show an example of an n-tier application that takes advantage of these features.&lt;/p&gt;&lt;p&gt;In n-tier architectures, each tier can be executed in a different process and potentially in a different server. In fact, every application that uses a database server and an internet browser has at least three tiers, so it could be considered an n-tier application. Nevertheless, in the .NET world it is very common to catalog as n-tier applications those in which the .NET code is separated by at least two processes, generally using technologies such as SOAP Web Services, .NET Remoting or Windows Communication Foundation (WCF).&lt;/p&gt;&lt;p&gt;The example application has the following architecture:&lt;/p&gt;&lt;p&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Architecture" border="0" alt="Architecture" src="http://lh6.ggpht.com/_3OJ07UNFNWY/THj6x0QascI/AAAAAAAAAJk/HjO-BCDq4LA/Architecture%5B16%5D.png?imgmax=800" width="465" height="342"&gt; &lt;/p&gt;&lt;p&gt;The application’s architecture is split into two tiers:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The presentation tier, which has the responsibility to execute the user interface logic using the “Model-View-Controller” (MVC) pattern [Fowler, PEAA].&lt;br /&gt;
&lt;li&gt;The business tier, which contains all the business and data access logic. This tier uses the “Unit of Work” and “Repository” patterns [Fowler, PEAA] combined with an Object Relational Mapper (Entity Framework).&lt;/li&gt;&lt;br /&gt;
&lt;/ul&gt;&lt;p&gt;In this architecture, the Model and the Entities are represented by the Plain Old CLR Objects (POCOs) that are serialized and transported over the wire between both tiers.&lt;/p&gt;&lt;p&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Tiers" border="0" alt="Tiers" src="http://lh4.ggpht.com/_3OJ07UNFNWY/THj6zlnVCUI/AAAAAAAAAJw/ruU4RhcSARo/Tiers%5B6%5D.png?imgmax=800" width="304" height="114"&gt; &lt;/p&gt;&lt;table style="border-bottom: #aaaaaa 1px solid; border-left: #aaaaaa 1px solid; display: block; float: none; margin-left: auto; border-top: #aaaaaa 1px solid; margin-right: auto; border-right: #aaaaaa 1px solid" cellspacing="2" cellpadding="2" width="90%"&gt;&lt;tbody&gt;
&lt;tr&gt; &lt;td valign="top" width="958"&gt;&lt;strong&gt;Note:&lt;/strong&gt; Plain Old CLR Objects (POCOs) are ordinary .NET classes without any infrastructure-related stuff. POCOs don’t have to inherit from a certain base class or to implement a specific interface. They are clean objects with persistence ignorance [Nilsson, ADDDP].&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;h2&gt;&amp;nbsp;&lt;/h2&gt;&lt;h2&gt;References:&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;Fowler, PEAA: Fowler, Martin. Patterns of Enterprise Application Architecture, Boston, MA: Addison-Wesley 2003.&lt;br /&gt;
&lt;li&gt;Nilsson, ADDDP: Nilsson, Jimmy. Applying Domain-Driven Design and Patterns with examples in C# and .NET, Boston, MA: Addison-Wesley 2006. &lt;/li&gt;&lt;br /&gt;
&lt;/ul&gt;
&lt;h2&gt;Posts in this series:&lt;/h2&gt;&lt;ol&gt;&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html"&gt;Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html"&gt;Model and Entities&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-3.html"&gt;Presentation Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-4.html"&gt;Business Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html"&gt;DataAccess Layer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html"&gt;Source Code&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-6370180792654247813?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/f-TwuSf8NVQ" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-02-18T15:42:41.567+11:00</app:edited><media:thumbnail url="http://lh6.ggpht.com/_3OJ07UNFNWY/THj6x0QascI/AAAAAAAAAJk/HjO-BCDq4LA/s72-c/Architecture%5B16%5D.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-1.html</feedburner:origLink></item><item><title>WPF Commands in IronPython</title><link>http://feedproxy.google.com/~r/jorgef/~3/GJvpGD4hl1E/wpf-commands-in-ironpython.html</link><category>WPF</category><category>IronPython</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Tue, 02 Feb 2010 07:25:03 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-3039146601667405881</guid><description>&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/ms752914.aspx"&gt;Dependency Properties&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/library/ms752308.aspx"&gt;Commands&lt;/a&gt; are very useful WPF features.&lt;/p&gt;  &lt;p&gt;In my last &lt;a href="http://blog.jorgef.com.ar/2010/01/wpf-dependency-properties-in-ironpython.html"&gt;post&lt;/a&gt; I wrote about how to use Dependency Properties in IronPython. In this post we will see how to implement and use the WPF RelayCommand (for more details see &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;WPF Apps With The Model-View-ViewModel Design Pattern&lt;/a&gt;).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;import&lt;/font&gt; clr &lt;/p&gt;  &lt;p&gt;clr.AddReference(&lt;font color="#800040"&gt;&amp;quot;WindowsBase&amp;quot;&lt;/font&gt;)     &lt;br /&gt;clr.AddReference(&lt;font color="#800040"&gt;&amp;quot;PresentationCore&amp;quot;&lt;/font&gt;)     &lt;br /&gt;clr.AddReference(&lt;font color="#800040"&gt;&amp;quot;PresentationFramework&amp;quot;&lt;/font&gt;) &lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;from&lt;/font&gt; System &lt;font color="#0000ff"&gt;import&lt;/font&gt; (    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; EventArgs    &lt;br /&gt;)&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;from&lt;/font&gt; System.Windows &lt;font color="#0000ff"&gt;import&lt;/font&gt; (     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; DependencyObject     &lt;br /&gt;) &lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;from&lt;/font&gt; System.Windows.Input &lt;font color="#0000ff"&gt;import&lt;/font&gt; (     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ICommand     &lt;br /&gt;)&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; RelayCommand(ICommand):     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; __init__(self, executeFunction, canExecuteFunction):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._executeFunction = executeFunction     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._canExecuteFunction = canExecuteFunction     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._handlers = []     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; CanExecute(self, parameter):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; self._canExecuteFunction(parameter)     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; add_CanExecuteChanged(self, handler):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._handlers.append(handler)     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; remove_CanExecuteChanged(self, handler):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._handlers.remove(handler)     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; canExecuteChanged(self):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; for handler in self._handlers:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; handler(self, EventArgs.Empty)     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; Execute(self, parameter):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._executeFunction(parameter)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self.canExecuteChanged()&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; Planning(DependencyObject):     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; _sessionProperty = &lt;font color="#0000ff"&gt;None&lt;/font&gt;     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; __new__(cls):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if not&lt;/font&gt; Planning._sessionProperty:     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Planning._sessionProperty = DependencyProperty.Register(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#800040"&gt;&amp;quot;session&amp;quot;&lt;/font&gt;, clr.GetClrType(Session), clr.GetClrType(Planning))&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; DependencyObject.__new__(cls)    &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; __init__(self):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self.loginCommand = RelayCommand(&lt;font color="#0000ff"&gt;lambda&lt;/font&gt; p : self.login(p), &lt;font color="#0000ff"&gt;lambda&lt;/font&gt; p : not self.session)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; login(self, user):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self.session = Session(user)     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; getSession(self):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; self.GetValue(Planning._sessionProperty)     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; setSession(self, value):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self.SetValue(Planning._sessionProperty, value)     &lt;br /&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; session = &lt;font color="#0000ff"&gt;property&lt;/font&gt;(getSession, setSession)&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-3039146601667405881?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/GJvpGD4hl1E" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2010-02-03T02:25:03.169+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2010/02/wpf-commands-in-ironpython.html</feedburner:origLink></item><item><title>WPF Dependency Properties in IronPython</title><link>http://feedproxy.google.com/~r/jorgef/~3/glcRK75oyqE/wpf-dependency-properties-in-ironpython.html</link><category>WPF</category><category>IronPython</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 11 Feb 2010 15:13:32 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-457674772949457302</guid><description>&lt;p&gt;One of the best features added to WPF are &lt;a href="http://msdn.microsoft.com/en-us/library/ms752914.aspx"&gt;Dependency Properties&lt;/a&gt;. Dependency properties use a combination of a property and a static field (a class field in python). &lt;/p&gt;&lt;p&gt;As follows you will find an example:&lt;/p&gt;&lt;p&gt;&lt;span style="color:#0000ff;"&gt;import&lt;/span&gt; clr &lt;/p&gt;&lt;p&gt;clr.AddReference(&lt;span style="color:#800040;"&gt;"WindowsBase"&lt;/span&gt;)&lt;br /&gt;clr.AddReference(&lt;span style="color:#800040;"&gt;"PresentationCore"&lt;/span&gt;)&lt;br /&gt;clr.AddReference(&lt;span style="color:#800040;"&gt;"PresentationFramework"&lt;/span&gt;) &lt;/p&gt;&lt;p&gt;&lt;span style="color:#0000ff;"&gt;from&lt;/span&gt; System.Windows &lt;span style="color:#0000ff;"&gt;import&lt;/span&gt; (&lt;br /&gt;    DependencyObject, DependencyProperty&lt;br /&gt;) &lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;span style="color:#0000ff;"&gt;class&lt;/span&gt; Planning(DependencyObject):&lt;br /&gt;&lt;br /&gt;    _sessionProperty = &lt;span style="color:#0000ff;"&gt;None&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;    &lt;span style="color:#0000ff;"&gt;def&lt;/span&gt; __new__(cls):&lt;br /&gt;       &lt;span style="color:#0000ff;"&gt;if not&lt;/span&gt; Planning._sessionProperty:&lt;br /&gt;            Planning._sessionProperty = DependencyProperty.Register(&lt;br /&gt;                &lt;span style="color:#800040;"&gt;"session"&lt;/span&gt;, clr.GetClrType(Session), clr.GetClrType(Planning))   &lt;br /&gt;        &lt;span style="color:#0000ff;"&gt;return&lt;/span&gt; DependencyObject.__new__(cls)&lt;br /&gt;&lt;br /&gt;    &lt;span style="color:#0000ff;"&gt;def&lt;/span&gt; getSession(self):&lt;br /&gt;        &lt;span style="color:#0000ff;"&gt;return&lt;/span&gt; self.GetValue(Planning._sessionProperty)&lt;br /&gt;&lt;br /&gt;    &lt;span style="color:#0000ff;"&gt;def&lt;/span&gt; setSession(self, value):&lt;br /&gt;        self.SetValue(Planning._sessionProperty, value)&lt;br /&gt;&lt;br /&gt;    session = &lt;span style="color:#0000ff;"&gt;property&lt;/span&gt;(getSession, setSession)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-457674772949457302?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/glcRK75oyqE" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2010-02-12T10:13:32.001+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2010/01/wpf-dependency-properties-in-ironpython.html</feedburner:origLink></item><item><title>Using an IronPython object from C#</title><link>http://feedproxy.google.com/~r/jorgef/~3/twHb-a-CuoI/using-ironpython-object-from-c.html</link><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Sun, 27 Dec 2009 15:26:31 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-1193159843472134836</guid><description>&lt;p&gt;The new keyword “dynamic” added to C# (.Net 4.0) allows you to interoperate with any dynamic language such as IronPython or IronRuby.&lt;/p&gt;  &lt;p&gt;This new feature bypasses any static type checking at compile time, assuming that any operation is allowed. But, if it is not allowed, an error will be showed at run time.&lt;/p&gt;  &lt;p&gt;For example, the following Customer “IronPython Class” is invoked from the C# code as a dynamic object:&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;&lt;strong&gt;IronPython code (Sample.py)&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;font color="#008040"&gt;# Function (method) that creates a new Customer      &lt;br /&gt;&lt;/font&gt;&lt;font color="#0000ff"&gt;def&lt;/font&gt; CreateCustomer(firstName, lastName):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; Customer(firstName, lastName) &lt;/p&gt;  &lt;p&gt;&lt;font color="#008040"&gt;# Customer object &lt;/font&gt;    &lt;br /&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; Customer(object):&amp;#160; &lt;/p&gt;  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008040"&gt;# Initialization (constructor) &lt;/font&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; __init__(&lt;font color="#0000ff"&gt;self&lt;/font&gt;, firstName, lastName):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;self&lt;/font&gt;._firstName = firstName     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;self&lt;/font&gt;._lastName = lastName &lt;/p&gt;  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008040"&gt;# Function (method) that print the customer&lt;/font&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;def&lt;/font&gt; printNames(&lt;font color="#0000ff"&gt;self&lt;/font&gt;):     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;print&lt;/font&gt; &lt;font color="#0000ff"&gt;self&lt;/font&gt;._firstName + ' ' + &lt;font color="#0000ff"&gt;self&lt;/font&gt;._lastName&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;&lt;strong&gt;C# code (Program.cs)&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; Microsoft.Scripting.Hosting;     &lt;br /&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; IronPython.Hosting;&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#408080"&gt;Program&lt;/font&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static void&lt;/font&gt; Main(&lt;font color="#0000ff"&gt;string&lt;/font&gt;[] args)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {&lt;/p&gt;  &lt;p&gt;&lt;font color="#408080"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ScriptRuntime&lt;/font&gt; py = &lt;font color="#408080"&gt;Python&lt;/font&gt;.CreateRuntime();     &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dynamic&lt;/font&gt; sample = py.UseFile(&lt;font color="#800000"&gt;&amp;quot;Sample.py&amp;quot;&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dynamic&lt;/font&gt; customer = sample.CreateCustomer(&lt;font color="#800040"&gt;&amp;quot;Paul&amp;quot;&lt;/font&gt;, &lt;font color="#804040"&gt;&amp;quot;Smith&amp;quot;&lt;/font&gt;);     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; customer.printNames();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;&lt;/p&gt;  &lt;p&gt;You can download the source code &lt;a href="http://files.jorgef.com.ar/code/Dynamic.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-1193159843472134836?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/twHb-a-CuoI" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-12-28T10:26:31.184+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/glGoPWxMGX8/Dynamic.zip" fileSize="1024565" type="application/x-zip-compressed; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle> The new keyword “dynamic” added to C# (.Net 4.0) allows you to interoperate with any dynamic language such as IronPython or IronRuby. This new feature bypasses any static type checking at compile time, assuming that any operation is allowed. But, if it i</itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary> The new keyword “dynamic” added to C# (.Net 4.0) allows you to interoperate with any dynamic language such as IronPython or IronRuby. This new feature bypasses any static type checking at compile time, assuming that any operation is allowed. But, if it is not allowed, an error will be showed at run time. For example, the following Customer “IronPython Class” is invoked from the C# code as a dynamic object: IronPython code (Sample.py) # Function (method) that creates a new Customer def CreateCustomer(firstName, lastName): &amp;#160;&amp;#160;&amp;#160; return Customer(firstName, lastName) # Customer object class Customer(object):&amp;#160; &amp;#160;&amp;#160;&amp;#160; # Initialization (constructor) &amp;#160;&amp;#160;&amp;#160; def __init__(self, firstName, lastName): &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._firstName = firstName &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; self._lastName = lastName &amp;#160;&amp;#160;&amp;#160; # Function (method) that print the customer &amp;#160;&amp;#160;&amp;#160; def printNames(self): &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; print self._firstName + ' ' + self._lastName C# code (Program.cs) using Microsoft.Scripting.Hosting; using IronPython.Hosting; class Program { &amp;#160;&amp;#160;&amp;#160; static void Main(string[] args) &amp;#160;&amp;#160;&amp;#160; { &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ScriptRuntime py = Python.CreateRuntime(); &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dynamic sample = py.UseFile(&amp;quot;Sample.py&amp;quot;); &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; dynamic customer = sample.CreateCustomer(&amp;quot;Paul&amp;quot;, &amp;quot;Smith&amp;quot;); &amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; customer.printNames(); &amp;#160;&amp;#160;&amp;#160; } } You can download the source code here. </itunes:summary><feedburner:origLink>http://blog.jorgef.net/2009/12/using-ironpython-object-from-c.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/glGoPWxMGX8/Dynamic.zip" length="1024565" type="application/x-zip-compressed; charset=UTF-8" /><feedburner:origEnclosureLink>http://files.jorgef.com.ar/code/Dynamic.zip</feedburner:origEnclosureLink></item><item><title>Using PLINQ to improve performance</title><link>http://feedproxy.google.com/~r/jorgef/~3/a9Z4rknRlKo/using-plinq-to-improve-performance.html</link><category>.Net 4.0</category><category>PLINQ</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Tue, 22 Dec 2009 02:45:58 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-6700267504149933497</guid><description>&lt;p&gt;The version 4.0 of .Net has a new feature called “Parallel LINQ” or PLINQ. If you use LINQ to filter or process a large amount of objects in memory and/or it is required a high-cost evaluation, PLINQ is for you.&lt;/p&gt;  &lt;p&gt;PLINQ segments the source in parts and it uses different threads in order to process each segment.&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; validCustomers = allCustomers&lt;strong&gt;.&lt;font color="#400080"&gt;&lt;font color="#000040"&gt;AsParallel()&lt;/font&gt;         &lt;br /&gt;&lt;/font&gt;&lt;/strong&gt;&amp;#160; .Where(c =&amp;gt; c.IsValid())     &lt;br /&gt;&amp;#160; .ToArray();&lt;/p&gt;  &lt;p&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PLINQ" border="0" alt="PLINQ" src="http://lh4.ggpht.com/_3OJ07UNFNWY/SzCjJfg6zSI/AAAAAAAAAI4/aEDyd3pICdg/PLINQ1.png?imgmax=800" width="563" height="251" /&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://files.jorgef.com.ar/code/PLINQ.zip"&gt;Here&lt;/a&gt; you can download the sample code.&lt;/p&gt;  &lt;p&gt;For more details I recommend you to watch the Igor Ostrovsky &lt;a href="http://microsoftpdc.com/Sessions/FT21"&gt;presentation&lt;/a&gt; in the PDC 2009 webpage.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-6700267504149933497?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/a9Z4rknRlKo" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-12-22T21:45:58.132+11:00</app:edited><media:thumbnail url="http://lh4.ggpht.com/_3OJ07UNFNWY/SzCjJfg6zSI/AAAAAAAAAI4/aEDyd3pICdg/s72-c/PLINQ1.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/6mE0iP_eS0I/PLINQ.zip" fileSize="24890" type="application/x-zip-compressed; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle> The version 4.0 of .Net has a new feature called “Parallel LINQ” or PLINQ. If you use LINQ to filter or process a large amount of objects in memory and/or it is required a high-cost evaluation, PLINQ is for you. PLINQ segments the source in parts and it </itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary> The version 4.0 of .Net has a new feature called “Parallel LINQ” or PLINQ. If you use LINQ to filter or process a large amount of objects in memory and/or it is required a high-cost evaluation, PLINQ is for you. PLINQ segments the source in parts and it uses different threads in order to process each segment. var validCustomers = allCustomers.AsParallel() &amp;#160; .Where(c =&amp;gt; c.IsValid()) &amp;#160; .ToArray(); Here you can download the sample code. For more details I recommend you to watch the Igor Ostrovsky presentation in the PDC 2009 webpage. </itunes:summary><itunes:keywords>.Net 4.0, PLINQ</itunes:keywords><feedburner:origLink>http://blog.jorgef.net/2009/12/using-plinq-to-improve-performance.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/6mE0iP_eS0I/PLINQ.zip" length="24890" type="application/x-zip-compressed; charset=UTF-8" /><feedburner:origEnclosureLink>http://files.jorgef.com.ar/code/PLINQ.zip</feedburner:origEnclosureLink></item><item><title>Entity Framework 4.0 - Foreign Key Relationships</title><link>http://feedproxy.google.com/~r/jorgef/~3/tOqV1ZGXPGQ/entity-framework-40-foreign-key.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Tue, 01 Dec 2009 16:33:13 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-2979461433988432106</guid><description>&lt;p&gt;The current version of EF (v3.5) maps table relationships as properties, hiding database foreign-key columns. However, there are some scenarios where you don’t need the entire referenced object to do some operation, you only need its “Id” (foreign key).&lt;/p&gt;  &lt;p&gt;For example, in a web application it is very common to use combo-boxes in order to assign relationships. In these scenarios, after a post-back it is necessary to re-create the model and its relationships (using combo-boxes “selected values”). Since you don’t have the referenced objects, you must get them from the database or use “&lt;a href="http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx"&gt;Stub Entities&lt;/a&gt;” to simulate them.&lt;/p&gt;  &lt;p&gt;To solve this problem, the version 4.0 will also allow you to map foreign-key columns as properties, making it easier.&lt;/p&gt;  &lt;p&gt;More info: &lt;a title="http://blogs.msdn.com/adonet/archive/2009/11/06/foreign-key-relationships-in-the-entity-framework.aspx" href="http://blogs.msdn.com/adonet/archive/2009/11/06/foreign-key-relationships-in-the-entity-framework.aspx"&gt;http://blogs.msdn.com/adonet/archive/2009/11/06/foreign-key-relationships-in-the-entity-framework.aspx&lt;/a&gt;.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-2979461433988432106?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/tOqV1ZGXPGQ" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-12-02T11:33:13.063+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2009/12/entity-framework-40-foreign-key.html</feedburner:origLink></item><item><title>WF Course</title><link>http://feedproxy.google.com/~r/jorgef/~3/yhHuhc5ZS90/wf-course.html</link><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 17 Dec 2009 03:07:17 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-1582992773101294286</guid><description>&lt;p&gt;Last week I was teaching a three days course about WF (Windows Workflow Foundation).&lt;/p&gt;  &lt;p&gt;The content was the following:&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Day One&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="WF" border="0" alt="WF" align="right" src="http://lh4.ggpht.com/_3OJ07UNFNWY/Sw5qWq73J7I/AAAAAAAAAIY/J5-_1NLfQmY/WF%5B3%5D.png?imgmax=800" width="244" height="185" /&gt;&lt;/strong&gt;     &lt;br /&gt;Introduction     &lt;br /&gt;Parameters     &lt;br /&gt;Conditions     &lt;br /&gt;Persistence     &lt;br /&gt;WebServices     &lt;br /&gt;LocalServices&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Day Two&lt;/strong&gt;     &lt;br /&gt;Errors     &lt;br /&gt;FaultHandlers     &lt;br /&gt;Transactions     &lt;br /&gt;Compensation     &lt;br /&gt;Compensation + Transaction&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Day Three&lt;/strong&gt;     &lt;br /&gt;Parallel Execution     &lt;br /&gt;WCF     &lt;br /&gt;Tracking     &lt;br /&gt;Custom Activities     &lt;br /&gt;WF v4 Overview     &lt;br /&gt;Questions&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://sites.google.com/site/jfioranelli/presentations/WindowsWorkflowFoundation.pptx"&gt;Here&lt;/a&gt; you can download the presentation (in Spanish).&lt;/p&gt;  &lt;p&gt;And here is the code: &lt;a href="http://sites.google.com/site/jfioranelli/code/WF-Day1.rar"&gt;DayOne&lt;/a&gt;, &lt;a href="http://sites.google.com/site/jfioranelli/code/WF-Day2.rar"&gt;DayTwo&lt;/a&gt; and &lt;a href="http://sites.google.com/site/jfioranelli/code/WF-Day3.rar"&gt;DayThree&lt;/a&gt;.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-1582992773101294286?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/yhHuhc5ZS90" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-12-17T22:07:17.607+11:00</app:edited><media:thumbnail url="http://lh4.ggpht.com/_3OJ07UNFNWY/Sw5qWq73J7I/AAAAAAAAAIY/J5-_1NLfQmY/s72-c/WF%5B3%5D.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/Vqs7513iGs0/WindowsWorkflowFoundation.pptx" fileSize="3144519" type="application/vnd.openxmlformats-officedocument.presentationml.presentation; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle> Last week I was teaching a three days course about WF (Windows Workflow Foundation). The content was the following: Day One Introduction Parameters Conditions Persistence WebServices LocalServices Day Two Errors FaultHandlers Transactions Compensation Co</itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary> Last week I was teaching a three days course about WF (Windows Workflow Foundation). The content was the following: Day One Introduction Parameters Conditions Persistence WebServices LocalServices Day Two Errors FaultHandlers Transactions Compensation Compensation + Transaction Day Three Parallel Execution WCF Tracking Custom Activities WF v4 Overview Questions &amp;#160; Here you can download the presentation (in Spanish). And here is the code: DayOne, DayTwo and DayThree. </itunes:summary><feedburner:origLink>http://blog.jorgef.net/2009/11/wf-course.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/Vqs7513iGs0/WindowsWorkflowFoundation.pptx" length="3144519" type="application/vnd.openxmlformats-officedocument.presentationml.presentation; charset=UTF-8" /><feedburner:origEnclosureLink>http://sites.google.com/site/jfioranelli/presentations/WindowsWorkflowFoundation.pptx</feedburner:origEnclosureLink></item><item><title>POCO in Entity Framework 4.0</title><link>http://feedproxy.google.com/~r/jorgef/~3/RaJxnz239iY/poco-in-entity-framework-40.html</link><category>.Net 4.0</category><category>Entity Framework</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Wed, 14 Oct 2009 04:44:49 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-3445358562622509286</guid><description>&lt;p&gt;The new version (4.0) of Entity Framework allows us to use “Plain Old CLR Objects” as entities. In the current version (3.5) every entity must inherit from EntityObject, but in the new version it is possible to use a simple POCO:&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;public class&lt;/font&gt; &lt;font color="#408080"&gt;Order&lt;/font&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;public&lt;/font&gt; &lt;font color="#408080"&gt;Guid&lt;/font&gt; Id { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;set&lt;/font&gt;; }     &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;public&lt;/font&gt; &lt;font color="#408080"&gt;Product&lt;/font&gt; Product { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;set&lt;/font&gt;; }     &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;public int&lt;/font&gt; Quantity { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;set&lt;/font&gt;; }&amp;#160; &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;In order to use this new feature it is necessary to follow these three steps:    &lt;br /&gt;1. Create the edmx file (ModelEntities).&amp;#160; &lt;br /&gt;2. Turn off the code generation removing the value of the “Custom Tool” property.     &lt;br /&gt;3. Create the context this way:&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;public class&lt;/font&gt; &lt;font color="#408080"&gt;ModelContext&lt;/font&gt; : &lt;font color="#408080"&gt;ObjectContext&lt;/font&gt;     &lt;br /&gt;{&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;public&lt;/font&gt; ModelContext() : &lt;font color="#0000ff"&gt;base&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;name=ModelEntities&amp;quot;&lt;/font&gt;, &lt;font color="#800000"&gt;&amp;quot;ModelEntities&amp;quot;&lt;/font&gt;)&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160; }&lt;/p&gt;  &lt;p&gt;&amp;#160; &lt;font color="#0000ff"&gt;public&lt;/font&gt; &lt;font color="#408080"&gt;ObjectSet&lt;/font&gt;&amp;lt;&lt;font color="#408080"&gt;Order&lt;/font&gt;&amp;gt; Orders     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return base&lt;/font&gt;.CreateObjectSet&amp;lt;&lt;font color="#408080"&gt;Order&lt;/font&gt;&amp;gt;(); }     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;More information:    &lt;br /&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/05/21/poco-in-the-entity-framework-part-1-the-experience.aspx"&gt;POCO in the Entity Framework: Part 1 - The Experience&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/05/28/poco-in-the-entity-framework-part-2-complex-types-deferred-loading-and-explicit-loading.aspx"&gt;POCO in the Entity Framework: Part 2 – Complex Types, Deferred Loading and Explicit Loading&lt;/a&gt;     &lt;br /&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/06/10/poco-in-the-entity-framework-part-3-change-tracking-with-poco.aspx"&gt;POCO in the Entity Framework: Part 3 – Change Tracking with POCO&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-3445358562622509286?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/RaJxnz239iY" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-10-14T22:44:49.228+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2009/10/poco-in-entity-framework-40.html</feedburner:origLink></item><item><title>Default Endpoints in WCF 4.0</title><link>http://feedproxy.google.com/~r/jorgef/~3/haqwSmNKNvs/default-endpoints-in-wcf-40.html</link><category>.Net 4.0</category><category>WCF</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Sun, 11 Oct 2009 11:53:46 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-7679470580892150223</guid><description>&lt;p&gt;One of the hardest things in WCF is its configuration. When you try to host a service without an endpoint declared in the configuration, an exception is thrown (a classic mistake).&lt;/p&gt;  &lt;p&gt;But this will change with the new version of the framework (in fact it has already changed in the beta 1).&lt;/p&gt;  &lt;p&gt;When you are hosting a service without any endpoint configured, the ServiceHost will read the service’s Uri and will create a default endpoint choosing one of de following bindings:    &lt;br /&gt;- http: basicHttpBinding     &lt;br /&gt;- net.tcp: netTcpBinding     &lt;br /&gt;- net.pipe: netNamedPipeBinding     &lt;br /&gt;- net.msmq: netMsmqBinding&lt;/p&gt;  &lt;p&gt;More information: &lt;a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx#_Simplified_Configuration"&gt;A Developer’s Introduction to Windows Communication Foundation (WCF) .NET 4 Beta 1&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-7679470580892150223?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/haqwSmNKNvs" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-10-12T05:53:46.225+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2009/10/default-endpoints-in-wcf-40.html</feedburner:origLink></item><item><title>Mocking WCF Services</title><link>http://feedproxy.google.com/~r/jorgef/~3/Wuqpo1WldL4/mocking-wcf-services.html</link><category>Mocks</category><category>IOC</category><category>WCF</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Sat, 10 Oct 2009 17:53:24 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-4841769080958910344</guid><description>&lt;p&gt;In my last &lt;a href="http://blog.jorgef.com.ar/2009/09/using-servicelocator-to-call-wcf.html"&gt;post&lt;/a&gt; I showed how to decouple the service consumer from the service proxy using the ServiceLocator pattern.&lt;/p&gt;  &lt;p&gt;In order to mock the WCF service, it is necessary to create the following ServiceClientStub:&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;public class&lt;/font&gt; &lt;font color="#408080"&gt;ServiceClientStub&lt;/font&gt;&amp;lt;TServiceInterface&amp;gt; : &lt;font color="#408080"&gt;IServiceClient&lt;/font&gt;&amp;lt;TServiceInterface&amp;gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;where&lt;/font&gt; TServiceInterface : &lt;font color="#0000ff"&gt;class&lt;/font&gt;     &lt;br /&gt;{    &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;private&lt;/font&gt; TServiceInterface serviceMock; &lt;/p&gt;  &lt;p&gt;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;ServiceClientStub(TServiceInterface serviceMock)    &lt;br /&gt;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;.serviceMock = serviceMock;    &lt;br /&gt;&amp;#160; } &lt;/p&gt;  &lt;p&gt;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;TServiceInterface Service&amp;#160; &lt;br /&gt;&amp;#160; {    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return&lt;/font&gt; serviceMock; }    &lt;br /&gt;&amp;#160; } &lt;/p&gt;  &lt;p&gt;&amp;#160; &lt;font color="#0000ff"&gt;public void&lt;/font&gt; Dispose() { }    &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;This allows you to test the service consumer without the service implementation (using &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt;):&lt;/p&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; result = ...    &lt;br /&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; mock = &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#408080"&gt;Mock&lt;/font&gt;&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;();    &lt;br /&gt;mock.Setup(s =&amp;gt; s.Operation()).Returns(result);    &lt;br /&gt;&lt;font color="#408080"&gt;ServiceLocator&lt;/font&gt;.Register&amp;lt;&lt;font color="#408080"&gt;IServiceClient&lt;/font&gt;&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;&amp;gt;(    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; () =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#408080"&gt;ServiceClientStub&lt;/font&gt;&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;(mock.Object));&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-4841769080958910344?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/Wuqpo1WldL4" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-10-11T11:53:24.476+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2009/09/mocking-wcf-services.html</feedburner:origLink></item><item><title>Using ServiceLocator to call a WCF Service</title><link>http://feedproxy.google.com/~r/jorgef/~3/MkNiR5WnAcQ/using-servicelocator-to-call-wcf.html</link><category>IOC</category><category>WCF</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Mon, 19 Oct 2009 04:41:35 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-6316388744795236540</guid><description>&lt;p&gt;In my last &lt;a href="http://blog.jorgef.com.ar/2009/08/simple-servicelocator-with-support-for.html"&gt;post&lt;/a&gt;, I published a simple ServiceLocator, it may help you to decouple the service consumer from service proxy.&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;To do this, it is necessary to create a generic interface:&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;public interface&lt;/font&gt; &lt;font color="#408080"&gt;IServiceClient&lt;/font&gt;&amp;lt;TServiceInterface&amp;gt; : &lt;font color="#408080"&gt;IDisposable &lt;/font&gt;    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;where&lt;/font&gt; TServiceInterface : &lt;font color="#0000ff"&gt;class&lt;/font&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160; TServiceInterface Service { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }     &lt;br /&gt;}&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;And it is the implementation using the ClientBase of WCF:&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;public class&lt;/font&gt; &lt;font color="#408080"&gt;ServiceClient&lt;/font&gt;&amp;lt;TServiceInterface&amp;gt; :     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#408080"&gt;ClientBase&lt;/font&gt;&amp;lt;TServiceInterface&amp;gt;,     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#408080"&gt;IServiceClient&lt;/font&gt;&amp;lt;TServiceInterface&amp;gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;where&lt;/font&gt; TServiceInterface : &lt;font color="#0000ff"&gt;class&lt;/font&gt;     &lt;br /&gt;{     &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;public&lt;/font&gt; TServiceInterface Service     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return base&lt;/font&gt;.Channel; }     &lt;br /&gt;&amp;#160; } &lt;/p&gt;  &lt;p&gt;&amp;#160; &lt;font color="#0000ff"&gt;void&lt;/font&gt; &lt;font color="#408080"&gt;IDisposable&lt;/font&gt;.Dispose()     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;try&lt;/font&gt;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;base&lt;/font&gt;.Close();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;catch&lt;/font&gt; (&lt;font color="#408080"&gt;CommunicationException&lt;/font&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;base&lt;/font&gt;.Abort();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;catch&lt;/font&gt; (&lt;font color="#408080"&gt;TimeoutException&lt;/font&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;base&lt;/font&gt;.Abort();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;catch&lt;/font&gt; (&lt;font color="#408080"&gt;Exception&lt;/font&gt;)     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;base&lt;/font&gt;.Abort();     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;throw&lt;/font&gt;;     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;}&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;Then, you can register and use the ServiceClient this way:&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;&lt;font color="#008000"&gt;// Service Registration&lt;/font&gt;     &lt;br /&gt;&lt;font color="#408080"&gt;ServiceLocator&lt;/font&gt;.Register&amp;lt;&lt;font color="#408080"&gt;IServiceClient&lt;/font&gt;&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;&amp;gt;(() =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#408080"&gt;ServiceClient&lt;/font&gt;&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;());&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008000"&gt;// Service Resolving&lt;/font&gt;     &lt;br /&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; (&lt;font color="#0000ff"&gt;var&lt;/font&gt; client = &lt;font color="#408080"&gt;ServiceLocator&lt;/font&gt;.Resolve&amp;lt;&lt;font color="#408080"&gt;IServiceClient&lt;/font&gt;&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;&amp;gt;())     &lt;br /&gt;{     &lt;br /&gt;&amp;#160; client.Service.Operation();     &lt;br /&gt;}&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-6316388744795236540?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/MkNiR5WnAcQ" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-10-19T22:41:35.899+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2009/09/using-servicelocator-to-call-wcf.html</feedburner:origLink></item><item><title>A simple ServiceLocator with support for WCF, Web and Thread contexts</title><link>http://feedproxy.google.com/~r/jorgef/~3/usaHlMA_eBI/simple-servicelocator-with-support-for.html</link><category>IOC</category><category>WCF</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Fri, 09 Oct 2009 05:01:44 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-7739634343880908477</guid><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;Last week I wrote a very simple ServiceLocator that supports single and multiple instances. It has three different containers:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;- WCF: It supports single instances on the same OperationContext.    &lt;br /&gt;- Web: It supports single instances on the same HttpContext.     &lt;br /&gt;- Thread: It supports single instances on the same Thread. &lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;Every container implements the ISingleInstanceContainer interface:&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;&lt;font color="#0000ff"&gt;interface&lt;/font&gt; &lt;font color="#408080"&gt;ISingleInstanceContainer&lt;/font&gt;     &lt;br /&gt;{     &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160; bool&lt;/font&gt; IsSuitable { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; }     &lt;br /&gt;&amp;#160; T Register&amp;lt;T&amp;gt;(T instance);     &lt;br /&gt;&amp;#160; T Resolve&amp;lt;T&amp;gt;();     &lt;br /&gt;}&lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;The IsSuitable method evaluates if the context is suitable for every container:&lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#408080"&gt;SingleInstanceWcfContainer&lt;/font&gt; : &lt;font color="#408080"&gt;ISingleInstanceContainer &lt;/font&gt;    &lt;br /&gt;{     &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160; public bool&lt;/font&gt; IsSuitable     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return&lt;/font&gt; &lt;font color="#408080"&gt;OperationContext&lt;/font&gt;.Current != &lt;font color="#0000ff"&gt;null&lt;/font&gt;; }     &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; ...     &lt;br /&gt;} &lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#408080"&gt;SingleInstanceWebContainer&lt;/font&gt; : &lt;font color="#408080"&gt;ISingleInstanceContainer&lt;/font&gt;     &lt;br /&gt;{     &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160; public bool&lt;/font&gt; IsSuitable     &lt;br /&gt;&amp;#160; {     &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; get&lt;/font&gt; { &lt;font color="#0000ff"&gt;return&lt;/font&gt; &lt;font color="#408080"&gt;HttpContext&lt;/font&gt;.Current != &lt;font color="#0000ff"&gt;null&lt;/font&gt;; }&amp;#160; &lt;br /&gt;&amp;#160; }     &lt;br /&gt;&amp;#160; ...     &lt;br /&gt;} &lt;/p&gt;  &lt;br /&gt;  &lt;p&gt;In the following example, you can see how to register the ServiceA as “multiple instances” and the ServiceB as “single instance”:&lt;/p&gt;  &lt;p&gt;   &lt;br /&gt;&lt;font color="#008000"&gt;// Multiple Instances Registration&lt;/font&gt;     &lt;br /&gt;&lt;font color="#408080"&gt;ServiceLocator&lt;/font&gt;.Register&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;&lt;iservicea&gt;(() =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#408080"&gt;ServiceA&lt;/font&gt;());     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008000"&gt;// Single Instance Registration &lt;/font&gt;    &lt;br /&gt;&lt;font color="#408080"&gt;ServiceLocator&lt;/font&gt;.Register&amp;lt;&lt;font color="#408080"&gt;IServiceB&lt;/font&gt;&amp;gt;&lt;iserviceb&gt;(() =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; &lt;font color="#408080"&gt;ServiceB&lt;/font&gt;()).SingleInstance();     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008000"&gt;// Resolving Instances &lt;/font&gt;    &lt;br /&gt;&lt;font color="#408080"&gt;IServiceA &lt;/font&gt;serviceA = &lt;font color="#408080"&gt;ServiceLocator&lt;/font&gt;.Resolve&amp;lt;&lt;font color="#408080"&gt;IServiceA&lt;/font&gt;&amp;gt;&lt;iservicea&gt;();     &lt;br /&gt;&lt;font color="#408080"&gt;IServiceB &lt;/font&gt;serviceB = &lt;font color="#408080"&gt;ServiceLocator&lt;/font&gt;.Resolve&amp;lt;&lt;font color="#408080"&gt;IServiceB&lt;/font&gt;&amp;gt;&lt;iserviceb&gt;(); &lt;/p&gt;  &lt;br /&gt;&lt;a href="http://files.jorgef.com.ar/code/ServiceLocator.zip"&gt;Here&lt;/a&gt; you can download the code.   &lt;br /&gt;.     &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-7739634343880908477?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/usaHlMA_eBI" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-10-09T23:01:44.498+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/jorgef/~5/8941rVFj7Qw/ServiceLocator.zip" fileSize="26604" type="application/x-zip-compressed; charset=UTF-8" /><itunes:explicit>no</itunes:explicit><itunes:subtitle> Last week I wrote a very simple ServiceLocator that supports single and multiple instances. It has three different containers: - WCF: It supports single instances on the same OperationContext. - Web: It supports single instances on the same HttpContext. </itunes:subtitle><itunes:author>noreply@blogger.com (Jorge Fioranelli)</itunes:author><itunes:summary> Last week I wrote a very simple ServiceLocator that supports single and multiple instances. It has three different containers: - WCF: It supports single instances on the same OperationContext. - Web: It supports single instances on the same HttpContext. - Thread: It supports single instances on the same Thread. Every container implements the ISingleInstanceContainer interface: interface ISingleInstanceContainer { &amp;#160; bool IsSuitable { get; } &amp;#160; T Register&amp;lt;T&amp;gt;(T instance); &amp;#160; T Resolve&amp;lt;T&amp;gt;(); } The IsSuitable method evaluates if the context is suitable for every container: class SingleInstanceWcfContainer : ISingleInstanceContainer { &amp;#160; public bool IsSuitable &amp;#160; { &amp;#160;&amp;#160;&amp;#160; get { return OperationContext.Current != null; } &amp;#160; } &amp;#160; ... } class SingleInstanceWebContainer : ISingleInstanceContainer { &amp;#160; public bool IsSuitable &amp;#160; { &amp;#160;&amp;#160;&amp;#160; get { return HttpContext.Current != null; }&amp;#160; &amp;#160; } &amp;#160; ... } In the following example, you can see how to register the ServiceA as “multiple instances” and the ServiceB as “single instance”: // Multiple Instances Registration ServiceLocator.Register&amp;lt;IServiceA&amp;gt;(() =&amp;gt; new ServiceA()); // Single Instance Registration ServiceLocator.Register&amp;lt;IServiceB&amp;gt;(() =&amp;gt; new ServiceB()).SingleInstance(); // Resolving Instances IServiceA serviceA = ServiceLocator.Resolve&amp;lt;IServiceA&amp;gt;(); IServiceB serviceB = ServiceLocator.Resolve&amp;lt;IServiceB&amp;gt;(); Here you can download the code. . </itunes:summary><itunes:keywords>IOC, WCF</itunes:keywords><feedburner:origLink>http://blog.jorgef.net/2009/08/simple-servicelocator-with-support-for.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/jorgef/~5/8941rVFj7Qw/ServiceLocator.zip" length="26604" type="application/x-zip-compressed; charset=UTF-8" /><feedburner:origEnclosureLink>http://files.jorgef.com.ar/code/ServiceLocator.zip</feedburner:origEnclosureLink></item><item><title>Mocking Views</title><link>http://feedproxy.google.com/~r/jorgef/~3/tvcXb61OEC8/mocking-views.html</link><category>MVC</category><category>Mocks</category><author>noreply@blogger.com (Jorge Fioranelli)</author><pubDate>Thu, 23 Jul 2009 08:51:30 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-3109374999835349472.post-8379574379445769007</guid><description>&lt;p&gt;In my last &lt;a href="http://blog.jorgef.com.ar/2009/06/simple-mvc-implementation-for-aspnet.html"&gt;post&lt;/a&gt;, I've shown how to implement a simple MVC over ASP.NET.&lt;/p&gt;  &lt;p&gt;As you can see in the picture, every View implements an interface which exposes the events and methods of the View.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh3.ggpht.com/_3OJ07UNFNWY/SmhHDRA1ByI/AAAAAAAAAII/eYq7WBBcOhE/s1600-h/View5.png"&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="View" border="0" alt="View" src="http://lh6.ggpht.com/_3OJ07UNFNWY/SmhHELg1aSI/AAAAAAAAAIM/Hm1Glj5VidY/View_thumb3.png?imgmax=800" width="128" height="175" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;The Controller uses the View’s interface, so it is possible to mock the View in order to test the Controller without the aspx page running.&lt;/p&gt;  &lt;p&gt;In the example of the last &lt;a href="http://blog.jorgef.com.ar/2009/06/simple-mvc-implementation-for-aspnet.html"&gt;post&lt;/a&gt;, the View’s interface exposes these members: &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;span style="color: #0000ff"&gt;internal&lt;/span&gt; &lt;span style="color: #0000ff"&gt;interface&lt;/span&gt; &lt;span style="color: #008080"&gt;ICustomersView&lt;/span&gt;     &lt;br /&gt;{     &lt;br /&gt;&lt;span style="color: #0000ff"&gt;&amp;#160; event&lt;/span&gt; &lt;span style="color: #008080"&gt;EventHandler&lt;/span&gt;&amp;lt;&lt;span style="color: #008080"&gt;GenericEventArgs&lt;/span&gt;&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;&amp;gt; FindCustomer;     &lt;br /&gt;&lt;span style="color: #0000ff"&gt;&amp;#160; void&lt;/span&gt; FillCustomers(&lt;span style="color: #008080"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #008080"&gt;Customer&lt;/span&gt;&amp;gt; customers);     &lt;br /&gt;}&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;So, you can mock the View and raise the FindCustomer event this way (I am using the &lt;a href="http://code.google.com/p/moq/"&gt;MOQ&lt;/a&gt; library):&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;span style="color: #008080"&gt;&lt;/span&gt;&lt;/p&gt;  &lt;p&gt;&lt;span style="color: #008080"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #008080"&gt;ICustomerView&lt;/span&gt;&amp;gt; mock = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #008080"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #008080"&gt;ICustomerView&lt;/span&gt;&amp;gt;();&lt;/p&gt;  &lt;p&gt;&lt;span style="color: #008080"&gt;CustomersController&lt;/span&gt; controller = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; &lt;span style="color: #008080"&gt;CustomersController&lt;/span&gt;(mock.Object);&lt;/p&gt;  &lt;p&gt;mock.Raise(v =&amp;gt; v.FindCustomer+= &lt;span style="color: #0000ff"&gt;null&lt;/span&gt;, &lt;/p&gt;  &lt;p&gt;&lt;span style="color: #0000ff"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; new&lt;/span&gt; &lt;span style="color: #008080"&gt;GenericEventArgs&lt;/span&gt;&amp;lt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;&amp;gt;(searchPattern));&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3109374999835349472-8379574379445769007?l=blog.jorgef.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/jorgef/~4/tvcXb61OEC8" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2009-07-24T01:51:30.502+10:00</app:edited><media:thumbnail url="http://lh6.ggpht.com/_3OJ07UNFNWY/SmhHELg1aSI/AAAAAAAAAIM/Hm1Glj5VidY/s72-c/View_thumb3.png?imgmax=800" height="72" width="72" /><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://blog.jorgef.net/2009/07/mocking-views.html</feedburner:origLink></item><media:rating>nonadult</media:rating></channel></rss>

